Commit d98b20b4 authored by Kourser's avatar Kourser
Browse files

Synchronisation Nextcloud au premier plan

Application :
- appairage par Login Flow v2 ou mot de passe d'application, choix du
  dossier distant, secret au trousseau (SEC-01) ;
- SyncController : une synchronisation à la fois, au retour dans
  l'application et après chaque modification du coffre ; révocation
  détectée et reconnexion préremplie (EF-SYN-13) ;
- état de sauvegarde par souvenir (EF-BIB-08) et écran de réglages.

Cœur :
- la corbeille locale suit le même chemin sur le serveur et y est purgée à
  la même échéance : un mémo mis à la corbeille n'est plus réadopté ;
- modifications locales détectées par empreinte : une édition non signalée
  n'est plus écrasée par une modification distante ;
- l'ancien audio d'un mémo converti est supprimé du serveur une fois le
  nouveau vérifié ;
- racine WebDAV comparée sous forme décodée.

Écarts trouvés contre Nextcloud 34.0.3 et corrigés : rapport différentiel
en 404 sur un dossier absent et en 415 sur l'arbre des fichiers, découpage
annoncé sous dav.chunking, ETag suffixé de -gzip sur un téléchargement
compressé.

Tests : planificateur, relevé distant, saisie d'appairage, moteur contre le
faux serveur, et EnvorennLiveTests contre un serveur réel, ignorés sans
ENVORENN_LIVE_TESTS=1.

Co-Authored-By: default avatarClaude Opus 5 <noreply@anthropic.com>
parent 2b39a443
Loading
Loading
Loading
Loading
+12
Changes for App/EnvorennApp.swift: 12 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -4,10 +4,13 @@ import EnvorennCore
@main
struct EnvorennApp: App {

    @Environment(\.scenePhase) private var scenePhase

    @State private var environment: AppEnvironment
    @State private var recorder: RecordingController
    @State private var playback: PlaybackController
    @State private var vault: VaultController
    @State private var sync: SyncController

