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

+84 -27
View File
@@ -113,12 +113,28 @@ final class AppState: ObservableObject {
@Published var templates: [IPTCTemplate] = [] { didSet { Storage.save(templates, to: Storage.templatesURL) } }
@Published var settings: AppSettings {
didSet {
Storage.save(settings, to: Storage.settingsURL)
scheduleSettingsSave()
if settings.jersey.teams != oldValue.jersey.teams { syncKitsToProfiles() }
}
}
/// Spieltag assistant: teams, competitions, patterns, created matches
@Published var spieltag: SpieltagLibrary { didSet { Storage.save(spieltag, to: Storage.spieltagURL) } }
@Published var spieltag: SpieltagLibrary { didSet { scheduleSettingsSave() } }
private var settingsSaveTask: Task<Void, Never>?
/// Text fields are bound directly to the settings – write the files once typing pauses, not per key.
private func scheduleSettingsSave() {
settingsSaveTask?.cancel()
settingsSaveTask = Task { [weak self] in
try? await Task.sleep(nanoseconds: 600_000_000)
guard !Task.isCancelled else { return }
self?.flushSettings()
}
}
func flushSettings() {
Storage.save(settings, to: Storage.settingsURL)
Storage.save(spieltag, to: Storage.spieltagURL)
}
@Published var showSpieltag = false
/// Teams with player codes (PM: list of code replacement files).
@Published var codeLibrary: CodeLibrary {
@@ -179,6 +195,8 @@ final class AppState: ObservableObject {
private var lrPollTimer: Timer?
private var codeReloadTimer: Timer?
private var pendingLRJobs: [String: LightroomJob] = [:]
/// source photos of each job (with their IPTC) – the folder may have changed when the result arrives
private var pendingLRSources: [String: [PhotoItem]] = [:]
@Published var lrPendingCount = 0
/// Upload history ("Gesendet"-Status)
@@ -204,7 +222,7 @@ final class AppState: ObservableObject {
sentLog = Storage.load(SentLog.self, from: Storage.sentLogURL) ?? SentLog()
uploads.state = self
_ = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.flushSentLog() }
MainActor.assumeIsolated { self?.flushSentLog(); self?.flushSettings() }
}
seedDefaultsIfNeeded()
startLightroomPolling()
@@ -454,8 +472,9 @@ final class AppState: ObservableObject {
/// Closes everything of ours that could keep the card busy (open tab on the card, folder watcher).
private func ejectReleaseCardHandles(_ volumes: [URL]) {
for v in volumes {
for tab in tabs where tab.path.hasPrefix(v.path) { closeTab(tab) }
if let f = folder, f.path.hasPrefix(v.path) { folderWatcher.watch(nil) }
func onVolume(_ u: URL) -> Bool { u.path == v.path || u.path.hasPrefix(v.path + "/") }
for tab in tabs where onVolume(tab) { closeTab(tab) }
if let f = folder, onVolume(f) { folderWatcher.watch(nil) }
}
}
@@ -526,15 +545,19 @@ final class AppState: ObservableObject {
if settings.tagLockedPhotos, !result.lockedCopies.isEmpty, let w = self.writer {
self.tasks.update(taskID, detail: "Tagge \(result.lockedCopies.count) gesperrte Fotos …")
for url in result.lockedCopies {
var item = PhotoItem(primary: url)
item.tagged = true
try? await w.writeState(of: item)
// only the tag – stars / color class set in the camera stay
try? await w.writeTag(true, to: PhotoItem(primary: url))
}
}
if let template {
self.tasks.update(taskID, detail: "Wende Vorlage „\(template.name)“ an …")
let copied = Set(result.copied.map(\.standardizedFileURL.path))
for f in result.folders {
let found = try FolderScanner.scan(folder: f)
// only the photos of this ingest – older (captioned) photos in the folder stay untouched
let found = try FolderScanner.scan(folder: f).filter { item in
([item.primary] + item.companions).contains { copied.contains($0.standardizedFileURL.path) }
}
guard !found.isEmpty else { continue }
let meta = try await et.readMetadata(files: found.map(\.primary))
let loaded = found.map { item -> PhotoItem in
var i = item
@@ -548,14 +571,14 @@ final class AppState: ObservableObject {
if result.skipped > 0 { detail += ", \(result.skipped) bereits importiert übersprungen" }
if !result.lockedCopies.isEmpty { detail += ", \(result.lockedCopies.count) gesperrt" + (settings.tagLockedPhotos ? " → getaggt" : "") }
self.tasks.finish(taskID, detail: detail + ejectNote)
if self.settings.jersey.autoAfterIngest, !self.settings.jersey.teams.isEmpty,
let current = self.folder, result.folders.contains(current) {
self.recognizeJerseys()
}
if let current = self.folder, result.folders.contains(current) {
self.metadataCache = nil
self.refreshFolder()
await self.loadMetadata(for: self.items)
// after the refresh, so the new photos are part of it
if self.settings.jersey.autoAfterIngest, !self.settings.jersey.teams.isEmpty {
self.recognizeJerseys()
}
}
} catch is CancellationError {
self.tasks.cancel(taskID)
@@ -614,6 +637,7 @@ final class AppState: ObservableObject {
private var readPool: ExifToolPool?
private var metadataCache: MetadataCache?
private var metadataGeneration = 0
private var activeMetadataLoads = 0
/// Cache first (instant), then the remaining files with several exiftool processes in parallel.
func loadMetadata(for snapshot: [PhotoItem]) async {
@@ -624,10 +648,13 @@ final class AppState: ObservableObject {
metadataCache?.save()
metadataCache = MetadataCache(folder: folder)
metadataCacheFolder = folder
// only a new folder (or reload) makes running loads obsolete – new files arriving do not
metadataGeneration += 1
}
guard let pool = readPool, let cache = metadataCache else { return }
metadataGeneration += 1
let generation = metadataGeneration
activeMetadataLoads += 1
defer { activeMetadataLoads -= 1 }
loadingMetadata = true
// 1. cache hits
@@ -672,7 +699,7 @@ final class AppState: ObservableObject {
}
cache.save()
}
if metadataGeneration == generation {
if metadataGeneration == generation && activeMetadataLoads == 1 {
loadingMetadata = false
statusText = "\(items.count) Bilder"
}
@@ -730,9 +757,9 @@ final class AppState: ObservableObject {
// MARK: Rating / labels / tags
private func mutate(_ targets: [PhotoItem], _ change: (inout PhotoItem) -> Void) {
private func mutate(_ targets: [PhotoItem], rebuild: Bool = true, _ change: (inout PhotoItem) -> Void) {
for t in targets { if let i = indexByID[t.id] { change(&items[i]) } }
rebuildVisible()
if rebuild { rebuildVisible() }
}
private var actionTargets: [PhotoItem] {
@@ -835,6 +862,7 @@ final class AppState: ObservableObject {
var before: [PhotoItem] = []
var after: [PhotoItem] = []
defer {
rebuildVisible() // once for all images instead of once per image
if recordUndo && !after.isEmpty {
let title = (fields.count == 1 ? "IPTC: \(fields[0].label)" : "IPTC: \(fields.count) Felder") + countSuffix(after.count)
pushUndo(UndoEntry(title: title, kind: .iptc(fields), before: before, after: after))
@@ -850,7 +878,8 @@ final class AppState: ObservableObject {
do {
let old = item(t.id) ?? t
try await w.write(values: expanded, fields: fields, to: t)
mutate([t]) { $0.iptc = expanded }
mutate([t], rebuild: false) { $0.iptc = expanded }
if count % 50 == 49 { rebuildVisible() } // visible progress on big selections
before.append(old)
after.append(item(t.id) ?? { var n = t; n.iptc = expanded; return n }())
count += 1
@@ -888,7 +917,8 @@ final class AppState: ObservableObject {
let before = current(targets)
do {
let result = try await w.apply(template: template, to: targets, codes: codes, dateFormat: settings.dateFormat)
for t in targets { if let v = result[t.id] { mutate([t]) { $0.iptc = v } } }
for t in targets { if let v = result[t.id] { mutate([t], rebuild: false) { $0.iptc = v } } }
rebuildVisible()
if recordUndo {
let after = targets.map { t -> PhotoItem in
if let cur = item(t.id) { return cur }
@@ -995,6 +1025,7 @@ final class AppState: ObservableObject {
do {
try LightroomBridge.submit(job)
pendingLRJobs[job.id] = job
pendingLRSources[job.id] = targets
lrPendingCount = pendingLRJobs.count
let what = export ? "Import + JPEG-Export nach \(exportFolder.lastPathComponent)" : develop ? "Bearbeiten" : "Import"
lrTaskIDs[job.id] = tasks.start(.lightroom, title: "Lightroom: \(what) (\(targets.count) Bild(er))", total: targets.count)
@@ -1024,8 +1055,18 @@ final class AppState: ObservableObject {
private func pollLightroom() {
guard !pendingLRJobs.isEmpty else { return }
// no answer from the plugin for 30 min (LR closed, plugin error) → give up instead of "running" forever
for (id, job) in pendingLRJobs where Date().timeIntervalSince(job.created) > 30 * 60 {
pendingLRJobs[id] = nil
pendingLRSources[id] = nil
if let tid = lrTaskIDs.removeValue(forKey: id) {
tasks.finish(tid, error: "Keine Antwort von Lightroom – läuft Lightroom Classic mit dem Lichtkasten-Plugin?")
}
}
lrPendingCount = pendingLRJobs.count
for result in LightroomBridge.collectResults() {
let job = pendingLRJobs.removeValue(forKey: result.id)
let jobSources = pendingLRSources.removeValue(forKey: result.id) ?? []
lrPendingCount = pendingLRJobs.count
if let tid = lrTaskIDs.removeValue(forKey: result.id) {
let detail = "\(result.imported) importiert" + (result.exported.isEmpty ? "" : ", \(result.exported.count) JPEG(s) exportiert")
@@ -1036,14 +1077,15 @@ final class AppState: ObservableObject {
}
statusText = "Lightroom: \(result.imported) importiert, \(result.exported.count) JPEG(s) exportiert"
guard let job, !result.exported.isEmpty else { continue }
Task { await handleExported(result.exported, job: job) }
Task { await handleExported(result.exported, job: job, sources: jobSources) }
}
}
/// After LR export: re-apply the original IPTC (PM-identical structure) and upload.
private func handleExported(_ files: [URL], job: LightroomJob) async {
private func handleExported(_ files: [URL], job: LightroomJob, sources jobSources: [PhotoItem]) async {
// Map exported JPEG → source item by base name (LR keeps the file name, may append "-2").
let sources = job.files.compactMap { f in items.first { $0.primary == f || $0.companions.contains(f) } }
// Current state if the photo is still open (IPTC edited meanwhile), else the copy from the job.
let sources = jobSources.map { item($0.id) ?? $0 }
if job.rewriteIPTCAfterExport, let w = writer {
for file in files {
let base = file.deletingPathExtension().lastPathComponent
@@ -1308,8 +1350,9 @@ final class AppState: ObservableObject {
return s.prefix(3).map { "#\($0.number)" }.joined(separator: " ")
}
private var jerseyCacheURL: URL? {
guard let f = folder else { return nil }
private var jerseyCacheURL: URL? { folder.map(jerseyCacheURL(for:)) }
private func jerseyCacheURL(for f: URL) -> URL {
var h: UInt64 = 0xcbf29ce484222325
for b in f.standardizedFileURL.path.utf8 { h = (h ^ UInt64(b)) &* 0x100000001b3 }
// "jersey2": results of the improved recognizer (older caches are ignored → recognized again)
@@ -1330,6 +1373,17 @@ final class AppState: ObservableObject {
if let d = try? JSONEncoder().encode(JerseyCache(suggestions: jerseySuggestions, done: jerseyDone)) { try? d.write(to: u, options: .atomic) }
}
/// Results of a recognition run belong to the folder it was started in – even if another folder is open now.
private func storeJerseyResults(_ results: [String: [JerseySuggestion]], folder f: URL?) {
guard let f else { return }
if folder == f { saveJerseyCache(); return }
let u = jerseyCacheURL(for: f)
var c = (try? Data(contentsOf: u)).flatMap { try? JSONDecoder().decode(JerseyCache.self, from: $0) }
?? JerseyCache(suggestions: [:], done: [:])
c.suggestions.merge(results) { _, new in new }
if let d = try? JSONEncoder().encode(c) { try? d.write(to: u, options: .atomic) }
}
/// Runs the recognition in the background (task window shows progress, cancellable).
func recognizeJerseys(_ targets: [PhotoItem]? = nil, onlyNew: Bool = true) {
guard jerseyTask == nil else { return }
@@ -1345,9 +1399,11 @@ final class AppState: ObservableObject {
let taskID = tasks.start(.metadata, title: "Trikotnummern erkennen (\(jobs.count) Bilder)", total: jobs.count) { [weak self] in
self?.jerseyTask?.cancel()
}
let startFolder = folder
jerseyTask = Task { [weak self] in
var done = 0
var found = 0
var collected: [String: [JerseySuggestion]] = [:]
await withTaskGroup(of: (String, [JerseySuggestion]).self) { group in
var next = 0
let parallel = 4
@@ -1360,16 +1416,17 @@ final class AppState: ObservableObject {
while let (id, result) = await group.next() {
guard let self else { return }
if Task.isCancelled { group.cancelAll(); break }
self.jerseySuggestions[id] = result
collected[id] = result
if self.folder == startFolder { self.jerseySuggestions[id] = result }
done += 1
if result.contains(where: { $0.replacement != nil }) { found += 1 }
self.tasks.update(taskID, done: done, detail: "\(found) Bilder mit Spieler-Vorschlag")
if done % 20 == 0 { self.saveJerseyCache() }
if done % 20 == 0 { self.storeJerseyResults(collected, folder: startFolder) }
add()
}
}
guard let self else { return }
self.saveJerseyCache()
self.storeJerseyResults(collected, folder: startFolder)
self.jerseyTask = nil
if Task.isCancelled { self.tasks.cancel(taskID) } else {
self.tasks.finish(taskID, detail: "\(found) von \(done) Bildern mit Vorschlag")
+14 -3
View File
@@ -10,6 +10,9 @@ final class ImageLoader: @unchecked Sendable {
private let thumbs = NSCache<NSString, NSImage>()
private let previews = NSCache<NSString, NSImage>()
private let queue = OperationQueue()
/// size each cached preview was rendered for – a 2000 px preview must not serve a 9000 px (100 %) request
private var previewSizes: [String: Int] = [:]
private let sizeLock = NSLock()
init() {
thumbs.countLimit = 4000
@@ -32,19 +35,27 @@ final class ImageLoader: @unchecked Sendable {
}
}
private func cachedSize(_ url: URL) -> Int {
sizeLock.lock(); defer { sizeLock.unlock() }
return previewSizes[url.path] ?? 0
}
func preview(for url: URL, maxPixel: Int = 3200) async -> NSImage? {
if let c = cachedPreview(url) { return c }
if let c = cachedPreview(url), cachedSize(url) >= maxPixel { return c }
return await withCheckedContinuation { cont in
queue.addOperation {
let img = Self.makeImage(url, maxPixel: maxPixel, minAcceptable: 1400)
if let img { self.previews.setObject(img, forKey: url.path as NSString) }
if let img {
self.previews.setObject(img, forKey: url.path as NSString)
self.sizeLock.lock(); self.previewSizes[url.path] = maxPixel; self.sizeLock.unlock()
}
cont.resume(returning: img)
}
}
}
func prefetchPreviews(_ urls: [URL]) {
for u in urls where cachedPreview(u) == nil {
for u in urls where cachedPreview(u) == nil || cachedSize(u) < 3200 {
Task { _ = await preview(for: u) }
}
}
@@ -74,6 +74,14 @@ final class TaskCenter: ObservableObject {
}
}
/// A finished task runs again (e.g. retrying failed uploads).
func reopen(_ id: UUID, cancel: (() -> Void)? = nil) {
guard let i = tasks.firstIndex(where: { $0.id == id }) else { return }
tasks[i].state = .running
tasks[i].finished = nil
if let cancel { cancelHandlers[id] = cancel }
}
func canCancel(_ id: UUID) -> Bool { cancelHandlers[id] != nil }
func clearFinished() { tasks.removeAll { !$0.isRunning } }
+21 -4
View File
@@ -35,7 +35,6 @@ final class UploadQueue: ObservableObject {
private var running = 0
private let maxParallel = 2
private var immichClient: ImmichClient?
private var immichAlbumId: String?
/// album name → new asset ids
private var immichNewAssets: [String: [String]] = [:]
@@ -123,6 +122,7 @@ final class UploadQueue: ObservableObject {
if let b = batchRef { self?.cancelBatch(b) }
}
batchRef = batch
var usedNames = Set<String>()
for f in files {
let src = sourceItems.first { $0.primary == f || $0.companions.contains(f) }
var remote = f.lastPathComponent
@@ -132,6 +132,15 @@ final class UploadQueue: ObservableObject {
remote = VariableExpander.expand(pattern, context: ctx)
.replacingOccurrences(of: "/", with: "-") + "." + f.pathExtension.lowercased()
}
// a pattern without {filenamebase}/{seqn} gives many images the same name → they would overwrite
// each other on the server: number the duplicates
if usedNames.contains(remote.lowercased()) {
let ext = (remote as NSString).pathExtension, stem = (remote as NSString).deletingPathExtension
var n = 2
while usedNames.contains("\(stem)-\(n).\(ext)".lowercased()) { n += 1 }
remote = "\(stem)-\(n).\(ext)"
}
usedNames.insert(remote.lowercased())
var job = UploadJob(file: f, target: target, targetName: name, remoteName: remote, captureDate: src?.captureDate)
job.batch = batch
job.fileSize = ((try? FileManager.default.attributesOfItem(atPath: f.path)[.size]) as? NSNumber)?.int64Value ?? 0
@@ -144,7 +153,15 @@ final class UploadQueue: ObservableObject {
}
func retryFailed() {
for i in jobs.indices { if case .failed = jobs[i].status { jobs[i].status = .waiting; jobs[i].attempts = 0 } }
var batches = Set<UUID>()
for i in jobs.indices {
if case .failed = jobs[i].status {
jobs[i].status = .waiting; jobs[i].attempts = 0
if let b = jobs[i].batch { batches.insert(b) }
}
}
// the task rows were already "failed" – make them run again so the result is shown
for b in batches { state?.tasks.reopen(b) { [weak self] in self?.cancelBatch(b) } }
pump()
}
@@ -179,7 +196,7 @@ final class UploadQueue: ObservableObject {
private func run(_ job: UploadJob) async {
defer { running -= 1; pump() }
guard let state else { return }
guard let state else { setStatus(job.id, .failed("App-Zustand nicht verfügbar")); return }
startRateTimer()
let jobID = job.id
// progress callbacks arrive on background threads → hop to the main actor
@@ -229,7 +246,7 @@ final class UploadQueue: ObservableObject {
}
/// Settings changed → rebuild client next time.
func resetImmich() { immichClient = nil; immichAlbumId = nil }
func resetImmich() { immichClient = nil }
private func finishImmichBatch() {
guard !immichNewAssets.isEmpty, let state, let client = immichClient else { return }
+16 -2
View File
@@ -53,7 +53,20 @@ struct IPTCInfoWindow: View {
.onDisappear {
if let m = arrowMonitor { NSEvent.removeMonitor(m); arrowMonitor = nil }
}
.onChange(of: state.cursorID) { _, _ in load(force: true) }
.onChange(of: state.cursorID) { _, _ in
// cursor moved from outside (click in the contact sheet …) while edits are open → keep them:
// they are saved to the image they were typed for instead of being thrown away
if !dirty.isEmpty, let id = loadedID, id != state.cursorID, let previous = state.item(id) {
let fields = IPTCField.all.filter { dirty.contains($0.id) }
let values = IPTCValues(texts: texts)
Task {
if await state.applyIPTCAndWait(values, fields: fields, to: [previous]) {
state.statusText = "Änderungen an \(previous.filename) gespeichert"
}
}
}
load(force: true)
}
.onReceive(state.$items) { _ in if dirty.isEmpty { DispatchQueue.main.async { load(force: false) } } }
.task(id: item.map { state.previewURL(for: $0) }) { await loadImage() }
}
@@ -275,7 +288,8 @@ struct IPTCInfoWindow: View {
@discardableResult
private func save() async -> Bool {
guard let item, !dirty.isEmpty else { return true }
// the image the form was loaded for (not whatever the cursor points at right now)
guard let item = loadedID.flatMap({ state.item($0) }) ?? item, !dirty.isEmpty else { return true }
saving = true
defer { saving = false }
let fields = IPTCField.all.filter { dirty.contains($0.id) }
+8 -2
View File
@@ -135,8 +135,14 @@ struct FTPSettings: View {
HStack {
Button { let d = FTPDestination(); state.settings.ftpDestinations.append(d); selected = d.id } label: { Image(systemName: "plus") }
Button {
if let i = index { Keychain.set("", account: state.settings.ftpDestinations[i].keychainAccount)
state.settings.ftpDestinations.remove(at: i); selected = nil }
// first leave the form (its bindings use the index), then remove by id – otherwise
// SwiftUI may still read the old index → "Index out of range"
guard let id = selected, let d = state.settings.ftpDestinations.first(where: { $0.id == id }) else { return }
selected = nil
DispatchQueue.main.async {
Keychain.set("", account: d.keychainAccount)
state.settings.ftpDestinations.removeAll { $0.id == id }
}
} label: { Image(systemName: "minus") }.disabled(index == nil)
Spacer()
}
@@ -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 {
@@ -377,3 +377,45 @@ final class SentLogTests: XCTestCase {
XCTAssertFalse(log.wasSent(item))
}
}
final class BugfixTests: XCTestCase {
private func tempDir() throws -> URL {
let d = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)
return d
}
func testIngestNeverOverwritesOtherPhotoWithSameName() throws {
let src = try tempDir(), dest = try tempDir()
let card2 = src.appendingPathComponent("DSC_0001.NEF")
try Data(repeating: 2, count: 20).write(to: card2)
try Data(repeating: 1, count: 10).write(to: dest.appendingPathComponent("DSC_0001.NEF")) // card 1, other photo
let r = IngestService.uniqueName("DSC_0001", files: [card2], in: dest, skipDuplicates: true)
XCTAssertEqual(r.name, "DSC_0001-1")
XCTAssertFalse(r.skip)
// the same photo again (same size) is recognised as already copied
try Data(repeating: 2, count: 20).write(to: dest.appendingPathComponent("DSC_0002.NEF"))
let same = src.appendingPathComponent("DSC_0002.NEF")
try Data(repeating: 2, count: 20).write(to: same)
XCTAssertTrue(IngestService.uniqueName("DSC_0002", files: [same], in: dest, skipDuplicates: true).skip)
}
func testCodeFileInWindowsEncodingIsNotReadAsUTF16() throws {
let f = try tempDir().appendingPathComponent("kader.txt")
try "w7\tLena M\u{fc}ller\n".data(using: .windowsCP1252)!.write(to: f)
XCTAssertTrue(try CodeLibrary.readText(f).contains("Lena Müller"))
}
func testCodeLibraryDecodesWithMissingFields() throws {
let json = #"{"sets":[{"name":"VfL","entries":[{"code":"w10","columns":["Svenja Huth"]}]}]}"#
let lib = try JSONDecoder().decode(CodeLibrary.self, from: Data(json.utf8))
XCTAssertEqual(lib.sets.first?.entries.first?.code, "w10")
XCTAssertTrue(lib.sets.first?.enabled ?? false)
}
func testDateCreatedKeepsTimeOfDay() {
var item = PhotoItem(primary: URL(fileURLWithPath: "/x/a.jpg"))
item.apply(fileMeta: ["XMP-photoshop:DateCreated": .string("2026:11:02 18:31:05+01:00")], sidecarMeta: nil)
XCTAssertEqual(item.iptc.text["dateCreated"], "2026-11-02 18:31:05+01:00")
}
}