SPB Git

Repository Public License

HistoryModel.swift 6.1 KB 159 lines swift

1// ORIX Convert — App/Sources/Features/History/HistoryModel.swift2// Description: Search, filters and paging over ConversionHistoryStore; delete, clear and "convert again".3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import ConvertCore5import Foundation6import Observation78enum HistoryPeriod: String, CaseIterable, Identifiable {9    case all, today, week, month10    var id: String { rawValue }11    var title: String {12        switch self {13        case .all: L("Any date")14        case .today: L("Today")15        case .week: L("Last 7 days")16        case .month: L("Last 30 days")17        }18    }1920    var lowerBound: Date? {21        let calendar = Calendar.current22        switch self {23        case .all: return nil24        case .today: return calendar.startOfDay(for: Date())25        case .week: return calendar.date(byAdding: .day, value: -7, to: Date())26        case .month: return calendar.date(byAdding: .day, value: -30, to: Date())27        }28    }29}3031@Observable final class HistoryModel {32    @ObservationIgnored unowned let app: AppModel33    var entries: [HistoryEntry] = []34    var totalCount = 035    var matchingCount = 036    var search = "" { didSet { if search != oldValue { scheduleReload() } } }37    /// `nil`: every status.38    var status: String? { didSet { if status != oldValue { scheduleReload() } } }39    var format: FormatID? { didSet { if format != oldValue { scheduleReload() } } }40    var period: HistoryPeriod = .all { didSet { if period != oldValue { scheduleReload() } } }41    var selection: Int64?42    var error: String?43    var isLoading = false44    @ObservationIgnored private var reloadTask: Task<Void, Never>?45    @ObservationIgnored private var needsReload = true46    static let pageSize = 3004748    init(app: AppModel) { self.app = app }4950    var store: ConversionHistoryStore? { app.manager.history }51    var selected: HistoryEntry? { entries.first { $0.id == selection } }52    var hasFilters: Bool { !search.isEmpty || status != nil || format != nil || period != .all }53    /// Formats present in the loaded page, for the filter menu.54    var formatsInUse: [FormatID] {55        Set(entries.flatMap { [$0.sourceFormat, $0.destinationFormat].compactMap { $0 } }).sorted()56    }5758    func setNeedsReload() {59        needsReload = true60        if app.section == .history { scheduleReload() }61    }6263    func reloadIfNeeded() {64        if needsReload { scheduleReload(immediately: true) }65    }6667    func scheduleReload(immediately: Bool = false) {68        reloadTask?.cancel()69        reloadTask = Task { [weak self] in70            if !immediately { try? await Task.sleep(for: .milliseconds(200)) }71            if Task.isCancelled { return }72            await self?.reload()73        }74    }7576    private var query: HistoryQuery {77        var query = HistoryQuery()78        let trimmed = search.trimmingCharacters(in: .whitespaces)79        query.search = trimmed.isEmpty ? nil : trimmed80        if let status { query.statuses = [status] }81        query.from = period.lowerBound82        query.limit = Self.pageSize83        return query84    }8586    func reload() async {87        guard let store else { error = app.historyError; return }88        isLoading = true89        defer { isLoading = false }90        needsReload = false91        do {92            // A format filter matches the source or the destination, so two queries are merged.93            var query = query94            let rows: [HistoryEntry]95            if let format {96                query.sourceFormat = format97                let asSource = try await store.entries(query)98                query.sourceFormat = nil99                query.destinationFormat = format100                let asDestination = try await store.entries(query).filter { $0.sourceFormat != format }101                rows = (asSource + asDestination).sorted { $0.finishedAt > $1.finishedAt }102                matchingCount = rows.count103            } else {104                rows = try await store.entries(query)105                matchingCount = try await store.count(query)106            }107            entries = rows108            totalCount = try await store.count()109            if let selection, !rows.contains(where: { $0.id == selection }) { self.selection = nil }110            if app.launch.select == "first", selection == nil { selection = rows.first?.id }111            error = nil112        } catch {113            self.error = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription114        }115    }116117    func delete(_ entry: HistoryEntry) {118        guard let store else { return }119        Task {120            _ = try? await store.delete(ids: [entry.id])121            await reload()122        }123    }124125    func clearAll() {126        guard let store else { return }127        Task {128            try? await store.clearAll()129            await reload()130        }131    }132133    func clearFilters() {134        search = ""; status = nil; format = nil; period = .all135    }136137    /// Sources of the entry that still exist.138    func existingSources(of entry: HistoryEntry) -> [URL] {139        ([entry.sourcePath] + entry.additionalSourcePaths).map { URL(fileURLWithPath: $0) }.filter(FileActions.exists)140    }141142    /// Enqueues the same conversion with the recorded options (which never include secrets).143    func convertAgain(_ entry: HistoryEntry) -> Bool {144        let sources = ([entry.sourcePath] + entry.additionalSourcePaths).map { URL(fileURLWithPath: $0) }145        guard !sources.isEmpty, sources.allSatisfy(FileActions.exists) else { return false }146        var destination = app.defaultDestination147        if let first = entry.destinationPaths.first { destination.directory = URL(fileURLWithPath: first).deletingLastPathComponent() }148        app.enqueue(ConversionJobRequest(sources: sources, sourceFormat: entry.sourceFormat, destinationFormat: entry.destinationFormat,149                                         operation: entry.operation, options: entry.options, destination: destination))150        return true151    }152}153154extension HistoryEntry {155    var sourceName: String { (sourcePath as NSString).lastPathComponent }156    var state: JobState { JobState(rawValue: status) ?? .failed }157    var outputURLs: [URL] { destinationPaths.map { URL(fileURLWithPath: $0) } }158}159
Files main
Menu

Theme