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:
1 parent
dd022b6900
commit
1f63714b73
12 files changed
+299
-56
No files matched your search
@@ -113,12 +113,28 @@ final class AppState: ObservableObject {
|
|||||||
@Published var templates: [IPTCTemplate] = [] { didSet { Storage.save(templates, to: Storage.templatesURL) } }
|
@Published var templates: [IPTCTemplate] = [] { didSet { Storage.save(templates, to: Storage.templatesURL) } }
|
||||||
@Published var settings: AppSettings {
|
@Published var settings: AppSettings {
|
||||||
didSet {
|
didSet {
|
||||||
Storage.save(settings, to: Storage.settingsURL)
|
scheduleSettingsSave()
|
||||||
if settings.jersey.teams != oldValue.jersey.teams { syncKitsToProfiles() }
|
if settings.jersey.teams != oldValue.jersey.teams { syncKitsToProfiles() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Spieltag assistant: teams, competitions, patterns, created matches
|
/// 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
|
@Published var showSpieltag = false
|
||||||
/// Teams with player codes (PM: list of code replacement files).
|
/// Teams with player codes (PM: list of code replacement files).
|
||||||
@Published var codeLibrary: CodeLibrary {
|
@Published var codeLibrary: CodeLibrary {
|
||||||
@@ -179,6 +195,8 @@ final class AppState: ObservableObject {
|
|||||||
private var lrPollTimer: Timer?
|
private var lrPollTimer: Timer?
|
||||||
private var codeReloadTimer: Timer?
|
private var codeReloadTimer: Timer?
|
||||||
private var pendingLRJobs: [String: LightroomJob] = [:]
|
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
|
@Published var lrPendingCount = 0
|
||||||
|
|
||||||
/// Upload history ("Gesendet"-Status)
|
/// Upload history ("Gesendet"-Status)
|
||||||
@@ -204,7 +222,7 @@ final class AppState: ObservableObject {
|
|||||||
sentLog = Storage.load(SentLog.self, from: Storage.sentLogURL) ?? SentLog()
|
sentLog = Storage.load(SentLog.self, from: Storage.sentLogURL) ?? SentLog()
|
||||||
uploads.state = self
|
uploads.state = self
|
||||||
_ = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: .main) { [weak self] _ in
|
_ = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: .main) { [weak self] _ in
|
||||||
MainActor.assumeIsolated { self?.flushSentLog() }
|
MainActor.assumeIsolated { self?.flushSentLog(); self?.flushSettings() }
|
||||||
}
|
}
|
||||||
seedDefaultsIfNeeded()
|
seedDefaultsIfNeeded()
|
||||||
startLightroomPolling()
|
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).
|
/// Closes everything of ours that could keep the card busy (open tab on the card, folder watcher).
|
||||||
private func ejectReleaseCardHandles(_ volumes: [URL]) {
|
private func ejectReleaseCardHandles(_ volumes: [URL]) {
|
||||||
for v in volumes {
|
for v in volumes {
|
||||||
for tab in tabs where tab.path.hasPrefix(v.path) { closeTab(tab) }
|
func onVolume(_ u: URL) -> Bool { u.path == v.path || u.path.hasPrefix(v.path + "/") }
|
||||||
if let f = folder, f.path.hasPrefix(v.path) { folderWatcher.watch(nil) }
|
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 {
|
if settings.tagLockedPhotos, !result.lockedCopies.isEmpty, let w = self.writer {
|
||||||
self.tasks.update(taskID, detail: "Tagge \(result.lockedCopies.count) gesperrte Fotos …")
|
self.tasks.update(taskID, detail: "Tagge \(result.lockedCopies.count) gesperrte Fotos …")
|
||||||
for url in result.lockedCopies {
|
for url in result.lockedCopies {
|
||||||
var item = PhotoItem(primary: url)
|
// only the tag – stars / color class set in the camera stay
|
||||||
item.tagged = true
|
try? await w.writeTag(true, to: PhotoItem(primary: url))
|
||||||
try? await w.writeState(of: item)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let template {
|
if let template {
|
||||||
self.tasks.update(taskID, detail: "Wende Vorlage „\(template.name)“ an …")
|
self.tasks.update(taskID, detail: "Wende Vorlage „\(template.name)“ an …")
|
||||||
|
let copied = Set(result.copied.map(\.standardizedFileURL.path))
|
||||||
for f in result.folders {
|
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 meta = try await et.readMetadata(files: found.map(\.primary))
|
||||||
let loaded = found.map { item -> PhotoItem in
|
let loaded = found.map { item -> PhotoItem in
|
||||||
var i = item
|
var i = item
|
||||||
@@ -548,14 +571,14 @@ final class AppState: ObservableObject {
|
|||||||
if result.skipped > 0 { detail += ", \(result.skipped) bereits importiert übersprungen" }
|
if result.skipped > 0 { detail += ", \(result.skipped) bereits importiert übersprungen" }
|
||||||
if !result.lockedCopies.isEmpty { detail += ", \(result.lockedCopies.count) gesperrt" + (settings.tagLockedPhotos ? " → getaggt" : "") }
|
if !result.lockedCopies.isEmpty { detail += ", \(result.lockedCopies.count) gesperrt" + (settings.tagLockedPhotos ? " → getaggt" : "") }
|
||||||
self.tasks.finish(taskID, detail: detail + ejectNote)
|
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) {
|
if let current = self.folder, result.folders.contains(current) {
|
||||||
self.metadataCache = nil
|
self.metadataCache = nil
|
||||||
self.refreshFolder()
|
self.refreshFolder()
|
||||||
await self.loadMetadata(for: self.items)
|
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 {
|
} catch is CancellationError {
|
||||||
self.tasks.cancel(taskID)
|
self.tasks.cancel(taskID)
|
||||||
@@ -614,6 +637,7 @@ final class AppState: ObservableObject {
|
|||||||
private var readPool: ExifToolPool?
|
private var readPool: ExifToolPool?
|
||||||
private var metadataCache: MetadataCache?
|
private var metadataCache: MetadataCache?
|
||||||
private var metadataGeneration = 0
|
private var metadataGeneration = 0
|
||||||
|
private var activeMetadataLoads = 0
|
||||||
|
|
||||||
/// Cache first (instant), then the remaining files with several exiftool processes in parallel.
|
/// Cache first (instant), then the remaining files with several exiftool processes in parallel.
|
||||||
func loadMetadata(for snapshot: [PhotoItem]) async {
|
func loadMetadata(for snapshot: [PhotoItem]) async {
|
||||||
@@ -624,10 +648,13 @@ final class AppState: ObservableObject {
|
|||||||
metadataCache?.save()
|
metadataCache?.save()
|
||||||
metadataCache = MetadataCache(folder: folder)
|
metadataCache = MetadataCache(folder: folder)
|
||||||
metadataCacheFolder = 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 }
|
guard let pool = readPool, let cache = metadataCache else { return }
|
||||||
metadataGeneration += 1
|
|
||||||
let generation = metadataGeneration
|
let generation = metadataGeneration
|
||||||
|
activeMetadataLoads += 1
|
||||||
|
defer { activeMetadataLoads -= 1 }
|
||||||
loadingMetadata = true
|
loadingMetadata = true
|
||||||
|
|
||||||
// 1. cache hits
|
// 1. cache hits
|
||||||
@@ -672,7 +699,7 @@ final class AppState: ObservableObject {
|
|||||||
}
|
}
|
||||||
cache.save()
|
cache.save()
|
||||||
}
|
}
|
||||||
if metadataGeneration == generation {
|
if metadataGeneration == generation && activeMetadataLoads == 1 {
|
||||||
loadingMetadata = false
|
loadingMetadata = false
|
||||||
statusText = "\(items.count) Bilder"
|
statusText = "\(items.count) Bilder"
|
||||||
}
|
}
|
||||||
@@ -730,9 +757,9 @@ final class AppState: ObservableObject {
|
|||||||
|
|
||||||
// MARK: Rating / labels / tags
|
// 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]) } }
|
for t in targets { if let i = indexByID[t.id] { change(&items[i]) } }
|
||||||
rebuildVisible()
|
if rebuild { rebuildVisible() }
|
||||||
}
|
}
|
||||||
|
|
||||||
private var actionTargets: [PhotoItem] {
|
private var actionTargets: [PhotoItem] {
|
||||||
@@ -835,6 +862,7 @@ final class AppState: ObservableObject {
|
|||||||
var before: [PhotoItem] = []
|
var before: [PhotoItem] = []
|
||||||
var after: [PhotoItem] = []
|
var after: [PhotoItem] = []
|
||||||
defer {
|
defer {
|
||||||
|
rebuildVisible() // once for all images instead of once per image
|
||||||
if recordUndo && !after.isEmpty {
|
if recordUndo && !after.isEmpty {
|
||||||
let title = (fields.count == 1 ? "IPTC: \(fields[0].label)" : "IPTC: \(fields.count) Felder") + countSuffix(after.count)
|
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))
|
pushUndo(UndoEntry(title: title, kind: .iptc(fields), before: before, after: after))
|
||||||
@@ -850,7 +878,8 @@ final class AppState: ObservableObject {
|
|||||||
do {
|
do {
|
||||||
let old = item(t.id) ?? t
|
let old = item(t.id) ?? t
|
||||||
try await w.write(values: expanded, fields: fields, to: 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)
|
before.append(old)
|
||||||
after.append(item(t.id) ?? { var n = t; n.iptc = expanded; return n }())
|
after.append(item(t.id) ?? { var n = t; n.iptc = expanded; return n }())
|
||||||
count += 1
|
count += 1
|
||||||
@@ -888,7 +917,8 @@ final class AppState: ObservableObject {
|
|||||||
let before = current(targets)
|
let before = current(targets)
|
||||||
do {
|
do {
|
||||||
let result = try await w.apply(template: template, to: targets, codes: codes, dateFormat: settings.dateFormat)
|
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 {
|
if recordUndo {
|
||||||
let after = targets.map { t -> PhotoItem in
|
let after = targets.map { t -> PhotoItem in
|
||||||
if let cur = item(t.id) { return cur }
|
if let cur = item(t.id) { return cur }
|
||||||
@@ -995,6 +1025,7 @@ final class AppState: ObservableObject {
|
|||||||
do {
|
do {
|
||||||
try LightroomBridge.submit(job)
|
try LightroomBridge.submit(job)
|
||||||
pendingLRJobs[job.id] = job
|
pendingLRJobs[job.id] = job
|
||||||
|
pendingLRSources[job.id] = targets
|
||||||
lrPendingCount = pendingLRJobs.count
|
lrPendingCount = pendingLRJobs.count
|
||||||
let what = export ? "Import + JPEG-Export nach \(exportFolder.lastPathComponent)" : develop ? "Bearbeiten" : "Import"
|
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)
|
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() {
|
private func pollLightroom() {
|
||||||
guard !pendingLRJobs.isEmpty else { return }
|
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() {
|
for result in LightroomBridge.collectResults() {
|
||||||
let job = pendingLRJobs.removeValue(forKey: result.id)
|
let job = pendingLRJobs.removeValue(forKey: result.id)
|
||||||
|
let jobSources = pendingLRSources.removeValue(forKey: result.id) ?? []
|
||||||
lrPendingCount = pendingLRJobs.count
|
lrPendingCount = pendingLRJobs.count
|
||||||
if let tid = lrTaskIDs.removeValue(forKey: result.id) {
|
if let tid = lrTaskIDs.removeValue(forKey: result.id) {
|
||||||
let detail = "\(result.imported) importiert" + (result.exported.isEmpty ? "" : ", \(result.exported.count) JPEG(s) exportiert")
|
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"
|
statusText = "Lightroom: \(result.imported) importiert, \(result.exported.count) JPEG(s) exportiert"
|
||||||
guard let job, !result.exported.isEmpty else { continue }
|
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.
|
/// 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").
|
// 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 {
|
if job.rewriteIPTCAfterExport, let w = writer {
|
||||||
for file in files {
|
for file in files {
|
||||||
let base = file.deletingPathExtension().lastPathComponent
|
let base = file.deletingPathExtension().lastPathComponent
|
||||||
@@ -1308,8 +1350,9 @@ final class AppState: ObservableObject {
|
|||||||
return s.prefix(3).map { "#\($0.number)" }.joined(separator: " ")
|
return s.prefix(3).map { "#\($0.number)" }.joined(separator: " ")
|
||||||
}
|
}
|
||||||
|
|
||||||
private var jerseyCacheURL: URL? {
|
private var jerseyCacheURL: URL? { folder.map(jerseyCacheURL(for:)) }
|
||||||
guard let f = folder else { return nil }
|
|
||||||
|
private func jerseyCacheURL(for f: URL) -> URL {
|
||||||
var h: UInt64 = 0xcbf29ce484222325
|
var h: UInt64 = 0xcbf29ce484222325
|
||||||
for b in f.standardizedFileURL.path.utf8 { h = (h ^ UInt64(b)) &* 0x100000001b3 }
|
for b in f.standardizedFileURL.path.utf8 { h = (h ^ UInt64(b)) &* 0x100000001b3 }
|
||||||
// "jersey2": results of the improved recognizer (older caches are ignored → recognized again)
|
// "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) }
|
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).
|
/// Runs the recognition in the background (task window shows progress, cancellable).
|
||||||
func recognizeJerseys(_ targets: [PhotoItem]? = nil, onlyNew: Bool = true) {
|
func recognizeJerseys(_ targets: [PhotoItem]? = nil, onlyNew: Bool = true) {
|
||||||
guard jerseyTask == nil else { return }
|
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
|
let taskID = tasks.start(.metadata, title: "Trikotnummern erkennen (\(jobs.count) Bilder)", total: jobs.count) { [weak self] in
|
||||||
self?.jerseyTask?.cancel()
|
self?.jerseyTask?.cancel()
|
||||||
}
|
}
|
||||||
|
let startFolder = folder
|
||||||
jerseyTask = Task { [weak self] in
|
jerseyTask = Task { [weak self] in
|
||||||
var done = 0
|
var done = 0
|
||||||
var found = 0
|
var found = 0
|
||||||
|
var collected: [String: [JerseySuggestion]] = [:]
|
||||||
await withTaskGroup(of: (String, [JerseySuggestion]).self) { group in
|
await withTaskGroup(of: (String, [JerseySuggestion]).self) { group in
|
||||||
var next = 0
|
var next = 0
|
||||||
let parallel = 4
|
let parallel = 4
|
||||||
@@ -1360,16 +1416,17 @@ final class AppState: ObservableObject {
|
|||||||
while let (id, result) = await group.next() {
|
while let (id, result) = await group.next() {
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
if Task.isCancelled { group.cancelAll(); break }
|
if Task.isCancelled { group.cancelAll(); break }
|
||||||
self.jerseySuggestions[id] = result
|
collected[id] = result
|
||||||
|
if self.folder == startFolder { self.jerseySuggestions[id] = result }
|
||||||
done += 1
|
done += 1
|
||||||
if result.contains(where: { $0.replacement != nil }) { found += 1 }
|
if result.contains(where: { $0.replacement != nil }) { found += 1 }
|
||||||
self.tasks.update(taskID, done: done, detail: "\(found) Bilder mit Spieler-Vorschlag")
|
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()
|
add()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
self.saveJerseyCache()
|
self.storeJerseyResults(collected, folder: startFolder)
|
||||||
self.jerseyTask = nil
|
self.jerseyTask = nil
|
||||||
if Task.isCancelled { self.tasks.cancel(taskID) } else {
|
if Task.isCancelled { self.tasks.cancel(taskID) } else {
|
||||||
self.tasks.finish(taskID, detail: "\(found) von \(done) Bildern mit Vorschlag")
|
self.tasks.finish(taskID, detail: "\(found) von \(done) Bildern mit Vorschlag")
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ final class ImageLoader: @unchecked Sendable {
|
|||||||
private let thumbs = NSCache<NSString, NSImage>()
|
private let thumbs = NSCache<NSString, NSImage>()
|
||||||
private let previews = NSCache<NSString, NSImage>()
|
private let previews = NSCache<NSString, NSImage>()
|
||||||
private let queue = OperationQueue()
|
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() {
|
init() {
|
||||||
thumbs.countLimit = 4000
|
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? {
|
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
|
return await withCheckedContinuation { cont in
|
||||||
queue.addOperation {
|
queue.addOperation {
|
||||||
let img = Self.makeImage(url, maxPixel: maxPixel, minAcceptable: 1400)
|
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)
|
cont.resume(returning: img)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func prefetchPreviews(_ urls: [URL]) {
|
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) }
|
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 canCancel(_ id: UUID) -> Bool { cancelHandlers[id] != nil }
|
||||||
|
|
||||||
func clearFinished() { tasks.removeAll { !$0.isRunning } }
|
func clearFinished() { tasks.removeAll { !$0.isRunning } }
|
||||||
|
|||||||
@@ -35,7 +35,6 @@ final class UploadQueue: ObservableObject {
|
|||||||
private var running = 0
|
private var running = 0
|
||||||
private let maxParallel = 2
|
private let maxParallel = 2
|
||||||
private var immichClient: ImmichClient?
|
private var immichClient: ImmichClient?
|
||||||
private var immichAlbumId: String?
|
|
||||||
/// album name → new asset ids
|
/// album name → new asset ids
|
||||||
private var immichNewAssets: [String: [String]] = [:]
|
private var immichNewAssets: [String: [String]] = [:]
|
||||||
|
|
||||||
@@ -123,6 +122,7 @@ final class UploadQueue: ObservableObject {
|
|||||||
if let b = batchRef { self?.cancelBatch(b) }
|
if let b = batchRef { self?.cancelBatch(b) }
|
||||||
}
|
}
|
||||||
batchRef = batch
|
batchRef = batch
|
||||||
|
var usedNames = Set<String>()
|
||||||
for f in files {
|
for f in files {
|
||||||
let src = sourceItems.first { $0.primary == f || $0.companions.contains(f) }
|
let src = sourceItems.first { $0.primary == f || $0.companions.contains(f) }
|
||||||
var remote = f.lastPathComponent
|
var remote = f.lastPathComponent
|
||||||
@@ -132,6 +132,15 @@ final class UploadQueue: ObservableObject {
|
|||||||
remote = VariableExpander.expand(pattern, context: ctx)
|
remote = VariableExpander.expand(pattern, context: ctx)
|
||||||
.replacingOccurrences(of: "/", with: "-") + "." + f.pathExtension.lowercased()
|
.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)
|
var job = UploadJob(file: f, target: target, targetName: name, remoteName: remote, captureDate: src?.captureDate)
|
||||||
job.batch = batch
|
job.batch = batch
|
||||||
job.fileSize = ((try? FileManager.default.attributesOfItem(atPath: f.path)[.size]) as? NSNumber)?.int64Value ?? 0
|
job.fileSize = ((try? FileManager.default.attributesOfItem(atPath: f.path)[.size]) as? NSNumber)?.int64Value ?? 0
|
||||||
@@ -144,7 +153,15 @@ final class UploadQueue: ObservableObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func retryFailed() {
|
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()
|
pump()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,7 +196,7 @@ final class UploadQueue: ObservableObject {
|
|||||||
|
|
||||||
private func run(_ job: UploadJob) async {
|
private func run(_ job: UploadJob) async {
|
||||||
defer { running -= 1; pump() }
|
defer { running -= 1; pump() }
|
||||||
guard let state else { return }
|
guard let state else { setStatus(job.id, .failed("App-Zustand nicht verfügbar")); return }
|
||||||
startRateTimer()
|
startRateTimer()
|
||||||
let jobID = job.id
|
let jobID = job.id
|
||||||
// progress callbacks arrive on background threads → hop to the main actor
|
// 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.
|
/// Settings changed → rebuild client next time.
|
||||||
func resetImmich() { immichClient = nil; immichAlbumId = nil }
|
func resetImmich() { immichClient = nil }
|
||||||
|
|
||||||
private func finishImmichBatch() {
|
private func finishImmichBatch() {
|
||||||
guard !immichNewAssets.isEmpty, let state, let client = immichClient else { return }
|
guard !immichNewAssets.isEmpty, let state, let client = immichClient else { return }
|
||||||
|
|||||||
@@ -53,7 +53,20 @@ struct IPTCInfoWindow: View {
|
|||||||
.onDisappear {
|
.onDisappear {
|
||||||
if let m = arrowMonitor { NSEvent.removeMonitor(m); arrowMonitor = nil }
|
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) } } }
|
.onReceive(state.$items) { _ in if dirty.isEmpty { DispatchQueue.main.async { load(force: false) } } }
|
||||||
.task(id: item.map { state.previewURL(for: $0) }) { await loadImage() }
|
.task(id: item.map { state.previewURL(for: $0) }) { await loadImage() }
|
||||||
}
|
}
|
||||||
@@ -275,7 +288,8 @@ struct IPTCInfoWindow: View {
|
|||||||
|
|
||||||
@discardableResult
|
@discardableResult
|
||||||
private func save() async -> Bool {
|
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
|
saving = true
|
||||||
defer { saving = false }
|
defer { saving = false }
|
||||||
let fields = IPTCField.all.filter { dirty.contains($0.id) }
|
let fields = IPTCField.all.filter { dirty.contains($0.id) }
|
||||||
|
|||||||
@@ -135,8 +135,14 @@ struct FTPSettings: View {
|
|||||||
HStack {
|
HStack {
|
||||||
Button { let d = FTPDestination(); state.settings.ftpDestinations.append(d); selected = d.id } label: { Image(systemName: "plus") }
|
Button { let d = FTPDestination(); state.settings.ftpDestinations.append(d); selected = d.id } label: { Image(systemName: "plus") }
|
||||||
Button {
|
Button {
|
||||||
if let i = index { Keychain.set("", account: state.settings.ftpDestinations[i].keychainAccount)
|
// first leave the form (its bindings use the index), then remove by id – otherwise
|
||||||
state.settings.ftpDestinations.remove(at: i); selected = nil }
|
// 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)
|
} label: { Image(systemName: "minus") }.disabled(index == nil)
|
||||||
Spacer()
|
Spacer()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -193,6 +193,8 @@ public enum IngestService {
|
|||||||
let destRoots = [settings.primaryDestination] + (settings.secondaryEnabled && !settings.backupDestination.isEmpty ? [settings.backupDestination] : [])
|
let destRoots = [settings.primaryDestination] + (settings.secondaryEnabled && !settings.backupDestination.isEmpty ? [settings.backupDestination] : [])
|
||||||
|
|
||||||
progress(IngestProgress(done: 0, total: total, currentFile: "Starte …"))
|
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 {
|
for e in entries {
|
||||||
try Task.checkCancellation()
|
try Task.checkCancellation()
|
||||||
let item = e.item
|
let item = e.item
|
||||||
@@ -204,7 +206,6 @@ public enum IngestService {
|
|||||||
if settings.renameEnabled, !settings.renamePattern.isEmpty {
|
if settings.renameEnabled, !settings.renamePattern.isEmpty {
|
||||||
baseName = VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-")
|
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
|
// Card structure (DCIM/100NZ8_1) below the destination if requested
|
||||||
let rel = settings.preserveStructure
|
let rel = settings.preserveStructure
|
||||||
? item.primary.deletingLastPathComponent().path.replacingOccurrences(of: e.root.path, with: "")
|
? 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 }
|
case .nonRawOnly: rawFiles = rawFiles.filter { !FileKind(url: $0).isRawLike }
|
||||||
}
|
}
|
||||||
guard !rawFiles.isEmpty else { continue }
|
guard !rawFiles.isEmpty else { continue }
|
||||||
|
if settings.sequenceEnabled { seq += 1 } // only photos that are really copied get a number
|
||||||
var files = rawFiles
|
var files = rawFiles
|
||||||
if item.kind.usesSidecar, fm.fileExists(atPath: item.sidecarURL.path), rawFiles.contains(item.primary) { files.append(item.sidecarURL) }
|
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 {
|
for destRoot in destRoots {
|
||||||
var folder = URL(fileURLWithPath: destRoot)
|
var folder = URL(fileURLWithPath: destRoot)
|
||||||
if !sub.isEmpty { folder.appendPathComponent(sub, isDirectory: true) }
|
if !sub.isEmpty { folder.appendPathComponent(sub, isDirectory: true) }
|
||||||
@@ -229,10 +245,11 @@ public enum IngestService {
|
|||||||
let isPrimary = destRoot == settings.primaryDestination
|
let isPrimary = destRoot == settings.primaryDestination
|
||||||
if isPrimary, usedFolders.insert(folder).inserted { onFolder?(folder) }
|
if isPrimary, usedFolders.insert(folder).inserted { onFolder?(folder) }
|
||||||
for (n, src) in files.enumerated() {
|
for (n, src) in files.enumerated() {
|
||||||
let dest = folder.appendingPathComponent(baseName).appendingPathExtension(src.pathExtension)
|
let dest = folder.appendingPathComponent(targetName).appendingPathExtension(src.pathExtension)
|
||||||
if fm.fileExists(atPath: dest.path) {
|
if skipGroup || fm.fileExists(atPath: dest.path) {
|
||||||
if settings.skipDuplicates, sameSize(src, dest) { continue }
|
// already there (duplicate, or the backup already has it) – never overwrite
|
||||||
try fm.removeItem(at: dest)
|
if isPrimary, n == 0, src.pathExtension.lowercased() != "xmp" { done += 1 }
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
try copy(src, to: dest)
|
try copy(src, to: dest)
|
||||||
if isPrimary {
|
if isPrimary {
|
||||||
@@ -249,7 +266,6 @@ public enum IngestService {
|
|||||||
}
|
}
|
||||||
if settings.incremental { history.insert(historyKey(item.primary)) }
|
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,
|
return IngestResult(folders: Array(usedFolders).sorted { $0.path < $1.path }, copied: copied,
|
||||||
lockedCopies: lockedCopies, nextSequence: seq, skipped: skipped)
|
lockedCopies: lockedCopies, nextSequence: seq, skipped: skipped)
|
||||||
}
|
}
|
||||||
@@ -270,6 +286,21 @@ public enum IngestService {
|
|||||||
return last.isEmpty ? "diskutil eject fehlgeschlagen" : last
|
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 {
|
static func sameSize(_ a: URL, _ b: URL) -> Bool {
|
||||||
func size(_ u: URL) -> Int64? {
|
func size(_ u: URL) -> Int64? {
|
||||||
guard let attrs = try? FileManager.default.attributesOfItem(atPath: u.path) else { return nil }
|
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.
|
/// 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.
|
/// Applies exiftool output (primary file + optional sidecar) to the item.
|
||||||
public mutating func apply(fileMeta: [String: MetadataValue], sidecarMeta: [String: MetadataValue]?) {
|
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 }
|
if !l.isEmpty { values.lists[field.id] = l }
|
||||||
} else {
|
} else {
|
||||||
var s = v.string
|
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 }
|
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
|
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).
|
/// Adds only codes that are not in the team yet (existing players stay untouched).
|
||||||
@discardableResult
|
@discardableResult
|
||||||
public mutating func merge(_ new: [CodeEntry]) -> (added: Int, existing: Int) {
|
public mutating func merge(_ new: [CodeEntry]) -> (added: Int, existing: Int) {
|
||||||
@@ -56,6 +69,18 @@ public struct CodeLibrary: Codable, Sendable {
|
|||||||
|
|
||||||
public init() {}
|
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.
|
/// Flat lookup table for the enabled teams – first team in the list wins on duplicate codes.
|
||||||
public var replacements: CodeReplacements {
|
public var replacements: CodeReplacements {
|
||||||
var table: [String: [String]] = [:]
|
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.
|
/// 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 {
|
public static func readText(_ url: URL) throws -> String {
|
||||||
let data = try Data(contentsOf: url)
|
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 }
|
if let s = String(data: data, encoding: enc) { return s }
|
||||||
}
|
}
|
||||||
return String(decoding: data, as: UTF8.self)
|
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 let searchPaths = ["/opt/homebrew/bin/exiftool", "/usr/local/bin/exiftool", "/usr/bin/exiftool"]
|
||||||
|
|
||||||
public static func locate(custom: String? = nil) -> URL? {
|
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") {
|
if let bundled = Bundle.main.url(forResource: "exiftool", withExtension: nil, subdirectory: "exiftool") {
|
||||||
return bundled
|
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
|
private let executable: URL
|
||||||
@@ -87,7 +90,10 @@ public final class ExifTool: @unchecked Sendable {
|
|||||||
counter += 1
|
counter += 1
|
||||||
let marker = "{ready\(counter)}"
|
let marker = "{ready\(counter)}"
|
||||||
stderrLock.lock(); stderrBuffer.removeAll(); stderrLock.unlock()
|
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))
|
try stdin.write(contentsOf: Data(payload.utf8))
|
||||||
var out = Data()
|
var out = Data()
|
||||||
let markerData = Data(marker.utf8)
|
let markerData = Data(marker.utf8)
|
||||||
@@ -100,10 +106,20 @@ public final class ExifTool: @unchecked Sendable {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// stderr arrives asynchronously; give it a moment.
|
// stderr arrives asynchronously: wait for our marker (max. 5 s)
|
||||||
Thread.sleep(forTimeInterval: 0.005)
|
let errMarkerData = Data(errMarker.utf8)
|
||||||
stderrLock.lock(); let err = String(decoding: stderrBuffer, as: UTF8.self); stderrLock.unlock()
|
var err = ""
|
||||||
return (String(decoding: out, as: UTF8.self), 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`.
|
/// 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)
|
let mine = chunks.enumerated().filter { $0.offset % workers.count == w }.map(\.element)
|
||||||
group.addTask {
|
group.addTask {
|
||||||
for chunk in mine {
|
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
|
let prefs = item.pmPrefsString
|
||||||
for target in item.metadataTargets {
|
for target in item.metadataTargets {
|
||||||
var args = ["-overwrite_original", "-m",
|
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:Tagged=\(item.tagged ? "Yes" : "No")",
|
||||||
"-XMP-photomech:Prefs=\(prefs)"]
|
"-XMP-photomech:Prefs=\(prefs)"]
|
||||||
if let l = item.label {
|
if let l = item.label {
|
||||||
|
|||||||
@@ -377,3 +377,45 @@ final class SentLogTests: XCTestCase {
|
|||||||
XCTAssertFalse(log.wasSent(item))
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user