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
This commit is contained in:
Lichtkasten DevandClaude Opus 5.5 committed 2026-11-05 08:08:06 +00:00
1 parent dd022b6900
commit 1f63714b73
12 files changed
+299 -56

No files matched your search

@@ -193,6 +193,8 @@ public enum IngestService {
let destRoots = [settings.primaryDestination] + (settings.secondaryEnabled && !settings.backupDestination.isEmpty ? [settings.backupDestination] : [])
progress(IngestProgress(done: 0, total: total, currentFile: "Starte …"))
// also after a cancel/error: what was copied is not copied again next time
defer { if settings.incremental { saveHistory(history) } }
for e in entries {
try Task.checkCancellation()
let item = e.item
@@ -204,7 +206,6 @@ public enum IngestService {
if settings.renameEnabled, !settings.renamePattern.isEmpty {
baseName = VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-")
}
if settings.sequenceEnabled { seq += 1 }
// Card structure (DCIM/100NZ8_1) below the destination if requested
let rel = settings.preserveStructure
? item.primary.deletingLastPathComponent().path.replacingOccurrences(of: e.root.path, with: "")
@@ -218,9 +219,24 @@ public enum IngestService {
case .nonRawOnly: rawFiles = rawFiles.filter { !FileKind(url: $0).isRawLike }
}
guard !rawFiles.isEmpty else { continue }
if settings.sequenceEnabled { seq += 1 } // only photos that are really copied get a number
var files = rawFiles
if item.kind.usesSidecar, fm.fileExists(atPath: item.sidecarURL.path), rawFiles.contains(item.primary) { files.append(item.sidecarURL) }
// Name for this photo in every destination: an existing file is never deleted. Same name + same size
// = already copied (skip); same name, other photo (second body, second card) → "-1", "-2" …
var targetName = baseName
var skipGroup = false
if let primaryFolder = destRoots.first.map({ root -> URL in
var f = URL(fileURLWithPath: root)
if !sub.isEmpty { f.appendPathComponent(sub, isDirectory: true) }
if !rel.isEmpty { f.appendPathComponent(rel, isDirectory: true) }
return f
}) {
(targetName, skipGroup) = uniqueName(baseName, files: files, in: primaryFolder,
skipDuplicates: settings.skipDuplicates)
}
for destRoot in destRoots {
var folder = URL(fileURLWithPath: destRoot)
if !sub.isEmpty { folder.appendPathComponent(sub, isDirectory: true) }
@@ -229,10 +245,11 @@ public enum IngestService {
let isPrimary = destRoot == settings.primaryDestination
if isPrimary, usedFolders.insert(folder).inserted { onFolder?(folder) }
for (n, src) in files.enumerated() {
let dest = folder.appendingPathComponent(baseName).appendingPathExtension(src.pathExtension)
if fm.fileExists(atPath: dest.path) {
if settings.skipDuplicates, sameSize(src, dest) { continue }
try fm.removeItem(at: dest)
let dest = folder.appendingPathComponent(targetName).appendingPathExtension(src.pathExtension)
if skipGroup || fm.fileExists(atPath: dest.path) {
// already there (duplicate, or the backup already has it) – never overwrite
if isPrimary, n == 0, src.pathExtension.lowercased() != "xmp" { done += 1 }
continue
}
try copy(src, to: dest)
if isPrimary {
@@ -249,7 +266,6 @@ public enum IngestService {
}
if settings.incremental { history.insert(historyKey(item.primary)) }
}
if settings.incremental { saveHistory(history) }
return IngestResult(folders: Array(usedFolders).sorted { $0.path < $1.path }, copied: copied,
lockedCopies: lockedCopies, nextSequence: seq, skipped: skipped)
}
@@ -270,6 +286,21 @@ public enum IngestService {
return last.isEmpty ? "diskutil eject fehlgeschlagen" : last
}
/// Base name that collides with no other photo in `folder`. If the photo itself is already there
/// (same name and size of its main file) and duplicates are skipped, `skip` is true.
static func uniqueName(_ base: String, files: [URL], in folder: URL, skipDuplicates: Bool) -> (name: String, skip: Bool) {
let fm = FileManager.default
func dest(_ name: String, _ src: URL) -> URL { folder.appendingPathComponent(name).appendingPathExtension(src.pathExtension) }
if let main = files.first, fm.fileExists(atPath: dest(base, main).path) {
if skipDuplicates, sameSize(main, dest(base, main)) { return (base, true) }
} else if !files.contains(where: { fm.fileExists(atPath: dest(base, $0).path) }) {
return (base, false)
}
var n = 1
while files.contains(where: { fm.fileExists(atPath: dest("\(base)-\(n)", $0).path) }) { n += 1 }
return ("\(base)-\(n)", false)
}
static func sameSize(_ a: URL, _ b: URL) -> Bool {
func size(_ u: URL) -> Int64? {
guard let attrs = try? FileManager.default.attributesOfItem(atPath: u.path) else { return nil }
@@ -148,7 +148,7 @@ public struct PhotoItem: Identifiable, Hashable, Sendable {
}
/// PM Prefs string for the current state.
public var pmPrefsString: String { "\(tagged ? 1 : 0):\(label?.pmColorClass ?? 0):\(rating):\(pmFrame)" }
public var pmPrefsString: String { "\(tagged ? 1 : 0):\(label?.pmColorClass ?? 0):\(max(0, rating)):\(pmFrame)" }
/// Applies exiftool output (primary file + optional sidecar) to the item.
public mutating func apply(fileMeta: [String: MetadataValue], sidecarMeta: [String: MetadataValue]?) {
@@ -183,7 +183,11 @@ public struct PhotoItem: Identifiable, Hashable, Sendable {
if !l.isEmpty { values.lists[field.id] = l }
} else {
var s = v.string
if field.id == "dateCreated" { s = String(s.prefix(10)).replacingOccurrences(of: ":", with: "-") }
if field.id == "dateCreated" {
// "2026:11:02 18:31:05+01:00" → "2026-11-02 18:31:05+01:00" – keep the time of day,
// otherwise every save of the field would cut it from XMP DateCreated
s = String(s.prefix(10)).replacingOccurrences(of: ":", with: "-") + String(s.dropFirst(10))
}
if !s.isEmpty { values.text[field.id] = s }
}
}
@@ -31,6 +31,19 @@ public struct CodeSet: Codable, Hashable, Identifiable, Sendable {
self.name = name; self.entries = entries; self.sourcePath = sourcePath
}
enum CodingKeys: String, CodingKey { case id, name, enabled, entries, sourcePath, sourceModified }
/// Tolerant: a missing/new field must never cost the players.
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = (try? c.decode(UUID.self, forKey: .id)) ?? UUID()
name = (try? c.decode(String.self, forKey: .name)) ?? "Team"
enabled = (try? c.decode(Bool.self, forKey: .enabled)) ?? true
entries = (try? c.decode([CodeEntry].self, forKey: .entries)) ?? []
sourcePath = try? c.decode(String.self, forKey: .sourcePath)
sourceModified = try? c.decode(Date.self, forKey: .sourceModified)
}
/// Adds only codes that are not in the team yet (existing players stay untouched).
@discardableResult
public mutating func merge(_ new: [CodeEntry]) -> (added: Int, existing: Int) {
@@ -56,6 +69,18 @@ public struct CodeLibrary: Codable, Sendable {
public init() {}
enum CodingKeys: String, CodingKey { case sets, delimiter, defaultReplacement, bareCodes, autoReload }
/// Tolerant decoding (see CodeSet).
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
sets = (try? c.decode([CodeSet].self, forKey: .sets)) ?? []
delimiter = (try? c.decode(String.self, forKey: .delimiter)) ?? "\\"
defaultReplacement = (try? c.decode(String.self, forKey: .defaultReplacement)) ?? ""
bareCodes = (try? c.decode(Bool.self, forKey: .bareCodes)) ?? true
autoReload = (try? c.decode(Bool.self, forKey: .autoReload)) ?? false
}
/// Flat lookup table for the enabled teams – first team in the list wins on duplicate codes.
public var replacements: CodeReplacements {
var table: [String: [String]] = [:]
@@ -87,7 +112,11 @@ public struct CodeLibrary: Codable, Sendable {
/// Reads a code file in UTF-8, UTF-16 (PM sometimes saves that), Windows-1252 or Mac Roman.
public static func readText(_ url: URL) throws -> String {
let data = try Data(contentsOf: url)
for enc in [String.Encoding.utf8, .utf16, .windowsCP1252, .macOSRoman] {
// UTF-16 only with a byte order mark – without one, almost any Latin-1 file "decodes" as UTF-16 garbage
if data.starts(with: [0xFF, 0xFE]) || data.starts(with: [0xFE, 0xFF]), let s = String(data: data, encoding: .utf16) {
return s
}
for enc in [String.Encoding.utf8, .windowsCP1252, .macOSRoman] {
if let s = String(data: data, encoding: enc) { return s }
}
return String(decoding: data, as: UTF8.self)
@@ -19,11 +19,14 @@ 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
// 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 candidates.map { URL(fileURLWithPath: $0) }.first { FileManager.default.isExecutableFile(atPath: $0.path) }
return searchPaths.map { URL(fileURLWithPath: $0) }.first { FileManager.default.isExecutableFile(atPath: $0.path) }
}
private let executable: URL
@@ -87,7 +90,10 @@ public final class ExifTool: @unchecked Sendable {
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"
// -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)
@@ -100,10 +106,20 @@ public final class ExifTool: @unchecked Sendable {
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)
// 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`.
@@ -229,7 +245,14 @@ public final class ExifToolPool: @unchecked Sendable {
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) }
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) }
}
}
}
}
}
@@ -42,7 +42,8 @@ public struct MetadataWriter: Sendable {
let prefs = item.pmPrefsString
for target in item.metadataTargets {
var args = ["-overwrite_original", "-m",
"-XMP-xmp:Rating=\(max(0, min(5, item.rating)))",
// -1 = rejected in Lightroom – keep it
"-XMP-xmp:Rating=\(max(-1, min(5, item.rating)))",
"-XMP-photomech:Tagged=\(item.tagged ? "Yes" : "No")",
"-XMP-photomech:Prefs=\(prefs)"]
if let l = item.label {