Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
238 lines
10 KiB
Swift
238 lines
10 KiB
Swift
import Foundation
|
||
|
||
public enum ExifToolError: LocalizedError {
|
||
case notInstalled
|
||
case failed(String)
|
||
|
||
public var errorDescription: String? {
|
||
switch self {
|
||
case .notInstalled:
|
||
return "exiftool wurde nicht gefunden. Installation: `brew install exiftool` oder Pfad in den Einstellungen angeben."
|
||
case .failed(let m): return "exiftool-Fehler: \(m)"
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Long-running exiftool process (`-stay_open`). exiftool is the reference implementation
|
||
/// for IPTC-IIM + XMP and produces exactly what agencies expect (incl. CodedCharacterSet & IPTCDigest).
|
||
public final class ExifTool: @unchecked Sendable {
|
||
public static let searchPaths = ["/opt/homebrew/bin/exiftool", "/usr/local/bin/exiftool", "/usr/bin/exiftool"]
|
||
|
||
public static func locate(custom: String? = nil) -> URL? {
|
||
let candidates = [custom].compactMap { $0 }.filter { !$0.isEmpty } + searchPaths
|
||
if let bundled = Bundle.main.url(forResource: "exiftool", withExtension: nil, subdirectory: "exiftool") {
|
||
return bundled
|
||
}
|
||
return candidates.map { URL(fileURLWithPath: $0) }.first { FileManager.default.isExecutableFile(atPath: $0.path) }
|
||
}
|
||
|
||
private let executable: URL
|
||
private let queue = DispatchQueue(label: "lichtkasten.exiftool")
|
||
private var process: Process?
|
||
private var stdinHandle: FileHandle?
|
||
private var stdoutHandle: FileHandle?
|
||
private var stderrBuffer = Data()
|
||
private let stderrLock = NSLock()
|
||
private var counter = 0
|
||
private let tempDir: URL
|
||
|
||
public init(executable: URL) {
|
||
self.executable = executable
|
||
tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("lichtkasten-exiftool", isDirectory: true)
|
||
try? FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
|
||
}
|
||
|
||
deinit { shutdown() }
|
||
|
||
public func shutdown() {
|
||
if let h = stdinHandle {
|
||
try? h.write(contentsOf: Data("-stay_open\nFalse\n".utf8))
|
||
}
|
||
process?.terminate()
|
||
process = nil
|
||
}
|
||
|
||
private func startIfNeeded() throws {
|
||
if let p = process, p.isRunning { return }
|
||
let p = Process()
|
||
p.executableURL = executable
|
||
p.arguments = ["-stay_open", "True", "-@", "-", "-common_args", "-charset", "utf8", "-charset", "iptc=utf8"]
|
||
let inPipe = Pipe(), outPipe = Pipe(), errPipe = Pipe()
|
||
p.standardInput = inPipe
|
||
p.standardOutput = outPipe
|
||
p.standardError = errPipe
|
||
errPipe.fileHandleForReading.readabilityHandler = { [weak self] h in
|
||
let d = h.availableData
|
||
guard let self, !d.isEmpty else { return }
|
||
self.stderrLock.lock(); self.stderrBuffer.append(d); self.stderrLock.unlock()
|
||
}
|
||
try p.run()
|
||
process = p
|
||
stdinHandle = inPipe.fileHandleForWriting
|
||
stdoutHandle = outPipe.fileHandleForReading
|
||
}
|
||
|
||
/// Runs one exiftool command. Arguments must not contain newlines (use `writeValueFile`).
|
||
public func execute(_ args: [String]) async throws -> (stdout: String, stderr: String) {
|
||
try await withCheckedThrowingContinuation { cont in
|
||
queue.async {
|
||
do { cont.resume(returning: try self.executeSync(args)) } catch { cont.resume(throwing: error) }
|
||
}
|
||
}
|
||
}
|
||
|
||
private func executeSync(_ args: [String]) throws -> (stdout: String, stderr: String) {
|
||
try startIfNeeded()
|
||
guard let stdin = stdinHandle, let stdout = stdoutHandle else { throw ExifToolError.failed("Prozess nicht gestartet") }
|
||
counter += 1
|
||
let marker = "{ready\(counter)}"
|
||
stderrLock.lock(); stderrBuffer.removeAll(); stderrLock.unlock()
|
||
let payload = (args.map { $0.replacingOccurrences(of: "\n", with: " ") } + ["-execute\(counter)"]).joined(separator: "\n") + "\n"
|
||
try stdin.write(contentsOf: Data(payload.utf8))
|
||
var out = Data()
|
||
let markerData = Data(marker.utf8)
|
||
while true {
|
||
let chunk = stdout.availableData
|
||
if chunk.isEmpty { throw ExifToolError.failed("exiftool wurde unerwartet beendet") }
|
||
out.append(chunk)
|
||
if let r = out.range(of: markerData, options: .backwards) {
|
||
out.removeSubrange(r.lowerBound..<out.endIndex)
|
||
break
|
||
}
|
||
}
|
||
// stderr arrives asynchronously; give it a moment.
|
||
Thread.sleep(forTimeInterval: 0.005)
|
||
stderrLock.lock(); let err = String(decoding: stderrBuffer, as: UTF8.self); stderrLock.unlock()
|
||
return (String(decoding: out, as: UTF8.self), err)
|
||
}
|
||
|
||
/// Writes a (possibly multi-line) value to a temp file so it can be passed as `-TAG<=file`.
|
||
public func writeValueFile(_ value: String) throws -> URL {
|
||
let url = tempDir.appendingPathComponent(UUID().uuidString + ".txt")
|
||
try Data(value.utf8).write(to: url)
|
||
return url
|
||
}
|
||
|
||
// MARK: Reading
|
||
|
||
/// Reads metadata for many files at once. Returns SourceFile path → flat [tag: value] dictionary.
|
||
/// Keys for IPTC/XMP keep their group ("IPTC:Keywords"), EXIF keys are plain ("Model").
|
||
public func readMetadata(files: [URL]) async throws -> [String: [String: MetadataValue]] {
|
||
guard !files.isEmpty else { return [:] }
|
||
var args = ["-json", "-G1", "-fast2", "-a",
|
||
"-XMP-xmp:Rating#", "-XMP-xmp:Label", "-XMP-photomech:Tagged#", "-XMP-photomech:ColorClass#",
|
||
"-Make", "-Model", "-LensModel", "-Lens", "-SerialNumber", "-ISO", "-ExposureTime", "-FNumber",
|
||
"-FocalLength", "-DateTimeOriginal", "-CreateDate", "-SubSecTimeOriginal", "-OffsetTimeOriginal", "-ImageWidth", "-ImageHeight",
|
||
"-Orientation#", "-Artist", "-GPSLatitude#", "-GPSLongitude#"]
|
||
for f in IPTCField.all {
|
||
if let iim = f.iimTag { args.append("-" + iim) }
|
||
args.append("-" + f.xmpTag)
|
||
}
|
||
args += files.map(\.path)
|
||
let (out, err) = try await execute(args)
|
||
guard let data = out.data(using: .utf8), !out.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||
if !err.isEmpty, !err.contains("Warning") { throw ExifToolError.failed(err) }
|
||
return [:]
|
||
}
|
||
guard let arr = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return [:] }
|
||
var result: [String: [String: MetadataValue]] = [:]
|
||
for obj in arr {
|
||
guard let src = obj["SourceFile"] as? String else { continue }
|
||
var flat: [String: MetadataValue] = [:]
|
||
for (k, v) in obj where k != "SourceFile" {
|
||
let isMeta = k.hasPrefix("IPTC:") || k.hasPrefix("XMP-")
|
||
let key = isMeta ? k : String(k.split(separator: ":").last ?? Substring(k))
|
||
if flat[key] != nil && !isMeta { continue } // first EXIF group wins
|
||
flat[key] = MetadataValue(any: v)
|
||
}
|
||
result[src] = flat
|
||
}
|
||
return result
|
||
}
|
||
}
|
||
|
||
/// JSON values coming back from exiftool.
|
||
public enum MetadataValue: Sendable, Hashable, Codable {
|
||
case string(String)
|
||
case number(Double)
|
||
case bool(Bool)
|
||
case list([String])
|
||
|
||
init(any: Any) {
|
||
switch any {
|
||
case let n as NSNumber:
|
||
// JSONSerialization returns booleans as NSNumber with objCType "c".
|
||
if String(cString: n.objCType) == "c" { self = .bool(n.boolValue) } else { self = .number(n.doubleValue) }
|
||
case let s as String: self = .string(s)
|
||
case let a as [Any]: self = .list(a.map { "\($0)" })
|
||
default: self = .string("\(any)")
|
||
}
|
||
}
|
||
|
||
public var string: String {
|
||
switch self {
|
||
case .string(let s): return s
|
||
case .number(let n): return n == n.rounded() && abs(n) < 1e15 ? String(Int(n)) : String(n)
|
||
case .bool(let b): return b ? "True" : "False"
|
||
case .list(let l): return l.joined(separator: ", ")
|
||
}
|
||
}
|
||
|
||
public var list: [String] {
|
||
if case .list(let l) = self { return l }
|
||
let s = string
|
||
return s.isEmpty ? [] : [s]
|
||
}
|
||
|
||
public var int: Int? {
|
||
switch self {
|
||
case .number(let n): return Int(n)
|
||
case .string(let s): return Int(s)
|
||
case .bool(let b): return b ? 1 : 0
|
||
case .list: return nil
|
||
}
|
||
}
|
||
|
||
public var bool: Bool {
|
||
switch self {
|
||
case .bool(let b): return b
|
||
case .number(let n): return n != 0
|
||
case .string(let s): return ["true", "yes", "1"].contains(s.lowercased())
|
||
case .list: return false
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Several exiftool processes in parallel – reading 2000+ files is I/O + Perl bound, so this scales well on Apple Silicon.
|
||
public final class ExifToolPool: @unchecked Sendable {
|
||
public let workers: [ExifTool]
|
||
|
||
public init(executable: URL, count: Int = min(6, max(2, ProcessInfo.processInfo.activeProcessorCount / 2))) {
|
||
workers = (0..<count).map { _ in ExifTool(executable: executable) }
|
||
}
|
||
|
||
public var primary: ExifTool { workers[0] }
|
||
|
||
public func shutdown() { workers.forEach { $0.shutdown() } }
|
||
|
||
/// Reads file groups (RAW + its sidecar stay together) in chunks spread over all workers;
|
||
/// `onChunk` is called as results arrive.
|
||
public func readMetadata(groups: [[URL]], groupsPerChunk: Int = 50,
|
||
onChunk: @escaping @Sendable ([String: [String: MetadataValue]]) async -> Void) async {
|
||
let chunks: [[URL]] = stride(from: 0, to: groups.count, by: groupsPerChunk).map {
|
||
groups[$0..<min($0 + groupsPerChunk, groups.count)].flatMap { $0 }
|
||
}
|
||
await withTaskGroup(of: Void.self) { group in
|
||
for w in 0..<workers.count {
|
||
let worker = workers[w]
|
||
let mine = chunks.enumerated().filter { $0.offset % workers.count == w }.map(\.element)
|
||
group.addTask {
|
||
for chunk in mine {
|
||
if let meta = try? await worker.readMetadata(files: chunk) { await onChunk(meta) }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|