SPB Git

Repository Public License

AppIntents.swift 14.4 KB 259 lines swift

1// ORIX Convert — App/Sources/Features/Integration/AppIntents.swift2// Description: Shortcuts actions (App Intents): Convert Files, Detect Format, Run Workflow. They run in the app's3//              process, on its real queue and registry, without bringing a window forward; results are written to4//              a private folder of the temporary directory and handed back to Shortcuts as files.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import AppIntents7import ConvertCore8import Foundation910// MARK: - Shared machinery1112/// What the intents do, as plain functions over file URLs (also called by the self-test).13enum IntentRunner {14    /// Root of the intents' working folders. Folders older than a day are removed at launch.15    nonisolated static var root: URL {16        FileManager.default.temporaryDirectory.appendingPathComponent("ai.spboucher.orix.convert.intents", isDirectory: true)17    }1819    nonisolated static func sweep(olderThan age: TimeInterval = 24 * 3600) {20        let fm = FileManager.default21        for entry in (try? fm.contentsOfDirectory(at: root, includingPropertiesForKeys: [.contentModificationDateKey])) ?? [] {22            if let date = try? entry.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, Date().timeIntervalSince(date) > age { try? fm.removeItem(at: entry) }23        }24    }2526    nonisolated static func newFolder(_ name: String) throws -> URL {27        let url = root.appendingPathComponent(UUID().uuidString, isDirectory: true).appendingPathComponent(name, isDirectory: true)28        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])29        return url30    }3132    /// Copies what Shortcuts handed over into a private folder (a file passed by Shortcuts may have no URL at all).33    nonisolated static func materialize(_ files: [IntentFile]) throws -> [URL] {34        let folder = try newFolder("in")35        var urls: [URL] = []36        var used = Set<String>()37        for (index, file) in files.enumerated() {38            var name = OutputNameTemplate.sanitize(file.filename.isEmpty ? "file-\(index + 1)" : file.filename, maxBytes: 240)39            if !used.insert(name.lowercased()).inserted { name = "\(index + 1)-" + name; used.insert(name.lowercased()) }40            let destination = folder.appendingPathComponent(name)41            if let source = file.fileURL, source.isFileURL, FileManager.default.fileExists(atPath: source.path) {42                let scoped = source.startAccessingSecurityScopedResource()43                defer { if scoped { source.stopAccessingSecurityScopedResource() } }44                try FileManager.default.copyItem(at: source, to: destination)45            } else {46                try file.data.write(to: destination)47            }48            urls.append(destination)49        }50        return urls51    }5253    /// Regular files of the results: a folder result (pages, extracted archive) is expanded, bounded.54    nonisolated static func flatten(_ outputs: [URL], limit: Int = 500) -> [URL] {55        var files: [URL] = []56        for url in outputs {57            var isDirectory: ObjCBool = false58            guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) else { continue }59            if !isDirectory.boolValue { files.append(url); continue }60            let inside = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey])61            var found: [URL] = []62            while let item = inside?.nextObject() as? URL, found.count < limit {63                if (try? item.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true { found.append(item) }64            }65            files += found.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }66        }67        return Array(files.prefix(limit))68    }6970    struct Failure: LocalizedError { let errorDescription: String? }7172    /// Converts each file on the app's queue and returns the outputs. Throws with the first job's message when73    /// nothing was produced.74    static func convert(_ sources: [URL], to destination: FormatID, operation: String? = nil, options: ConversionOptions = .init(), preset: ConversionPreset? = nil,75                        model: AppModel) async throws -> [URL] {76        let out = try newFolder("out")77        let target = OutputDestination(directory: out, conflictPolicy: .rename)78        let queue = model.manager.queue79        let record = model.settings.stored.historyEnabled80        let ids = await queue.enqueue(batch: sources.map {81            var request = ConversionJobRequest(sources: [$0], destinationFormat: preset?.destinationFormat ?? destination, operation: preset?.operation ?? operation,82                                               options: preset?.options ?? options, destination: target)83            request.recordInHistory = record84            return request85        })86        var outputs: [URL] = [], errors: [String] = []87        for id in ids {88            let job = await withTaskCancellationHandler { await queue.waitForJob(id) } onCancel: { Task { await queue.cancel(id) } }89            if let job, job.state == .finished { outputs += job.outputs.filter { $0.outcome != .skipped }.map(\.url) } else if let message = job?.error { errors.append(message) }90        }91        if outputs.isEmpty { throw Failure(errorDescription: errors.first ?? L("Nothing was converted.")) }92        return outputs93    }9495    static func runWorkflow(_ workflow: Workflow, inputs: [URL], model: AppModel) async throws -> [URL] {96        let out = try newFolder("out")97        var options = WorkflowRunOptions()98        options.defaultExportFolder = out99        let run = try await model.manager.workflowRunner.run(workflow, inputs: inputs, options: options)100        let outputs = run.items.flatMap(\.outputs)101        if outputs.isEmpty { throw Failure(errorDescription: run.items.flatMap(\.errors).first ?? L("The workflow produced no file.")) }102        return outputs103    }104105    /// One line describing what a file is, from its content.106    nonisolated static func describe(_ url: URL) -> (format: FormatID?, text: String) {107        let detection = FileTypeDetector.detect(url)108        guard let format = detection.format else { return (nil, L("Unrecognised (%@)", detection.evidence)) }109        let name = FormatCatalog.format(format)?.name ?? format.rawValue.uppercased()110        return (format, detection.mismatch ? L("%@ — the name says .%@ (%@)", name, detection.fileExtension, detection.evidence) : "\(name) (\(detection.evidence))")111    }112}113114// MARK: - Entities115116/// A destination format that at least one engine of this build can write.117nonisolated struct FormatEntity: AppEntity {118    static let typeDisplayRepresentation: TypeDisplayRepresentation = "Format"119    static let defaultQuery = FormatEntityQuery()120    let id: String121    let name: String122    let category: String123    var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(name)", subtitle: "\(category)") }124125    init?(_ format: FormatID) {126        guard let entry = FormatCatalog.format(format) else { return nil }127        id = format.rawValue; name = entry.name; category = entry.category.rawValue.capitalized128    }129}130131nonisolated struct FormatEntityQuery: EntityStringQuery {132    /// Destinations of plain conversions in the registry of the running app, most common first.133    private func all() async -> [FormatEntity] {134        let registry = await MainActor.run { AppRuntime.model.registry }135        let plain = Set(registry.paths.filter { $0.operation == nil && $0.destination != .folder }.map(\.destination))136        let preferred: [FormatID] = [.pdf, .png, .jpeg, .heic, .webp, .mp4, .mov, .mp3, .m4a, .wav, .docx, .markdown, .txt, .csv, .xlsx, .json, .parquet, .zip]137        let ordered = preferred.filter(plain.contains) + plain.subtracting(preferred).sorted { $0.rawValue < $1.rawValue }138        return ordered.compactMap(FormatEntity.init)139    }140    func entities(for identifiers: [String]) async throws -> [FormatEntity] { await all().filter { identifiers.contains($0.id) } }141    func suggestedEntities() async throws -> [FormatEntity] { await all() }142    func entities(matching string: String) async throws -> [FormatEntity] {143        let needle = string.lowercased()144        return await all().filter { $0.id.contains(needle) || $0.name.lowercased().contains(needle) }145    }146}147148/// A preset of the app (shipped or saved by the user).149nonisolated struct PresetEntity: AppEntity {150    static let typeDisplayRepresentation: TypeDisplayRepresentation = "Preset"151    static let defaultQuery = PresetEntityQuery()152    let id: String153    let name: String154    let summary: String155    var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(name)", subtitle: "\(summary)") }156}157158nonisolated struct PresetEntityQuery: EntityQuery {159    private func all() async -> [PresetEntity] {160        let model = await MainActor.run { AppRuntime.model }161        await model.reloadPresets()162        return await model.presetList.map { PresetEntity(id: $0.id.uuidString, name: $0.name, summary: $0.summary.isEmpty ? $0.destinationFormat.rawValue.uppercased() : $0.summary) }163    }164    func entities(for identifiers: [String]) async throws -> [PresetEntity] { await all().filter { identifiers.contains($0.id) } }165    func suggestedEntities() async throws -> [PresetEntity] { await all() }166}167168/// A workflow of Conversion Flow (saved, or a built-in example valid in this build).169nonisolated struct WorkflowEntity: AppEntity {170    static let typeDisplayRepresentation: TypeDisplayRepresentation = "Workflow"171    static let defaultQuery = WorkflowEntityQuery()172    let id: String173    let name: String174    var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(name)") }175}176177nonisolated struct WorkflowEntityQuery: EntityQuery {178    static func workflows() async -> [Workflow] {179        let model = await MainActor.run { AppRuntime.model }180        await model.flow.start()181        return await MainActor.run { model.flow.saved + model.flow.builtIns.map(\.workflow) }182    }183    private func all() async -> [WorkflowEntity] { await Self.workflows().map { WorkflowEntity(id: $0.id.uuidString, name: $0.name) } }184    func entities(for identifiers: [String]) async throws -> [WorkflowEntity] { await all().filter { identifiers.contains($0.id) } }185    func suggestedEntities() async throws -> [WorkflowEntity] { await all() }186}187188// MARK: - Intents189190struct ConvertFilesIntent: AppIntent {191    static let title: LocalizedStringResource = "Convert Files"192    static let description = IntentDescription("Converts files to another format on this Mac with ORIX Convert. Nothing is sent anywhere.", categoryName: "Conversion")193    static let openAppWhenRun = false194195    @Parameter(title: "Files", supportedContentTypes: [.item]) var files: [IntentFile]196    @Parameter(title: "Format") var format: FormatEntity197    @Parameter(title: "Preset", description: "Optional: a preset replaces the format and brings its settings.") var preset: PresetEntity?198199    static var parameterSummary: some ParameterSummary { Summary("Convert \(\.$files) to \(\.$format)") { \.$preset } }200201    func perform() async throws -> some IntentResult & ReturnsValue<[IntentFile]> {202        let sources = try IntentRunner.materialize(files)203        let model = await MainActor.run { AppRuntime.model }204        var chosen: ConversionPreset?205        if let preset {206            await model.reloadPresets()207            chosen = await model.presetList.first { $0.id.uuidString == preset.id }208        }209        let outputs = try await IntentRunner.convert(sources, to: FormatID(format.id), preset: chosen, model: model)210        return .result(value: IntentRunner.flatten(outputs).map { IntentFile(fileURL: $0) })211    }212}213214struct DetectFormatIntent: AppIntent {215    static let title: LocalizedStringResource = "Detect Format"216    static let description = IntentDescription("Says what a file really is, from its content rather than its name.", categoryName: "Conversion")217    static let openAppWhenRun = false218219    @Parameter(title: "File", supportedContentTypes: [.item]) var file: IntentFile220221    static var parameterSummary: some ParameterSummary { Summary("Detect the format of \(\.$file)") }222223    func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {224        let url = try IntentRunner.materialize([file])[0]225        defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent().deletingLastPathComponent()) }226        let result = IntentRunner.describe(url)227        return .result(value: result.format?.rawValue ?? "", dialog: IntentDialog(stringLiteral: result.text))228    }229}230231struct RunWorkflowIntent: AppIntent {232    static let title: LocalizedStringResource = "Run Workflow"233    static let description = IntentDescription("Runs a Conversion Flow workflow of ORIX Convert over files and returns what it produced.", categoryName: "Conversion")234    static let openAppWhenRun = false235236    @Parameter(title: "Workflow") var workflow: WorkflowEntity237    @Parameter(title: "Files", supportedContentTypes: [.item]) var files: [IntentFile]238239    static var parameterSummary: some ParameterSummary { Summary("Run \(\.$workflow) on \(\.$files)") }240241    func perform() async throws -> some IntentResult & ReturnsValue<[IntentFile]> {242        guard let chosen = await WorkflowEntityQuery.workflows().first(where: { $0.id.uuidString == workflow.id }) else {243            throw IntentRunner.Failure(errorDescription: L("This workflow no longer exists in ORIX Convert."))244        }245        let sources = try IntentRunner.materialize(files)246        let model = await MainActor.run { AppRuntime.model }247        let outputs = try await IntentRunner.runWorkflow(chosen, inputs: sources, model: model)248        return .result(value: IntentRunner.flatten(outputs).map { IntentFile(fileURL: $0) })249    }250}251252nonisolated struct ORIXConvertShortcuts: AppShortcutsProvider {253    static var appShortcuts: [AppShortcut] {254        AppShortcut(intent: ConvertFilesIntent(), phrases: ["Convert files with \(.applicationName)", "Convert with \(.applicationName)"], shortTitle: "Convert Files", systemImageName: "arrow.triangle.2.circlepath")255        AppShortcut(intent: DetectFormatIntent(), phrases: ["Detect a file format with \(.applicationName)"], shortTitle: "Detect Format", systemImageName: "doc.text.magnifyingglass")256        AppShortcut(intent: RunWorkflowIntent(), phrases: ["Run a workflow with \(.applicationName)"], shortTitle: "Run Workflow", systemImageName: "point.3.connected.trianglepath.dotted")257    }258}259
Files main
Menu

Theme