Repository Public License
1// ORIX Convert — App/Sources/Features/WatchFolders/WatchModel.swift2// Description: Watch Folders state: the rules of the core's FolderWatcher with their status, the rule editor's3// draft (folders come from an open panel only), global and per-rule pause, the activity log, and the4// demonstration set used by screenshots. The watcher runs only while the app is open.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import AppKit7import ConvertCore8import Observation910enum WatchRuleStatus: Equatable {11 case watching, paused, pausedGlobally, stopped12 case error(String)1314 var title: String {15 switch self {16 case .watching: L("Watching")17 case .paused: L("Paused")18 case .pausedGlobally: L("Paused (all rules)")19 case .stopped: L("Not running")20 case .error: L("Needs attention")21 }22 }23 var symbol: String {24 switch self {25 case .watching: "eye.fill"26 case .paused, .pausedGlobally: "pause.fill"27 case .stopped: "stop.fill"28 case .error: "exclamationmark.triangle.fill"29 }30 }31}3233/// The rule being created or edited in the sheet.34struct WatchRuleDraft: Identifiable {35 enum MatchKind: String, CaseIterable, Identifiable {36 case any, formats, categories, glob37 var id: String { rawValue }38 var title: String {39 switch self {40 case .any: L("Any file")41 case .formats: L("Formats")42 case .categories: L("Categories")43 case .glob: L("Name pattern")44 }45 }46 }47 enum ActionKind: String, CaseIterable, Identifiable {48 case convert, preset, workflow49 var id: String { rawValue }50 var title: String {51 switch self {52 case .convert: L("Convert")53 case .preset: L("Preset")54 case .workflow: L("Workflow")55 }56 }57 }5859 var id = UUID()60 var isNew = true61 var name = ""62 var folder: URL?63 var folderBookmark: Data?64 var matchKind: MatchKind = .categories65 var formats: Set<FormatID> = []66 var categories: Set<FormatCategory> = [.image]67 var glob = "*.heic"68 var actionKind: ActionKind = .convert69 var destination: FormatID?70 var operation: String?71 var options = ConversionOptions()72 var presetID: UUID?73 var workflowID: UUID?74 var destinationFolder: URL?75 var destinationBookmark: Data?76 var conflictPolicy: ConflictPolicy = .rename77 var includeSubfolders = false78 var processExistingFiles = false79 var isPaused = false80 var error: String?8182 init() {}8384 init(_ rule: WatchRule) {85 id = rule.id; isNew = false; name = rule.name; folder = rule.folder; folderBookmark = rule.folderBookmark86 destinationFolder = rule.destinationFolder; destinationBookmark = rule.destinationBookmark87 conflictPolicy = rule.conflictPolicy; includeSubfolders = rule.includeSubfolders; processExistingFiles = rule.processExistingFiles; isPaused = rule.isPaused88 switch rule.match {89 case .any: matchKind = .any90 case .formats(let set): matchKind = .formats; formats = set91 case .categories(let set): matchKind = .categories; categories = set92 case .glob(let pattern): matchKind = .glob; glob = pattern93 }94 switch rule.action {95 case .convert(let d, let o, let opts): actionKind = .convert; destination = d; operation = o; options = opts96 case .preset(let id): actionKind = .preset; presetID = id97 case .workflow(let id): actionKind = .workflow; workflowID = id98 }99 }100101 var match: WatchRule.Match {102 switch matchKind {103 case .any: .any104 case .formats: .formats(formats)105 case .categories: .categories(categories)106 case .glob: .glob(glob)107 }108 }109110 /// What is still missing before the rule can be saved, in plain words.111 var missing: String? {112 if folder == nil { return L("Choose the folder to watch.") }113 if matchKind == .formats, formats.isEmpty { return L("Choose at least one format.") }114 if matchKind == .categories, categories.isEmpty { return L("Choose at least one category.") }115 if matchKind == .glob, glob.trimmingCharacters(in: .whitespaces).isEmpty { return L("Type a name pattern, for example *.heic.") }116 switch actionKind {117 case .convert: if destination == nil { return L("Choose what the files are converted to.") }118 case .preset: if presetID == nil { return L("Choose a preset.") }119 case .workflow: if workflowID == nil { return L("Choose a workflow.") }120 }121 if destinationFolder == nil { return L("Choose where the results go.") }122 return nil123 }124125 /// The rule, once nothing is missing. Secrets are never stored in a rule.126 var rule: WatchRule? {127 guard missing == nil, let folder, let destinationFolder else { return nil }128 let action: WatchRule.Action129 switch actionKind {130 case .convert:131 guard let destination else { return nil }132 action = .convert(destination: destination, operation: operation, options: options.redactingSecrets())133 case .preset:134 guard let presetID else { return nil }135 action = .preset(presetID)136 case .workflow:137 guard let workflowID else { return nil }138 action = .workflow(workflowID)139 }140 let trimmed = name.trimmingCharacters(in: .whitespaces)141 var rule = WatchRule(id: id, name: trimmed.isEmpty ? folder.lastPathComponent : trimmed, folder: folder, match: match, action: action, destinationFolder: destinationFolder,142 conflictPolicy: conflictPolicy, includeSubfolders: includeSubfolders, isPaused: isPaused, processExistingFiles: processExistingFiles)143 rule.folderBookmark = folderBookmark144 rule.destinationBookmark = destinationBookmark145 return rule146 }147}148149@Observable final class WatchModel {150 @ObservationIgnored unowned let app: AppModel151 @ObservationIgnored let watcher: FolderWatcher152153 private(set) var rules: [WatchRule] = []154 /// Most recent first.155 private(set) var activity: [WatchActivity] = []156 private(set) var isRunning = false157 private(set) var isPaused = false158 private(set) var loadError: String?159 private(set) var notice: String?160 var draft: WatchRuleDraft?161 var selection: UUID?162 /// Re-evaluated periodically: a watched folder can disappear at any time.163 private(set) var missingFolders: Set<UUID> = []164165 @ObservationIgnored private var eventTask: Task<Void, Never>?166 @ObservationIgnored private var checkTask: Task<Void, Never>?167 @ObservationIgnored private var started = false168169 init(app: AppModel) {170 self.app = app171 watcher = app.watcher172 }173174 var activeRuleCount: Int { rules.filter { !$0.isPaused }.count }175 var hasWork: Bool { isRunning && !isPaused && activeRuleCount > 0 }176177 // MARK: Lifecycle178179 /// Loads the rules, follows the watcher's events and starts watching. Called once at launch.180 func start() async {181 guard !started else { return }182 started = true183 let watcher = watcher184 let events = await watcher.events()185 eventTask = Task { [weak self] in186 for await event in events {187 guard let self else { return }188 switch event {189 case .activity(let entry): self.activity.insert(entry, at: 0)190 case .rulesChanged(let rules): self.rules = rules; self.checkFolders()191 case .stateChanged(let running, let paused): self.isRunning = running; self.isPaused = paused192 }193 }194 }195 await refresh()196 await watcher.start()197 await refresh()198 checkTask = Task { [weak self] in199 while !Task.isCancelled {200 try? await Task.sleep(for: .seconds(5))201 self?.checkFolders()202 }203 }204 }205206 func refresh() async {207 rules = await watcher.rules208 activity = Array(await watcher.activity.reversed())209 isRunning = await watcher.isRunning210 isPaused = await watcher.isPaused211 loadError = await watcher.loadError212 checkFolders()213 }214215 func shutDown() async {216 eventTask?.cancel()217 checkTask?.cancel()218 await watcher.stop()219 }220221 private func checkFolders() {222 var missing = Set<UUID>()223 var isDirectory: ObjCBool = false224 for rule in rules where !(FileManager.default.fileExists(atPath: rule.folder.path, isDirectory: &isDirectory) && isDirectory.boolValue) { missing.insert(rule.id) }225 if missing != missingFolders { missingFolders = missing }226 }227228 func status(of rule: WatchRule) -> WatchRuleStatus {229 if missingFolders.contains(rule.id) { return .error(L("The folder “%@” no longer exists. Put it back, or edit the rule to choose another one.", rule.folder.lastPathComponent)) }230 if !FileManager.default.isWritableFile(atPath: rule.destinationFolder.path) {231 return .error(L("The destination “%@” is missing or read-only.", rule.destinationFolder.lastPathComponent))232 }233 if rule.isPaused { return .paused }234 if isPaused { return .pausedGlobally }235 return isRunning ? .watching : .stopped236 }237238 // MARK: Pause239240 func toggleAll() {241 let watcher = watcher, paused = isPaused242 Task {243 if paused { await watcher.resumeAll() } else { await watcher.pauseAll() }244 await refresh()245 }246 }247248 func setPaused(_ rule: WatchRule, _ paused: Bool) {249 let watcher = watcher250 Task {251 try? await watcher.setRulePaused(rule.id, paused)252 await refresh()253 }254 }255256 // MARK: Editing257258 func newRule() {259 var draft = WatchRuleDraft()260 draft.destination = app.registry.destinationFormats.contains(.jpeg) ? .jpeg : nil261 self.draft = draft262 }263264 func edit(_ rule: WatchRule) { draft = WatchRuleDraft(rule) }265266 func chooseFolder(watched: Bool) {267 guard var draft else { return }268 let message = watched ? L("Choose the folder to watch. Only this folder is looked at.") : L("Choose where the results go")269 guard let url = FolderPanel.choose(message: message, starting: watched ? draft.folder : draft.destinationFolder ?? draft.folder?.deletingLastPathComponent()) else { return }270 // The bookmark is taken at the moment the user authorises the folder.271 let bookmark = (try? url.bookmarkData(options: .withSecurityScope)) ?? (try? url.bookmarkData())272 if watched {273 draft.folder = url; draft.folderBookmark = bookmark274 if draft.name.isEmpty { draft.name = url.lastPathComponent }275 } else {276 draft.destinationFolder = url; draft.destinationBookmark = bookmark277 }278 draft.error = nil279 self.draft = draft280 }281282 /// The loop the core would refuse, found before saving (same check as `addRule`).283 func loopRisk(for draft: WatchRuleDraft) async -> String? {284 guard let rule = draft.rule, let workflow = await workflow(for: rule) else { return nil }285 return FolderWatcher.loopRisk(rule: rule, workflow: workflow, registry: app.registry) == nil ? nil : Self.loopMessage(rule)286 }287288 private static func loopMessage(_ rule: WatchRule) -> String {289 L("This rule would process its own results: they would be written to “%@”, inside the folder it watches, and could match the rule again. Choose a destination outside the watched folder, or restrict the rule to formats it does not produce.", rule.destinationFolder.lastPathComponent)290 }291292 private func workflow(for rule: WatchRule) async -> Workflow? {293 switch rule.action {294 case .workflow(let id): return await app.workflows.workflow(id: id)295 case .preset(let id):296 guard let preset = await app.presets.preset(id: id) else { return nil }297 return Workflow(name: preset.name, nodes: [.convert(destination: preset.destinationFormat, operation: preset.operation, options: preset.options),298 .export(folder: rule.destinationFolder, conflictPolicy: rule.conflictPolicy)])299 case .convert(let destination, let operation, let options):300 return Workflow(name: rule.name, nodes: [.convert(destination: destination, operation: operation, options: options), .export(folder: rule.destinationFolder, conflictPolicy: rule.conflictPolicy)])301 }302 }303304 /// Saves the draft through the core (which checks the folders and refuses a rule that would feed itself).305 @discardableResult306 func saveDraft() async -> Bool {307 guard var draft else { return false }308 guard let rule = draft.rule else {309 draft.error = draft.missing310 self.draft = draft311 return false312 }313 do {314 if draft.isNew { try await watcher.addRule(rule) } else { try await watcher.updateRule(rule) }315 self.draft = nil316 selection = rule.id317 await refresh()318 return true319 } catch {320 draft.error = Self.describe(error, rule: rule)321 self.draft = draft322 return false323 }324 }325326 /// Adds a rule directly (self-test, demonstration set). Returns the error message when the core refuses it.327 func add(_ rule: WatchRule) async -> String? {328 do { try await watcher.addRule(rule); await refresh(); return nil } catch { return Self.describe(error, rule: rule) }329 }330331 static func describe(_ error: Error, rule: WatchRule) -> String {332 guard let error = error as? WatchError else { return (error as? LocalizedError)?.errorDescription ?? error.localizedDescription }333 switch error {334 case .loopRisk: return loopMessage(rule)335 case .folderUnavailable(let detail): return L("A folder of this rule is not available.") + " " + detail336 case .notFound(let detail): return LE(detail)337 case .storage(let detail): return L("The rules could not be saved.") + " " + detail338 }339 }340341 func remove(_ rule: WatchRule) {342 let watcher = watcher343 Task {344 try? await watcher.removeRule(id: rule.id)345 if selection == rule.id { selection = nil }346 await refresh()347 }348 }349350 func clearActivity() {351 let watcher = watcher352 Task { try? await watcher.clearActivity(); await refresh() }353 }354355 func ruleName(_ id: UUID) -> String { rules.first { $0.id == id }?.name ?? L("Deleted rule") }356357 /// What a rule does, in one line.358 func actionSummary(_ rule: WatchRule) -> String {359 switch rule.action {360 case .convert(let destination, let operation, _):361 if let operation, let title = app.registry.paths(to: destination, operation: .some(operation)).first?.title { return LE(title) }362 return L("Convert to %@", destination.displayName)363 case .preset(let id): return L("Preset “%@”", app.presetList.first { $0.id == id }?.name ?? L("missing"))364 case .workflow(let id): return L("Workflow “%@”", app.flow.find(id.uuidString)?.name ?? L("missing"))365 }366 }367368 func matchSummary(_ rule: WatchRule) -> String {369 switch rule.match {370 case .any: return L("Any file")371 case .formats(let formats): return formats.map(\.displayName).sorted().joined(separator: ", ")372 case .categories(let categories): return categories.map(\.title).sorted().joined(separator: ", ")373 case .glob(let pattern): return pattern374 }375 }376377 // MARK: Demonstration set (screenshots)378379 /// Creates folders and rules under `root`, drops generated files and lets the watcher convert them for real.380 func seedDemo(in root: URL) async {381 let fm = FileManager.default382 func folder(_ name: String) -> URL {383 let url = root.appendingPathComponent(name, isDirectory: true)384 try? fm.createDirectory(at: url, withIntermediateDirectories: true)385 return url386 }387 guard rules.isEmpty else { return }388 let inbox = folder("Camera uploads"), web = folder("Web-ready"), scans = folder("Scanner"), archive = folder("Scans as PDF"), gone = folder("Old downloads"), out = folder("Converted")389 _ = await add(WatchRule(name: L("Photos for the web"), folder: inbox, match: .categories([.image]),390 action: .convert(destination: .webp, operation: nil, options: ConversionOptions(["quality": .int(80), "resize.mode": .string("long-edge"), "resize.long-edge": .int(1600)])),391 destinationFolder: web))392 _ = await add(WatchRule(name: L("Scans to PDF"), folder: scans, match: .formats([.tiff, .png]), action: .convert(destination: .pdf, operation: nil, options: ConversionOptions()),393 destinationFolder: archive, isPaused: true))394 _ = await add(WatchRule(name: L("Downloads to PNG"), folder: gone, match: .glob("*.heic"), action: .convert(destination: .png, operation: nil, options: ConversionOptions()), destinationFolder: out))395 try? fm.removeItem(at: gone)396 // Real arrivals: two photos, the same photo again (duplicate content), and a file that is no image.397 SampleFiles.makePhoto(at: inbox.appendingPathComponent("IMG_2041.jpg"), width: 1800, height: 1200)398 SampleFiles.makeImage(at: inbox.appendingPathComponent("Sketch.png"), width: 900, height: 700, type: .png, alpha: true, seed: 2)399 try? Data("not an image\n".utf8).write(to: inbox.appendingPathComponent("Notes.txt"))400 try? await Task.sleep(for: .milliseconds(3200))401 try? fm.copyItem(at: inbox.appendingPathComponent("IMG_2041.jpg"), to: inbox.appendingPathComponent("IMG_2041 copy.jpg"))402 try? Data([0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00]).write(to: inbox.appendingPathComponent("Broken.jpg"))403 await refresh()404 }405}406407extension WatchActivity.Kind {408 var title: String {409 switch self {410 case .processed: L("Converted")411 case .nothingWritten: L("Nothing written")412 case .failed: L("Failed")413 case .duplicate: L("Duplicate, skipped")414 }415 }416 var symbol: String {417 switch self {418 case .processed: "checkmark.circle.fill"419 case .nothingWritten: "minus.circle"420 case .failed: "xmark.octagon.fill"421 case .duplicate: "doc.on.doc"422 }423 }424}425426extension WatchActivity {427 /// The core's detail in the user's language where the sentence is known.428 var localizedDetail: String {429 if let match = detail.firstMatch(of: /^Wrote (\d+) files?\.$/), let count = Int(match.1) { return count == 1 ? L("1 file written") : L("%lld files written", count) }430 switch detail {431 case "The same content was already processed by this rule.": return L("The same content was already processed by this rule.")432 case "Nothing was written.": return L("Nothing was written.")433 case "Excluded by the workflow's filter.": return L("Excluded by the workflow's filter.")434 case "Cancelled.": return L("Cancelled")435 case "The conversion failed.": return L("The conversion failed.")436 default: return LE(detail)437 }438 }439}440