Files
lichtkasten/Sources/LichtkastenCore/Lightroom/LightroomBridge.swift
T

144 lines
7.2 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
/// A job for the "Lichtkasten Bridge" Lightroom Classic plugin.
/// The plugin polls the inbox, imports the files into the open catalog, applies the develop preset,
/// optionally adds them to a collection and exports JPEGs – then writes a result file.
public struct LightroomJob: Codable, Identifiable, Sendable {
public var id: String
public var files: [URL]
public var developPreset: String // name of the LR develop preset, empty = none
public var collection: String // collection name, empty = none
public var export: Bool
public var exportFolder: URL?
public var jpegQuality: Int // 0–100
public var longEdge: Int // px, 0 = full size
public var sharpening: String // "none" | "screen" | "matte" | "glossy"
public var colorSpace: String // "sRGB" | "AdobeRGB"
public var created: Date
/// After export Lichtkasten writes the original IPTC block again (PM-identical structure).
public var rewriteIPTCAfterExport: Bool
/// Upload targets applied after export (FTP destination ids, "immich").
public var uploadTargets: [String]
/// ⌘E – switch Lightroom to the Develop module with the photos selected.
public var openDevelop: Bool = false
public init(id: String = UUID().uuidString, files: [URL], developPreset: String = "", collection: String = "",
export: Bool = false, exportFolder: URL? = nil, jpegQuality: Int = 90, longEdge: Int = 0,
sharpening: String = "none", colorSpace: String = "sRGB", rewriteIPTCAfterExport: Bool = true,
uploadTargets: [String] = []) {
self.id = id; self.files = files; self.developPreset = developPreset; self.collection = collection
self.export = export; self.exportFolder = exportFolder; self.jpegQuality = jpegQuality; self.longEdge = longEdge
self.sharpening = sharpening; self.colorSpace = colorSpace; self.created = Date()
self.rewriteIPTCAfterExport = rewriteIPTCAfterExport; self.uploadTargets = uploadTargets
}
/// Simple line format, trivial to parse in Lua (no JSON library in the LR SDK).
public func serialized() -> String {
var lines = ["version=1", "id=\(id)", "preset=\(developPreset)", "collection=\(collection)",
"export=\(export ? 1 : 0)", "exportFolder=\(exportFolder?.path ?? "")",
"quality=\(jpegQuality)", "longEdge=\(longEdge)", "sharpening=\(sharpening)",
"colorSpace=\(colorSpace)", "develop=\(openDevelop ? 1 : 0)"]
lines += files.map { "file=\($0.path)" }
return lines.map { $0.replacingOccurrences(of: "\n", with: " ") }.joined(separator: "\n") + "\n"
}
}
public struct LightroomJobResult: Sendable {
public var id: String
public var ok: Bool
public var imported: Int
public var exported: [URL]
public var errors: [String]
public private(set) var exportSources: [URL: URL] = [:]
public static func parse(_ text: String) -> LightroomJobResult {
var r = LightroomJobResult(id: "", ok: false, imported: 0, exported: [], errors: [])
var lastExport: URL?
for line in text.components(separatedBy: .newlines) {
guard let eq = line.firstIndex(of: "=") else { continue }
let k = String(line[..<eq]), v = String(line[line.index(after: eq)...])
switch k {
case "id": r.id = v
case "status": r.ok = v == "done"
case "imported": r.imported = Int(v) ?? 0
case "exported":
let file = URL(fileURLWithPath: v)
r.exported.append(file)
lastExport = file
case "source":
if let file = lastExport, v.hasPrefix("/") { r.exportSources[file] = URL(fileURLWithPath: v) }
lastExport = nil
case "error": r.errors.append(v)
default: break
}
}
return r
}
}
public enum LightroomBridge {
public static var root: URL {
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("Lichtkasten/LRBridge", isDirectory: true)
}
public static var inbox: URL { root.appendingPathComponent("inbox", isDirectory: true) }
public static var outbox: URL { root.appendingPathComponent("outbox", isDirectory: true) }
public static var heartbeat: URL { root.appendingPathComponent("heartbeat") }
/// Lightroom Classic loads every *.lrplugin in this folder automatically.
public static var lightroomModulesFolder: URL {
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("Adobe/Lightroom/Modules", isDirectory: true)
}
public static let lightroomBundleIDs = ["com.adobe.LightroomClassicCC7"]
public static func prepareFolders() throws {
for d in [inbox, outbox] { try FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) }
}
/// Writes the job atomically (tmp + rename) so the plugin never reads half a file.
public static func submit(_ job: LightroomJob) throws {
try prepareFolders()
let tmp = inbox.appendingPathComponent(job.id + ".tmp")
try Data(job.serialized().utf8).write(to: tmp)
let final = inbox.appendingPathComponent(job.id + ".job")
try? FileManager.default.removeItem(at: final)
try FileManager.default.moveItem(at: tmp, to: final)
}
/// Collects finished results and removes them from the outbox.
public static func collectResults() -> [LightroomJobResult] {
guard let files = try? FileManager.default.contentsOfDirectory(at: outbox, includingPropertiesForKeys: nil) else { return [] }
var results: [LightroomJobResult] = []
for f in files where f.pathExtension == "result" {
if let text = try? String(contentsOf: f, encoding: .utf8) {
var r = LightroomJobResult.parse(text)
if r.id.isEmpty { r.id = f.deletingPathExtension().lastPathComponent }
results.append(r)
}
try? FileManager.default.removeItem(at: f)
}
return results
}
/// The plugin touches the heartbeat file every few seconds while LR is running.
public static var pluginIsAlive: Bool {
guard let attrs = try? FileManager.default.attributesOfItem(atPath: heartbeat.path),
let date = attrs[.modificationDate] as? Date else { return false }
return Date().timeIntervalSince(date) < 15
}
/// Installs (copies) the plugin bundle into Lightroom's Modules folder.
public static func installPlugin(from bundle: URL) throws {
let fm = FileManager.default
try fm.createDirectory(at: lightroomModulesFolder, withIntermediateDirectories: true)
let dest = lightroomModulesFolder.appendingPathComponent(bundle.lastPathComponent)
if fm.fileExists(atPath: dest.path) { try fm.removeItem(at: dest) }
try fm.copyItem(at: bundle, to: dest)
}
public static var pluginInstalled: Bool {
FileManager.default.fileExists(atPath: lightroomModulesFolder.appendingPathComponent("LichtkastenBridge.lrplugin").path)
}
}