    init() {
        let environment = AppEnvironment.live()
@@ -22,6 +25,7 @@ struct EnvorennApp: App {
        ))
        _playback = State(initialValue: PlaybackController(session: session))
        _vault = State(initialValue: VaultController(environment: environment))
        _sync = State(initialValue: SyncController(environment: environment))
    }

    var body: some Scene {
@@ -31,6 +35,14 @@ struct EnvorennApp: App {
                .environment(recorder)
                .environment(playback)
                .environment(vault)
                .environment(sync)
        }
        .onChange(of: scenePhase) { _, phase in
            // Faute de tâche de fond pour l'instant, le retour dans l'application
            // est l'occasion de rattraper ce qui n'a pas pu partir.
            if phase == .active {
                sync.synchronize()
            }
        }
    }
}
+16 −4
Changes for App/Features/LibraryModel.swift: 16 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -29,11 +29,13 @@ final class LibraryModel {

    private let environment: AppEnvironment
    private let vault: VaultController
    private let sync: SyncController
    private let finalizer: RecordingFinalizer

    init(environment: AppEnvironment, vault: VaultController) {
    init(environment: AppEnvironment, vault: VaultController, sync: SyncController) {
        self.environment = environment
        self.vault = vault
        self.sync = sync
        self.finalizer = RecordingFinalizer(
            layout: environment.layout,
            store: environment.store,
@@ -70,6 +72,9 @@ final class LibraryModel {

        let outcome = await finalizer.finalizePending(sealing: sealing)
        recoveredCount = outcome.recovered.count
        for memo in outcome.recovered {
            sync.noteLocalChange(memo.id)
        }
        recoveredInClearCount = (wantedEncryption && sealing == nil) ? outcome.recovered.count : 0
        if !outcome.failed.isEmpty {
            errorMessage = "\(outcome.failed.count) enregistrement(s) n'ont pas pu être finalisés. "
@@ -97,8 +102,9 @@ final class LibraryModel {
    func finalize(_ recording: PendingRecording, encrypt: Bool? = nil) async {
        do {
            let sealing = (encrypt == false) ? nil : sealingContext()
            _ = try await finalizer.finalize(recording, sealing: sealing)
            let memo = try await finalizer.finalize(recording, sealing: sealing)
            reload()
            sync.noteLocalChange(memo.id)
        } catch {
            errorMessage = "L'enregistrement n'a pas pu être finalisé : \(error.localizedDescription). "
                + "Il est conservé et sera retenté au prochain lancement."
@@ -224,6 +230,7 @@ final class LibraryModel {
            if let index = memos.firstIndex(where: { $0.id == updated.id }) {
                memos[index] = updated
            }
            sync.noteLocalChange(updated.id)
        } catch {
            errorMessage = "Modification impossible : \(error.localizedDescription)"
        }
@@ -251,6 +258,7 @@ final class LibraryModel {
            } else {
                reload()
            }
            sync.noteLocalChange(converted.id)
        } catch {
            // Une conversion qui échoue laisse le mémo intact — c'est garanti
            // par l'ordre des écritures dans MemoConverter. On recharge tout de
@@ -264,6 +272,7 @@ final class LibraryModel {
        do {
            try environment.store.moveToTrash(memo, at: environment.clock.now)
            memos.removeAll { $0.id == memo.id }
            sync.noteLocalChange()
        } catch {
            errorMessage = "Suppression impossible : \(error.localizedDescription)"
        }
@@ -280,9 +289,11 @@ final class TrashModel {
    var errorMessage: String?

    private let environment: AppEnvironment
    private let sync: SyncController

    init(environment: AppEnvironment) {
    init(environment: AppEnvironment, sync: SyncController) {
        self.environment = environment
        self.sync = sync
    }

    func reload() {
@@ -295,8 +306,9 @@ final class TrashModel {

    func restore(_ memo: Memo) {
        do {
            _ = try environment.store.restore(memo)
            let restored = try environment.store.restore(memo)
            memos.removeAll { $0.id == memo.id }
            sync.noteLocalChange(restored.id)
        } catch {
            errorMessage = "Restauration impossible : \(error.localizedDescription)"
        }
+53 −5
Changes for App/Features/LibraryView.swift: 53 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -6,11 +6,13 @@ struct LibraryView: View {
    @Environment(AppEnvironment.self) private var environment
    @Environment(PlaybackController.self) private var playback
    @Environment(VaultController.self) private var vault
    @Environment(SyncController.self) private var sync

    @State private var model: LibraryModel?
    @State private var isRecording = false
    @State private var showTrash = false
    @State private var showVault = false
    @State private var showSync = false

    var body: some View {
        NavigationStack {
@@ -31,6 +33,14 @@ struct LibraryView: View {
                    }
                    .tint(vault.state == .locked ? .orange : nil)
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Button {
                        showSync = true
                    } label: {
                        SyncToolbarLabel(phase: sync.phase)
                    }
                    .tint(sync.phase.needsAttention ? .orange : nil)
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Button {
                        showTrash = true
@@ -39,8 +49,11 @@ struct LibraryView: View {
                    }
                }
            }
            .sheet(isPresented: $showTrash) {
                TrashView(environment: environment)
            .sheet(isPresented: $showTrash, onDismiss: { model?.reload() }) {
                TrashView(environment: environment, sync: sync)
            }
            .sheet(isPresented: $showSync) {
                SyncSettingsView(memos: model?.memos ?? [])
            }
            .sheet(isPresented: $showVault) {
                VaultSettingsView()
@@ -62,11 +75,15 @@ struct LibraryView: View {
                    guard let vault else { throw PlaybackController.PlaybackError.vaultLocked }
                    return try vault.openAudio(of: memo)
                }
                let created = LibraryModel(environment: environment, vault: vault)
                let created = LibraryModel(environment: environment, vault: vault, sync: sync)
                model = created
                await created.load()
            }
        }
        .onChange(of: sync.vaultRevision) {
            // Une synchronisation a déposé ou fusionné des souvenirs.
            model?.reload()
        }
    }

    private var vaultIcon: String {
@@ -119,6 +136,27 @@ struct LibraryView: View {
                    }
                }

                if sync.phase == .needsReconnection {
                    Section {
                        Button {
                            showSync = true
                        } label: {
                            HStack(spacing: 10) {
                                Image(systemName: "exclamationmark.arrow.triangle.2.circlepath")
                                    .foregroundStyle(.orange)
                                VStack(alignment: .leading, spacing: 2) {
                                    Text("Reconnexion à Nextcloud nécessaire")
                                        .font(.subheadline.weight(.medium))
                                    Text("Vos souvenirs restent sur cet appareil. Ils repartiront dès que l'accès sera rétabli.")
                                        .font(.caption)
                                        .foregroundStyle(.secondary)
                                }
                            }
                        }
                        .buttonStyle(.plain)
                    }
                }

                if model.recoveredCount > 0 {
                    Section {
                        Label(
@@ -148,7 +186,8 @@ struct LibraryView: View {
                                    title: model.displayTitle(of: memo),
                                    isTitleHidden: model.isTitleHidden(of: memo),
                                    tags: model.readableFields(of: memo).tags,
                                    isPlaying: playback.currentID == memo.id
                                    isPlaying: playback.currentID == memo.id,
                                    backup: sync.status(of: memo)
                                )
                            }
                            .swipeActions(edge: .trailing) {
@@ -173,7 +212,10 @@ struct LibraryView: View {
            }
            .listStyle(.insetGrouped)
            .searchable(text: $model.searchText, prompt: "Rechercher")
            .refreshable { model.reload() }
            .refreshable {
                model.reload()
                sync.synchronize()
            }

            RecordButton { isRecording = true }
                .padding(.bottom, 24)
@@ -189,6 +231,7 @@ private struct MemoRow: View {
    let isTitleHidden: Bool
    let tags: [String]
    let isPlaying: Bool
    let backup: MemoBackupStatus?

    private var icon: String {
        if isPlaying { return "waveform.circle.fill" }
@@ -219,6 +262,11 @@ private struct MemoRow: View {
                .foregroundStyle(.secondary)
                .monospacedDigit()
            }

            if let backup {
                Spacer(minLength: 8)
                BackupBadge(status: backup)
            }
        }
        .padding(.vertical, 2)
    }
+4
Changes for App/Features/MemoDetailView.swift: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,7 @@ struct MemoDetailView: View {

    @Environment(PlaybackController.self) private var playback
    @Environment(VaultController.self) private var vault
    @Environment(SyncController.self) private var sync
    @Environment(\.dismiss) private var dismiss

    @State private var title: String = ""
@@ -60,6 +61,9 @@ struct MemoDetailView: View {
                               value: DurationFormat.short(milliseconds: memo.metadata.durationMs))
                LabeledContent("Format", value: memo.metadata.audio.codec.uppercased())
                LabeledContent("Chiffrement", value: encryptionLabel)
                if let backup = sync.status(of: memo) {
                    LabeledContent("Sauvegarde", value: backup.label)
                }
                LabeledContent("Taille", value: ByteFormat.string(memo.metadata.audio.bytes))
                LabeledContent("Identifiant", value: memo.id.rawValue)
                    .font(.footnote.monospaced())
+333
Changes for App/Features/Sync/PairingView.swift: 333 added lines, 0 removed lines.
Original line number Diff line number Diff line
import SwiftUI
import EnvorennCore

/// Appairage d'un Nextcloud (EF-SYN-01 à 04).
///
/// Trois temps : l'adresse du serveur, l'obtention d'un mot de passe
/// d'application — par le navigateur de préférence, par saisie en repli — puis
/// le choix du dossier. Rien n'est enregistré avant la dernière étape.
struct PairingView: View {

    /// Compte dont on reprend l'adresse, le nom et le dossier lors d'une
    /// reconnexion (EF-SYN-13).
    let reconnecting: NextcloudAccount?

    @Environment(SyncController.self) private var sync
    @Environment(\.dismiss) private var dismiss

    private enum Step {
        case address
        case manual
        case folder(NextcloudCredentials, NextcloudCapabilities)
    }

    @State private var step: Step = .address
    @State private var address = ""
    @State private var loginName = ""
    @State private var appPassword = ""
    @State private var remoteRoot = RemoteFolder.defaultPath
    @State private var folders: [String] = []
    @State private var isWorking = false
    @State private var errorMessage: String?
    @State private var work: Task<Void, Never>?
    @State private var didPrefill = false

    var body: some View {
        NavigationStack {
            Form {
                switch step {
                case .address:
                    addressStep
                case .manual:
                    manualStep
                case .folder(let credentials, let capabilities):
                    folderStep(credentials, capabilities)
                }

                if let errorMessage {
                    Section {
                        WarningRow(message: errorMessage)
                    }
                }
            }
            .navigationTitle(title)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button("Annuler") {
                        work?.cancel()
                        dismiss()
                    }
                }
            }
            .interactiveDismissDisabled(isWorking)
        }
        .onAppear(perform: prefill)
        .onDisappear { work?.cancel() }
    }

    // MARK: - Étapes

    @ViewBuilder
    private var addressStep: some View {
        Section {
            addressField
                .submitLabel(.continue)
                .onSubmit(connectWithBrowser)
        } header: {
            Text("Adresse du serveur")
        } footer: {
            Text("L'adresse que vous tapez pour ouvrir Nextcloud dans un navigateur. La connexion doit être chiffrée (https).")
        }

        Section {
            if isWorking {
                HStack(spacing: 12) {
                    ProgressView()
                    Text("Validez l'accès sur la page de Nextcloud…")
                }
                Button("Arrêter", role: .cancel) { work?.cancel() }
            } else {
                Button("Se connecter avec le navigateur", action: connectWithBrowser)
                    .disabled(isBlank(address))
            }
        } footer: {
            Text("Votre mot de passe Nextcloud se saisit sur la page du serveur, jamais dans Envorenn. Le serveur crée pour cet appareil un accès que vous pourrez révoquer à tout moment.")
        }

        Section {
            Button("Saisir un mot de passe d'application") {
                errorMessage = nil
                step = .manual
            }
            .disabled(isWorking)
        } footer: {
            Text("Si la connexion par le navigateur n'aboutit pas.")
        }
    }

    @ViewBuilder
    private var manualStep: some View {
        Section {
            addressField
        } header: {
            Text("Adresse du serveur")
        }

        Section {
            TextField("Nom de connexion", text: $loginName)
                .textContentType(.username)
                .textInputAutocapitalization(.never)
                .autocorrectionDisabled()
            SecureField("Mot de passe d'application", text: $appPassword)
        } header: {
            Text("Accès")
        } footer: {
            Text("À créer dans Nextcloud : Paramètres personnels › Sécurité › Appareils et sessions. N'utilisez pas le mot de passe de votre compte : un mot de passe d'application se révoque sans rien changer d'autre.")
        }

        Section {
            if isWorking {
                HStack(spacing: 12) {
                    ProgressView()
                    Text("Vérification…")
                }
            } else {
                Button("Vérifier l'accès", action: connectManually)
                    .disabled(isBlank(address) || isBlank(loginName) || isBlank(appPassword))
            }
            Button("Revenir à la connexion par le navigateur") {
                errorMessage = nil
                step = .address
            }
            .disabled(isWorking)
        }
    }

    @ViewBuilder
    private func folderStep(
        _ credentials: NextcloudCredentials,
        _ capabilities: NextcloudCapabilities
    ) -> some View {
        Section {
            LabeledContent("Serveur", value: credentials.endpoints.server.host(percentEncoded: false) ?? "")
            LabeledContent("Compte", value: credentials.endpoints.loginName)
            LabeledContent("Version", value: "Nextcloud \(capabilities.versionString)")
        } header: {
            Text("Accès accordé")
        }

        Section {
            TextField(RemoteFolder.defaultPath, text: $remoteRoot)
                .textInputAutocapitalization(.never)
                .autocorrectionDisabled()
            ForEach(folders, id: \.self) { folder in
                Button {
                    remoteRoot = folder
                } label: {
                    HStack {
                        Label(folder, systemImage: "folder")
                        Spacer()
                        if RemoteFolder.normalize(remoteRoot) == folder {
                            Image(systemName: "checkmark")
                                .foregroundStyle(.tint)
                        }
                    }
                }
                .foregroundStyle(.primary)
            }
        } header: {
            Text("Dossier du coffre")
        } footer: {
            Text("Créé au premier envoi s'il n'existe pas. Réservez-le au coffre : Envorenn y range ses propres sous-dossiers.")
        }

        Section {
            // § 8.2 : une limite du serveur, que l'utilisateur doit connaître
            // pour décider en connaissance de cause.
            WarningRow(message: "Un mot de passe d'application ouvre tous les fichiers de ce compte, pas seulement ce dossier : Nextcloud ne sait pas le restreindre. Pour cloisonner, créez un compte dédié au coffre.")
            if !capabilities.supportsChunking {
                WarningRow(message: "Ce serveur n'annonce pas l'envoi par morceaux : les enregistrements de plus de 10 Mo risquent de ne pas partir.")
            }
        }

        Section {
            Button("Commencer la synchronisation") { finish(credentials) }
                .disabled(RemoteFolder.normalize(remoteRoot) == nil)
        } footer: {
            if RemoteFolder.normalize(remoteRoot) == nil {
                Text("Indiquez un dossier : la racine du compte ne convient pas.")
            }
        }
    }

    private var addressField: some View {
        TextField("nuage.exemple.fr", text: $address)
            .keyboardType(.URL)
            .textContentType(.URL)
            .textInputAutocapitalization(.never)
            .autocorrectionDisabled()
    }

    // MARK: - Actions

    private func connectWithBrowser() {
        guard !isWorking, !isBlank(address) else { return }
        errorMessage = nil

        let server: URL
        do {
            server = try NextcloudServerAddress.parse(address)
        } catch {
            errorMessage = Self.describe(error)
            return
        }

        isWorking = true
        work = Task {
            defer { isWorking = false }
            do {
                let session = LoginFlowSession(userAgent: SyncController.userAgent, client: sync.pairingClient)
                let granted = try await session.run(server: server)
                try await proceed(with: NextcloudCredentials(from: granted))
            } catch {
                errorMessage = Self.describe(error)
            }
        }
    }

    private func connectManually() {
        guard !isWorking else { return }
        errorMessage = nil

        let candidate: NextcloudCredentials
        do {
            candidate = NextcloudCredentials(
                endpoints: try NextcloudEndpoints(
                    server: try NextcloudServerAddress.parse(address),
                    loginName: loginName.trimmingCharacters(in: .whitespacesAndNewlines)
                ),
                appPassword: appPassword.trimmingCharacters(in: .whitespacesAndNewlines)
            )
        } catch {
            errorMessage = Self.describe(error)
            return
        }

        isWorking = true
        work = Task {
            defer { isWorking = false }
            do {
                try await proceed(with: candidate)
            } catch {
                errorMessage = Self.describe(error)
            }
        }
    }

    /// Vérifie l'accès, puis passe au choix du dossier.
    private func proceed(with candidate: NextcloudCredentials) async throws {
        let capabilities = try await sync.validate(candidate)
        // La liste n'est qu'une aide au choix : son échec n'empêche rien.
        folders = (try? await sync.topLevelFolders(for: candidate)) ?? []
        try Task.checkCancellation()
        step = .folder(candidate, capabilities)
    }

    private func finish(_ credentials: NextcloudCredentials) {
        guard let root = RemoteFolder.normalize(remoteRoot) else { return }
        do {
            try sync.pair(credentials, remoteRoot: root)
            dismiss()
        } catch {
            errorMessage = Self.describe(error)
        }
    }

    private func prefill() {
        guard !didPrefill else { return }
        didPrefill = true
        guard let reconnecting else { return }
        address = reconnecting.server.absoluteString
        loginName = reconnecting.loginName
        remoteRoot = reconnecting.remoteRoot
    }

    // MARK: - Détails

    private var title: String {
        switch step {
        case .address: reconnecting == nil ? "Connecter Nextcloud" : "Se reconnecter"
        case .manual: "Mot de passe d'application"
        case .folder: "Dossier du coffre"
        }
    }

    private func isBlank(_ text: String) -> Bool {
        text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }

    /// Message d'erreur, ou `nil` pour un arrêt voulu par l'utilisateur.
    private static func describe(_ error: any Error) -> String? {
        switch error {
        case SyncError.cancelled, is CancellationError, LoginFlowSession.LoginError.cancelled:
            nil
        case SyncError.insecureServerURL:
            "Adresse refusée : la connexion doit être chiffrée (https)."
        case SyncError.invalidServerURL:
            "Adresse de serveur invalide."
        case SyncError.credentialsRevoked:
            "Accès refusé : vérifiez le nom de connexion et le mot de passe d'application."
        case SyncError.unsupportedServer(let detail):
            "Serveur non pris en charge : \(detail)."
        case SyncError.malformedResponse, SyncError.unexpectedStatus(404, _):
            "Aucun Nextcloud ne répond à cette adresse."
        case SyncError.unexpectedStatus(let status, _):
            "Le serveur a répondu \(status)."
        case let error as URLError where error.code == .cannotFindHost || error.code == .dnsLookupFailed:
            "Serveur introuvable. Vérifiez l'adresse."
        default:
            error.localizedDescription
        }
    }
}
Loading