SPB Git

Repository Public License

PhotoCleanupController.swift 4.2 KB 110 lines swift

1// ORIX Secure2// File: App/Sources/Features/PhotoCleanup/PhotoCleanupController.swift3// Description: Drives Photo Cleanup: permission, the incremental scan with progress and cancellation, the user's selection, and4//              the deletion the user confirms. Nothing is selected for deletion by the app except extra copies of exact duplicates.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXMediaCleanup9import ORIXSecureModel10import SwiftUI1112@Observable final class PhotoCleanupController {13    enum Phase: Equatable {14        case idle15        case scanning(String, Double?)16        case results17        case deleting18        case failed(String)19    }2021    private let library = PhotoLibrary(cacheDirectory: AppFolders.caches)22    private var task: Task<Void, Never>?2324    private(set) var access: MediaLibraryAccess = PhotoLibraryAccess.current()25    private(set) var phase: Phase = .idle26    private(set) var output: CleanupPipelineOutput?27    private(set) var lastResult: CleanupResult?28    var selection = CleanupSelection()2930    var analysis: CleanupAnalysis? { output?.analysis }31    var isScanning: Bool { if case .scanning = phase { true } else { false } }3233    func refreshAccess() { access = PhotoLibraryAccess.current() }3435    func requestAccess() async {36        access = await library.requestAccess()37    }3839    private var onFinish: ((CleanupPipelineOutput) -> Void)?4041    func scan(keepingResult: Bool = false, onFinish: @escaping (CleanupPipelineOutput) -> Void) {42        guard !isScanning else { return }43        self.onFinish = onFinish44        if !keepingResult { lastResult = nil }45        phase = .scanning(String(localized: "Reading the photo library…"), nil)46        let pipeline = CleanupPipeline(library: library)47        task = Task { [weak self] in48            do {49                let result = try await pipeline.run { progress in50                    Task { @MainActor in self?.show(progress) }51                }52                guard let self, !Task.isCancelled else { return }53                self.output = result54                self.access = result.access55                self.selection = CleanupSelection.preselected(from: result.analysis)56                self.phase = .results57                onFinish(result)58            } catch is CancellationError {59                self?.phase = self?.output == nil ? .idle : .results60            } catch MediaLibraryError.accessDenied(let level) {61                self?.access = level62                self?.phase = .idle63            } catch {64                self?.phase = .failed(error.localizedDescription)65            }66        }67    }6869    private func show(_ progress: CleanupPipelineProgress) {70        guard isScanning else { return }71        switch progress {72        case .scanning(let scan):73            phase = .scanning(String(localized: "Fingerprinting \(scan.processed) of \(scan.total) items (\(scan.cacheHits) from cache)"), scan.fraction)74        case .analyzing(let analysis):75            phase = .scanning(String(localized: "Comparing items…"), analysis.total > 0 ? Double(analysis.completed) / Double(analysis.total) : nil)76        case .measuring(let measure):77            phase = .scanning(String(localized: "Measuring candidate \(measure.completed) of \(measure.total)"), measure.total > 0 ? Double(measure.completed) / Double(measure.total) : nil)78        }79    }8081    func cancel() {82        task?.cancel()83        task = nil84        phase = output == nil ? .idle : .results85    }8687    func plan() -> CleanupPlan? {88        analysis.map { CleanupPlan(selection: selection, analysis: $0) }89    }9091    /// Asks iOS to delete exactly the selected items. iOS shows its own confirmation; declining it deletes nothing.92    func delete(_ plan: CleanupPlan) async -> CleanupResult {93        phase = .deleting94        let result = await library.deleter.execute(plan)95        lastResult = result96        selection.removeAll()97        phase = .results98        // What was found is out of date once items are gone: scan again (fingerprints come from the cache).99        if !result.deleted.isEmpty {100            output = nil101            scan(keepingResult: true, onFinish: onFinish ?? { _ in })102        }103        return result104    }105106    func resetCache() async {107        await library.scanner.resetCache()108    }109}110
Files main
Menu

Theme