Files
lichtkasten/Sources/LichtkastenCore/Metadata/ExifTool.swift
T
Lichtkasten DevandClaude Opus 5.5 1f63714b73 Bugfixes aus dem Projekt-Review (27 Punkte)
Datenverlust:
- Ingest löscht keine vorhandenen Fotos mehr: gleiche Namen (zweiter Body/zweite Karte) bekommen -1, -2 …
- Ingest-Vorlage nur auf die neu kopierten Fotos, nicht auf den ganzen Ordner
- Neue Dateien brechen das Laden der Metadaten nicht mehr ab
- Code-Dateien in Windows-1252/Mac Roman werden nicht mehr als UTF-16-Zeichensalat gelesen
- Code-Bibliothek und Teams werden tolerant gelesen (fehlende Felder löschen nichts mehr)
- IPTC-Fenster speichert offene Änderungen, wenn das Bild von außen gewechselt wird
- Datum mit Uhrzeit bleibt beim Speichern erhalten; Lightroom-„abgelehnt“ (-1) bleibt erhalten
- gesperrte Fotos: beim Ingest nur getaggt, Sterne aus der Kamera bleiben

Zuverlässigkeit:
- exiftool-Fehlermeldungen werden sicher erkannt (Marker auf stderr statt 5 ms warten)
- ein defektes Bild kostet nicht mehr 49 andere ihre Metadaten
- LR-Export: Upload/IPTC auch nach Ordnerwechsel, Zeitlimit für Jobs ohne Antwort
- Trikot-Erkennung bleibt beim Ordnerwechsel beim richtigen Ordner; nach Ingest mit den neuen Fotos
- Absturz beim Löschen eines FTP-Servers behoben
- doppelte Namen beim FTP-Umbenennen werden nummeriert; Wiederholen öffnet die Aufgabe wieder
- Vorschau-Cache beachtet die angeforderte Größe (echte 100 %-Ansicht)
- Ingest: Verlauf auch bei Abbruch gespeichert, keine Lücken in der Laufnummer
- Auswerfen schließt keine Tabs anderer Karten; eigener exiftool-Pfad hat Vorrang

Tempo: Massenänderungen sortieren die Liste einmal statt pro Bild, Einstellungen werden verzögert gespeichert.
Tests für Namenskollision, Kodierung, tolerante Code-Bibliothek und Datum mit Uhrzeit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
2026-11-05 08:08:06 +00:00

262 lines
11 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
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? {
// the path set in Settings first, then a bundled copy, then the usual install locations
if let custom, !custom.isEmpty, FileManager.default.isExecutableFile(atPath: custom) {
return URL(fileURLWithPath: custom)
}
if let bundled = Bundle.main.url(forResource: "exiftool", withExtension: nil, subdirectory: "exiftool") {
return bundled
}
return searchPaths.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()
// -echo4 prints the marker on stderr after the command finished → all its messages are in the buffer
let errMarker = "{done\(counter)}"
let payload = (args.map { $0.replacingOccurrences(of: "\n", with: " ") } + ["-echo4", errMarker, "-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: wait for our marker (max. 5 s)
let errMarkerData = Data(errMarker.utf8)
var err = ""
let deadline = Date().addingTimeInterval(5)
while true {
stderrLock.lock(); let buf = stderrBuffer; stderrLock.unlock()
if let r = buf.range(of: errMarkerData) {
err = String(decoding: buf[buf.startIndex..<r.lowerBound], as: UTF8.self)
break
}
if Date() > deadline { err = String(decoding: buf, as: UTF8.self); break }
Thread.sleep(forTimeInterval: 0.002)
}
return (String(decoding: out, as: UTF8.self), err.trimmingCharacters(in: .whitespacesAndNewlines))
}
/// 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#",
"-IPTC:Prefs#", "-XMP-photomech:Prefs#",
"-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)
} else {
// one broken file must not cost the other 49 their metadata → file by file
for file in chunk {
if let meta = try? await worker.readMetadata(files: [file]) { await onChunk(meta) }
}
}
}
}
}
}
}
}