SPB Git

Repository Public License

FileCleanupView.swift 11.2 KB 207 lines swift

1// ORIX Secure2// File: App/Sources/Features/Storage/FileCleanupView.swift3// Description: File cleanup in a folder the user authorises: byte-identical duplicates and the largest files, selected by the4//              user, deleted only after confirmation, with a per-file result. Other apps' private storage is out of reach.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDesign9import ORIXFileInspection10import ORIXSecureModel11import SwiftUI12import UniformTypeIdentifiers1314struct FileCleanupView: View {15    @Environment(AppModel.self) private var model16    @Environment(Router.self) private var router17    @State private var picking = false18    @State private var folder: URL?19    @State private var duplicates: DuplicateReport?20    @State private var large: LargeFileReport?21    @State private var status: String?22    @State private var error: String?23    @State private var selected: Set<URL> = []24    @State private var confirm = false25    @State private var removal: RemovalReport?26    @State private var task: Task<Void, Never>?2728    var body: some View {29        ScreenScroll {30            VStack(alignment: .leading, spacing: ORIX.Space.sm) {31                Text("Choose a folder in Files (On My iPhone, iCloud Drive, a connected drive). ORIX Secure looks only inside the folder you choose.")32                    .font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)33                Button { picking = true } label: { Label(folder == nil ? "Choose Folder" : "Choose Another Folder", systemImage: "folder.badge.plus") }34                    .buttonStyle(.orixPrimary).accessibilityIdentifier("files.choose")35                if let folder { Label { Text(verbatim: folder.lastPathComponent) } icon: { Image(systemName: "folder") }.font(.orixHeadline) }36                if let status {37                    HStack { ProgressView(); Text(verbatim: status).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary) }38                    Button("Cancel") { task?.cancel() }.font(.orixCallout)39                }40            }41            .orixCard()42            if let error { ORIXBanner(.error, title: Text("The folder could not be scanned"), message: Text(verbatim: error)) }43            if let removal { removalBanner(removal) }44            if let duplicates { duplicateSection(duplicates) }45            if let large { largeSection(large) }46            LimitsCard(title: "What file cleanup can reach", items: [47                String(localized: "Only folders you pick. Other apps' private storage and caches are invisible to every app."),48                String(localized: "Files are deleted permanently from the folder: there is no Recently Deleted for them unless the storage provider keeps one."),49                String(localized: "Duplicates are byte-identical files (same SHA-256). Similar but different files are not listed."),50            ])51        }52        .accessibilityIdentifier("files")53        .safeAreaInset(edge: .bottom) {54            if !selected.isEmpty {55                Button(role: .destructive) { confirm = true } label: { Label("Delete \(selected.count) File(s)…", systemImage: "trash") }56                    .buttonStyle(.orixPrimary).padding(.horizontal, ORIX.Space.md).padding(.vertical, ORIX.Space.xs).background(.bar)57                    .accessibilityIdentifier("files.delete")58            }59        }60        .navigationTitle("File Cleanup")61        .fileImporter(isPresented: $picking, allowedContentTypes: [.folder]) { result in62            switch result {63            case .success(let url): scan(url)64            case .failure(let failure): error = failure.localizedDescription65            }66        }67        .confirmationDialog("Delete \(selected.count) file(s) permanently?", isPresented: $confirm, titleVisibility: .visible) {68            Button("Delete \(selected.count) File(s)", role: .destructive) { remove() }69        } message: { Text("\(ORIXFormat.bytes(selectedBytes)) will be removed from the folder. This cannot be undone.") }70        .onAppear { if let url = router.pendingFolder { router.pendingFolder = nil; scan(url) } }71    }7273    private var sizes: [URL: Int64] {74        var map: [URL: Int64] = [:]75        for group in duplicates?.groups ?? [] { for url in group.urls { map[url] = group.fileSize } }76        for file in large?.largestFiles ?? [] { map[file.url] = file.size }77        return map78    }7980    private var selectedBytes: Int64 { let sizes = sizes; return selected.reduce(0) { $0 + (sizes[$1] ?? 0) } }8182    private func scan(_ url: URL) {83        task?.cancel()84        folder = url85        duplicates = nil86        large = nil87        removal = nil88        selected = []89        error = nil90        status = String(localized: "Listing files…")91        task = Task {92            let scoped = url.startAccessingSecurityScopedResource()93            defer { if scoped { url.stopAccessingSecurityScopedResource() } }94            do {95                let largeReport = try await LargeFileScanner().scan(folder: url) { count in96                    Task { @MainActor in if status != nil { status = String(localized: "\(count) files listed…") } }97                }98                large = largeReport99                let duplicateReport = try await DuplicateFinder().findDuplicates(inFolder: url) { progress in100                    Task { @MainActor in if status != nil { status = String(localized: "Comparing \(progress.filesProcessed) of \(progress.filesTotal) files…") } }101                }102                duplicates = duplicateReport103            } catch is CancellationError {104            } catch {105                self.error = error.localizedDescription106            }107            status = nil108        }109    }110111    private func remove() {112        guard let folder else { return }113        let urls = Array(selected)114        Task {115            let scoped = folder.startAccessingSecurityScopedResource()116            let report = await FileRemover().remove(urls)117            if scoped { folder.stopAccessingSecurityScopedResource() }118            removal = report119            let gone = Set(report.results.filter { $0.outcome == .removed || $0.outcome == .missing }.map(\.url))120            selected.subtract(gone)121            duplicates?.groups = (duplicates?.groups ?? []).compactMap { group in122                var group = group123                group.urls.removeAll { gone.contains($0) }124                return group.urls.count > 1 ? group : nil125            }126            large?.largestFiles.removeAll { gone.contains($0.url) }127            model.store.save(ReportDocument(kind: .cleanup, title: L("File cleanup"),128                summary: L("\(report.removedCount) file(s) deleted, \(ORIXFormat.bytes(report.bytesFreed)) freed, \(report.failedCount) not deleted. Sizes were measured before deletion and each deletion was verified."),129                sections: [.init(title: L("Result"), facts: [130                    .init(L("Files selected"), "\(urls.count)"), .init(L("Deleted"), "\(report.removedCount)"),131                    .init(L("Freed (measured)"), ORIXFormat.bytes(report.bytesFreed)), .init(L("Not deleted"), "\(report.failedCount)"),132                ], bullets: report.results.filter { $0.outcome != .removed }.map { "\($0.url.lastPathComponent): \($0.message ?? $0.outcome.rawValue)" })],133                generator: ReportBuilder.generator))134            model.refresh()135            ORIXHaptics.success()136        }137    }138139    private func removalBanner(_ report: RemovalReport) -> some View {140        ORIXBanner(report.failedCount == 0 ? .success : .warning,141                   title: Text("\(report.removedCount) file(s) deleted, \(ORIXFormat.bytes(report.bytesFreed)) freed"),142                   message: Text(report.failedCount == 0 ? String(localized: "Each deletion was verified.") : String(localized: "\(report.failedCount) file(s) could not be deleted and were left in place.")))143            .accessibilityIdentifier("files.result")144    }145146    @ViewBuilder private func duplicateSection(_ report: DuplicateReport) -> some View {147        ORIXSectionHeader("Duplicates")148        Text(report.groups.isEmpty ? "No byte-identical files among the \(report.filesExamined) examined."149                                   : "\(report.duplicateFileCount) extra copies in \(report.groups.count) group(s) — \(ORIXFormat.bytes(report.reclaimableBytes)) if all extra copies are deleted.")150            .font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)151            .accessibilityIdentifier("files.duplicateSummary")152        ForEach(report.groups.prefix(100)) { group in153            VStack(alignment: .leading, spacing: ORIX.Space.xs) {154                HStack {155                    Text("\(group.urls.count) copies · \(ORIXFormat.bytes(group.fileSize)) each").font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)156                    Spacer()157                    Button("Select Extra Copies") { selected.formUnion(group.urls.dropFirst()) }.font(.orixCallout)158                }159                ForEach(group.urls, id: \.self) { url in fileRow(url, size: nil) }160            }161            .orixCard(padding: ORIX.Space.sm)162        }163    }164165    @ViewBuilder private func largeSection(_ report: LargeFileReport) -> some View {166        ORIXSectionHeader("Largest files")167        Text("\(report.filesExamined) files, \(ORIXFormat.bytes(report.totalBytes)) in this folder.").font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)168            .accessibilityIdentifier("files.largeSummary")169        if !report.largestFiles.isEmpty {170            VStack(alignment: .leading, spacing: ORIX.Space.xs) {171                ForEach(report.largestFiles.prefix(30)) { file in fileRow(file.url, size: file.size) }172            }173            .orixCard(padding: ORIX.Space.sm)174        }175        if !report.skipped.isEmpty {176            Text("\(report.skipped.count) item(s) could not be read and were skipped.").font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)177        }178    }179180    private func fileRow(_ url: URL, size: Int64?) -> some View {181        let isSelected = selected.contains(url)182        return Button {183            if isSelected { selected.remove(url) } else { selected.insert(url) }184        } label: {185            HStack(spacing: ORIX.Space.sm) {186                Image(systemName: isSelected ? "trash.circle.fill" : "circle").foregroundStyle(isSelected ? ORIX.Palette.danger : ORIX.Palette.textTertiary).font(.title3)187                VStack(alignment: .leading, spacing: 1) {188                    Text(verbatim: url.lastPathComponent).font(.orixCallout).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1).truncationMode(.middle)189                    Text(verbatim: relativePath(url)).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1).truncationMode(.head)190                }191                Spacer(minLength: 4)192                if let size { Text(verbatim: ORIXFormat.bytes(size)).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary).monospacedDigit() }193            }194            .frame(minHeight: 40)195            .contentShape(Rectangle())196        }197        .buttonStyle(.plain)198        .accessibilityAddTraits(isSelected ? .isSelected : [])199        .accessibilityIdentifier("files.row")200    }201202    private func relativePath(_ url: URL) -> String {203        guard let folder else { return url.path }204        return url.deletingLastPathComponent().path.replacingOccurrences(of: folder.path, with: folder.lastPathComponent)205    }206}207
Files main
Menu

Theme