Repository Public
1// SP Drive iOS2// File: App/NextCenter.swift3// Description: SP Drive 2.0 in the app: the client of the shared `SPDriveNext` package, and what the server announced it can do4// (`GET /meta`). A screen or a control exists only when its feature is announced — nothing is shown that cannot work.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Observation10import SPDriveNext11import SwiftUI1213@MainActor @Observable14final class NextCenter {15 let client: NextClient16 /// What the server can do. Starts from what it said last time (the app also opens offline), then refreshed at sign-in and when the app comes to the front.17 private(set) var meta: ServerMeta18 private(set) var providers: AIProviders?1920 init(api: DriveAPI) {21 client = api.next()22 if let data = UserDefaults.standard.data(forKey: "next.meta"), let saved = try? JSONDecoder().decode(ServerMeta.self, from: data) { meta = saved } else { meta = .v1 }23 #if DEBUG24 // UI tests check that a 1.0 server hides every 2.0 control25 if ProcessInfo.processInfo.environment["SPDRIVE_FORCE_V1"] == "1" { meta = .v1 }26 #endif27 }2829 func has(_ feature: ServerMeta.Feature) -> Bool { meta.has(feature) }3031 /// Asks the server what it can do. Returns true when the answer changed.32 @discardableResult33 func refresh() async -> Bool {34 #if DEBUG35 if ProcessInfo.processInfo.environment["SPDRIVE_FORCE_V1"] == "1" { return false }36 #endif37 guard let fresh = try? await client.capabilities(), fresh != meta else { return false }38 meta = fresh39 UserDefaults.standard.set(try? JSONEncoder().encode(fresh), forKey: "next.meta")40 return true41 }4243 func refreshProviders() async { if has(.ai) { providers = try? await client.aiProviders() } }4445 func forget() { meta = .v1; providers = nil; UserDefaults.standard.removeObject(forKey: "next.meta") }4647 /// A message for the user from an error of the 2.0 calls.48 static func describe(_ error: Error) -> String {49 guard let e = error as? NextError else { return AppModel.describe(error) }50 switch e {51 case .offline: return String(localized: "MacLustr est injoignable. Vérifie ta connexion.")52 case .unauthenticated: return String(localized: "Session expirée. Connecte-toi à nouveau.")53 case .cancelled: return String(localized: "Annulé.")54 case .invalidResponse: return String(localized: "Réponse inattendue du serveur.")55 case .server(let status, let code, let message, _):56 switch code {57 case "forbidden": return String(localized: "Ton rôle dans ce dossier partagé ne permet pas cette action.")58 case "not_found": return String(localized: "Cet élément n’existe plus, ou ne t’est plus partagé.")59 case "name_conflict": return String(localized: "Ce nom est déjà utilisé.")60 case "quota_exceeded": return String(localized: "Espace de stockage insuffisant.")61 case "rate_limited": return String(localized: "Trop de requêtes. Réessaie dans un instant.")62 case "too_many_pending_uploads": return String(localized: "Trop d’envois inachevés dans ce dossier partagé. Termine ou annule les envois en cours, puis réessaie.")63 case "busy", "too_many_streams": return String(localized: "Le serveur est occupé. Réessaie dans un instant.")64 case "ai_unavailable": return String(localized: "Aucun fournisseur d’IA n’est configuré sur ce serveur.")65 case "ai_external_disabled": return String(localized: "Ce fournisseur est externe : autorise les fournisseurs externes dans Paramètres, si le serveur le permet.")66 case "provider_not_configured": return String(localized: "Ce fournisseur n’est pas configuré sur le serveur.")67 default: return message.isEmpty ? String(localized: "Le serveur a refusé l’opération (\(status)).") : String(localized: "Le serveur a refusé l’opération (\(message)).")68 }69 }70 }71}7273extension AppModel {74 /// Runs a 2.0 action; a failure is shown instead of being swallowed.75 func performNext(success: String? = nil, _ action: () async throws -> Void) async {76 do {77 try await action()78 if let success { toast = Toast(text: success, style: .success) }79 } catch is CancellationError {80 } catch let e as NextError where e == .cancelled {81 } catch {82 Haptics.error()83 toast = Toast(text: NextCenter.describe(error), style: .error)84 }85 }86}8788/// Loading state shared by the 2.0 screens.89enum Loadable<T> {90 case loading, loaded(T), failed(String)91 var value: T? { if case .loaded(let v) = self { return v }; return nil }92}9394/// A screen body that loads something from the server: progress, the content, or the reason it could not be loaded with a retry.95struct LoadingView<T, Content: View>: View {96 let state: Loadable<T>97 let retry: () async -> Void98 @ViewBuilder let content: (T) -> Content99 var body: some View {100 switch state {101 case .loading: ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)102 case .loaded(let v): content(v)103 case .failed(let message):104 EmptyState(symbol: "exclamationmark.icloud", title: String(localized: "Indisponible"), message: message, action: (String(localized: "Réessayer"), { Task { await retry() } }))105 }106 }107}108109extension NextFile {110 var fileKind: FileKind { FileKind(extension: fileExtension) }111}112