Review-Korrekturen zu „Kartenimport, Metadaten und Versand absichern“

- Ingest-Verlauf wieder wie PM: Name + Größe + Datum, unabhängig von Ziel und Ordnermuster.
  Beim Sichten gelöschte Fotos kommen nicht zurück, neuer Spieltags-Ordner importiert keine alte Karte
  erneut, keine SHA-256-Prüfsumme mehr über die ganze Karte. Alter Verlauf (ingest-history.json) gilt wieder.
  Schutz vor Namenskollisionen, Rollback und Backup-Prüfung bleiben.
- FTP: „Vorhandene Datei auf dem Server ersetzen“ (wie PM, Standard an) – Korrekturen lassen sich erneut
  senden, kein Auflisten des Server-Ordners vor jeder Datei. Aus = Upload stoppt bei belegtem Namen.
- LR-Export: Pfadabgleich unabhängig von Unicode-Schreibweise (Umlaute), Groß/Klein und Symlinks
- Ordner-Scan: einzelne unlesbare oder verschwundene Dateien werden übersprungen statt alles abzubrechen
- Agentur-Check: Mindestgröße nur für die gelieferten Bilder, RAWs blockieren nicht; Senden nutzt die
  aktuellen Bilddaten
- Datum ohne Uhrzeit lässt IPTC TimeCreated stehen

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:46:36 +00:00
1 parent 427b6fa7b0
commit c9d43aba9c
11 files changed
+88 -126

No files matched your search

+10 -4
View File
@@ -1088,17 +1088,22 @@ final class AppState: ObservableObject {
} }
} }
/// Path key for matching LR's source paths: symlinks resolved, Unicode precomposed (LR may report
/// "Köln" decomposed), case-insensitive like APFS.
static func exportKey(_ url: URL) -> String {
url.resolvingSymlinksInPath().standardizedFileURL.path.precomposedStringWithCanonicalMapping.lowercased()
}
/// 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(_ result: LightroomJobResult, job: LightroomJob, sources jobSources: [PhotoItem]) async { private func handleExported(_ result: LightroomJobResult, job: LightroomJob, sources jobSources: [PhotoItem]) async {
let sources = Dictionary(jobSources.map { original in let sources = Dictionary(jobSources.map { original in
let path = (original.rawFile ?? original.primary).standardizedFileURL.path return (Self.exportKey(original.rawFile ?? original.primary), item(original.id) ?? original)
return (path, item(original.id) ?? original)
}, uniquingKeysWith: { first, _ in first }) }, uniquingKeysWith: { first, _ in first })
let writer = job.rewriteIPTCAfterExport ? self.writer : nil let writer = job.rewriteIPTCAfterExport ? self.writer : nil
var exportedItems: [PhotoItem] = [] var exportedItems: [PhotoItem] = []
var missingSources = 0 var missingSources = 0
for file in result.exported { for file in result.exported {
guard let path = result.exportSources[file]?.standardizedFileURL.path, let source = sources[path] else { guard let src = result.exportSources[file], let source = sources[Self.exportKey(src)] else {
missingSources += 1 missingSources += 1
continue continue
} }
@@ -1240,7 +1245,8 @@ final class AppState: ObservableObject {
guard p.variant == variant else { recheckPendingUpload(); return } guard p.variant == variant else { recheckPendingUpload(); return }
discardPendingUpload() discardPendingUpload()
guard !send.isEmpty else { return } guard !send.isEmpty else { return }
enqueueUpload(send, target: p.target, variant: variant) // current metadata (captions may have been fixed after the check) for rename patterns / albums
enqueueUpload(send.map { item($0.id) ?? $0 }, target: p.target, variant: variant)
} }
func discardPendingUpload() { func discardPendingUpload() {
@@ -178,6 +178,8 @@ struct FTPSettings: View {
TextField("Umbenennen (leer = Originalname)", text: $state.settings.ftpDestinations[i].renamePattern) TextField("Umbenennen (leer = Originalname)", text: $state.settings.ftpDestinations[i].renamePattern)
Toggle("Passiver Modus", isOn: $state.settings.ftpDestinations[i].passive) Toggle("Passiver Modus", isOn: $state.settings.ftpDestinations[i].passive)
Toggle("Mit .part hochladen und danach umbenennen", isOn: $state.settings.ftpDestinations[i].uploadWithTempName) Toggle("Mit .part hochladen und danach umbenennen", isOn: $state.settings.ftpDestinations[i].uploadWithTempName)
Toggle("Vorhandene Datei auf dem Server ersetzen (wie PM)", isOn: $state.settings.ftpDestinations[i].replaceExisting)
.help("An: korrigierte Bilder können unter gleichem Namen erneut gesendet werden. Aus: Upload stoppt, wenn der Name schon existiert.")
Toggle("TLS-Zertifikat nicht prüfen (nur wenn nötig)", isOn: $state.settings.ftpDestinations[i].allowInsecureTLS) Toggle("TLS-Zertifikat nicht prüfen (nur wenn nötig)", isOn: $state.settings.ftpDestinations[i].allowInsecureTLS)
HStack { HStack {
Button("Verbindung testen") { test(state.settings.ftpDestinations[i]) }.disabled(testing) Button("Verbindung testen") { test(state.settings.ftpDestinations[i]) }.disabled(testing)
@@ -85,6 +85,11 @@ struct UploadWindow: View {
Toggle("Vor dem Senden prüfen (Pflichtfelder, Codes, Datum …)", isOn: $state.settings.ftpDestinations[i].preflight) Toggle("Vor dem Senden prüfen (Pflichtfelder, Codes, Datum …)", isOn: $state.settings.ftpDestinations[i].preflight)
.toggleStyle(.checkbox) .toggleStyle(.checkbox)
} }
divider
optionRow("Auf dem Server") {
Toggle("Vorhandene Datei ersetzen (Korrekturen erneut senden)", isOn: $state.settings.ftpDestinations[i].replaceExisting)
.toggleStyle(.checkbox)
}
} }
.background(RoundedRectangle(cornerRadius: 12).fill(LK.card)) .background(RoundedRectangle(cornerRadius: 12).fill(LK.card))
.overlay(RoundedRectangle(cornerRadius: 12).stroke(LK.border)) .overlay(RoundedRectangle(cornerRadius: 12).stroke(LK.border))
@@ -1,4 +1,3 @@
import CryptoKit
import Foundation import Foundation
/// PM Ingest "Filter Files": in-camera protected (locked) photos. /// PM Ingest "Filter Files": in-camera protected (locked) photos.
@@ -111,43 +110,26 @@ public enum IngestService {
let d = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] let d = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("Lichtkasten", isDirectory: true) .appendingPathComponent("Lichtkasten", isDirectory: true)
try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)
return d.appendingPathComponent("ingest-history-v2.json") return d.appendingPathComponent("ingest-history.json")
} }
private struct HistoryKey: Codable { /// Incremental ingest key like PM: original name + size + modification date on the card.
let destinations: [URL] /// Independent of destination and naming – a photo that was ingested once is skipped, even if it was
let folderPattern: String /// deleted while culling or the next match uses another folder name. Costs one stat, no file read.
let preserveStructure: Bool static func historyKey(_ url: URL) -> String {
let sourceFolder: String let a = try? FileManager.default.attributesOfItem(atPath: url.path)
let renamePattern: String? let size = (a?[.size] as? NSNumber)?.int64Value ?? 0
let files: [String] let m = Int((a?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0)
return "\(url.lastPathComponent)|\(size)|\(m)"
} }
private struct ImportedGroup: Codable { static func loadHistory(at url: URL) -> Set<String> {
let folders: [URL] guard let d = try? Data(contentsOf: url), let s = try? JSONDecoder().decode(Set<String>.self, from: d) else { return [] }
let name: String return s
} }
private static func sourceFingerprint(_ url: URL) throws -> String { static func saveHistory(_ s: Set<String>, at url: URL) throws {
let handle = try FileHandle(forReadingFrom: url) try JSONEncoder().encode(s).write(to: url, options: .atomic)
defer { try? handle.close() }
var hash = SHA256()
while let chunk = try handle.read(upToCount: 1024 * 1024), !chunk.isEmpty {
try Task.checkCancellation()
hash.update(data: chunk)
}
let digest = Data(hash.finalize()).base64EncodedString()
return "\(url.lastPathComponent)|\(digest)"
}
private static func loadHistory(at url: URL) -> [String: ImportedGroup] {
guard let d = try? Data(contentsOf: url),
let history = try? JSONDecoder().decode([String: ImportedGroup].self, from: d) else { return [:] }
return history
}
private static func saveHistory(_ history: [String: ImportedGroup], at url: URL) throws {
try JSONEncoder().encode(history).write(to: url, options: .atomic)
} }
/// Copy + make the copy writable again (otherwise locked files stay locked and metadata can't be written). /// Copy + make the copy writable again (otherwise locked files stay locked and metadata can't be written).
@@ -183,12 +165,9 @@ public enum IngestService {
throw UploadError.failed("Hauptziel und Backup-Ziel müssen verschieden sein.") throw UploadError.failed("Hauptziel und Backup-Ziel müssen verschieden sein.")
} }
// A history entry proves which full group was copied to these destinations. var history = historyFile.map { loadHistory(at: $0) } ?? []
var history = historyFile.map { loadHistory(at: $0) } ?? [:]
var historyChanged = false var historyChanged = false
var skipped = 0 var skipped = 0
let keyEncoder = JSONEncoder()
keyEncoder.outputFormatting = [.sortedKeys]
typealias Entry = (item: PhotoItem, relativeFolder: String, locked: Bool, files: [URL], historyKey: String?) typealias Entry = (item: PhotoItem, relativeFolder: String, locked: Bool, files: [URL], historyKey: String?)
var entries: [Entry] = [] var entries: [Entry] = []
progress(IngestProgress(done: 0, total: 0, currentFile: "Prüfe Quelldateien …")) progress(IngestProgress(done: 0, total: 0, currentFile: "Prüfe Quelldateien …"))
@@ -215,21 +194,9 @@ public enum IngestService {
? item.primary.deletingLastPathComponent().pathComponents ? item.primary.deletingLastPathComponent().pathComponents
.dropFirst(source.pathComponents.count).joined(separator: "/") .dropFirst(source.pathComponents.count).joined(separator: "/")
: "" : ""
var historyKey: String? let key = historyFile != nil ? historyKey(item.primary) : nil
if historyFile != nil { if let key, history.contains(key) { skipped += 1; continue }
let key = HistoryKey(destinations: destRoots, folderPattern: settings.folderPattern, entries.append((item, relative, locked, files, key))
preserveStructure: settings.preserveStructure, sourceFolder: relative,
renamePattern: settings.renameEnabled ? settings.renamePattern : nil,
files: try files.map(sourceFingerprint).sorted())
let encoded = try keyEncoder.encode(key)
historyKey = Data(SHA256.hash(data: encoded)).base64EncodedString()
if let historyKey, let group = history[historyKey],
reusable(group, files: files, requireAll: true) {
skipped += 1
continue
}
}
entries.append((item, relative, locked, files, historyKey))
} }
} }
progress(IngestProgress(done: 0, total: entries.count, currentFile: "Lese Aufnahmezeiten …")) progress(IngestProgress(done: 0, total: entries.count, currentFile: "Lese Aufnahmezeiten …"))
@@ -274,17 +241,9 @@ public enum IngestService {
return folder return folder
} }
// Reuse the recorded name when restoring a missing copy, including a sequence-based name. // A name free in all destinations (or holding exactly this photo already) – never overwrite.
let previous = entry.historyKey.flatMap { history[$0] } let targets = folders
let targets = previous?.folders ?? folders let name = uniqueName(baseName, files: entry.files, in: targets, skipDuplicates: settings.skipDuplicates).name
let canRestore = previous.map { reusable($0, files: entry.files, requireAll: false) } ?? false
let name: String
if let previous, canRestore {
name = previous.name
} else {
name = uniqueName(previous?.name ?? baseName, files: entry.files, in: targets,
skipDuplicates: settings.skipDuplicates).name
}
var newCopies: [URL] = [] var newCopies: [URL] = []
var newPrimary: URL? var newPrimary: URL?
do { do {
@@ -295,7 +254,7 @@ public enum IngestService {
try Task.checkCancellation() try Task.checkCancellation()
let dest = destination(for: src, name: name, in: folder) let dest = destination(for: src, name: name, in: folder)
if fm.fileExists(atPath: dest.path) { if fm.fileExists(atPath: dest.path) {
if !(canRestore && folderIndex == 0) && !fm.contentsEqual(atPath: src.path, andPath: dest.path) { if !fm.contentsEqual(atPath: src.path, andPath: dest.path) {
throw UploadError.failed("Die Zieldatei wurde zwischenzeitlich geändert: \(dest.path)") throw UploadError.failed("Die Zieldatei wurde zwischenzeitlich geändert: \(dest.path)")
} }
guard (try dest.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true else { guard (try dest.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true else {
@@ -321,10 +280,10 @@ public enum IngestService {
copied.append(newPrimary) copied.append(newPrimary)
if entry.locked { lockedCopies.append(newPrimary) } if entry.locked { lockedCopies.append(newPrimary) }
} }
if settings.sequenceEnabled && previous == nil { seq += 1 } if settings.sequenceEnabled { seq += 1 }
if newCopies.isEmpty { skipped += 1 } if newCopies.isEmpty { skipped += 1 }
if let key = entry.historyKey { if let key = entry.historyKey {
history[key] = ImportedGroup(folders: targets, name: name) history.insert(key)
historyChanged = true historyChanged = true
} }
} }
@@ -381,19 +340,6 @@ public enum IngestService {
} }
} }
private static func reusable(_ group: ImportedGroup, files: [URL], requireAll: Bool) -> Bool {
let fm = FileManager.default
return group.folders.enumerated().allSatisfy { index, folder in
files.allSatisfy { source in
let dest = destination(for: source, name: group.name, in: folder)
guard fm.fileExists(atPath: dest.path) else { return !requireAll }
guard (try? dest.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { return false }
// IPTC changes can legitimately modify the main copy after ingest.
return index == 0 || fm.contentsEqual(atPath: source.path, andPath: dest.path)
}
}
}
private static func destination(for source: URL, name: String, in folder: URL) -> URL { private static func destination(for source: URL, name: String, in folder: URL) -> URL {
folder.appendingPathComponent(name).appendingPathExtension(source.pathExtension) folder.appendingPathComponent(name).appendingPathExtension(source.pathExtension)
} }
@@ -203,23 +203,22 @@ public enum FolderScanner {
let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey, .isHiddenKey] let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey, .isHiddenKey]
var urls: [URL] = [] var urls: [URL] = []
if recursive { if recursive {
var scanError: Error? // the folder itself must be readable (card gone → error); a single unreadable subfolder or file
guard let enumerator = fm.enumerator(at: folder, includingPropertiesForKeys: keys, // is skipped instead of failing the whole ingest
guard (try folder.resourceValues(forKeys: [.isDirectoryKey])).isDirectory == true,
let enumerator = fm.enumerator(at: folder, includingPropertiesForKeys: keys,
options: [.skipsHiddenFiles, .skipsPackageDescendants], options: [.skipsHiddenFiles, .skipsPackageDescendants],
errorHandler: { _, error in errorHandler: { _, _ in true }) else {
scanError = error
return false
}) else {
throw CocoaError(.fileReadUnknown, userInfo: [NSURLErrorKey: folder]) throw CocoaError(.fileReadUnknown, userInfo: [NSURLErrorKey: folder])
} }
for case let url as URL in enumerator { urls.append(url) } for case let url as URL in enumerator { urls.append(url) }
if let scanError { throw scanError }
} else { } else {
urls = try fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles]) urls = try fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles])
} }
urls = try urls.filter { url in // files that vanish during the scan (LR export temp files, .part) are simply left out
urls = urls.filter { url in
guard !url.lastPathComponent.hasPrefix("._"), FileKind(url: url).isImage else { return false } guard !url.lastPathComponent.hasPrefix("._"), FileKind(url: url).isImage else { return false }
return try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true return (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true
} }
// Group by directory + lowercase base name // Group by directory + lowercase base name
@@ -111,7 +111,8 @@ public struct MetadataWriter: Sendable {
var args = ["-XMP-photoshop:DateCreated=\(datePart)\(timePart.isEmpty ? "" : " " + timePart)"] var args = ["-XMP-photoshop:DateCreated=\(datePart)\(timePart.isEmpty ? "" : " " + timePart)"]
if writeIIM { if writeIIM {
args.append("-IPTC:DateCreated=\(datePart)") args.append("-IPTC:DateCreated=\(datePart)")
args.append("-IPTC:TimeCreated=\(timePart)") // date without time (fixed date, {today}) keeps the existing TimeCreated
if !timePart.isEmpty { args.append("-IPTC:TimeCreated=\(timePart)") }
} }
return args return args
} }
@@ -41,20 +41,25 @@ public struct FTPDestination: Codable, Identifiable, Hashable, Sendable {
public var allowInsecureTLS: Bool public var allowInsecureTLS: Bool
/// Agentur-Check before uploading to this server /// Agentur-Check before uploading to this server
public var preflight: Bool public var preflight: Bool
/// PM "Replace existing file on server": a corrected image can be sent again under the same name.
/// Off = the upload stops if the name already exists there.
public var replaceExisting: Bool
public init(id: UUID = UUID(), name: String = "Neuer Server", proto: FTPProtocol = .ftp, host: String = "", public init(id: UUID = UUID(), name: String = "Neuer Server", proto: FTPProtocol = .ftp, host: String = "",
port: Int = 21, username: String = "", remoteDirectory: String = "/", passive: Bool = true, port: Int = 21, username: String = "", remoteDirectory: String = "/", passive: Bool = true,
uploadWithTempName: Bool = true, renamePattern: String = "", variant: UploadVariant = .jpeg, uploadWithTempName: Bool = true, renamePattern: String = "", variant: UploadVariant = .jpeg,
sshKeyPath: String = "", allowInsecureTLS: Bool = false, preflight: Bool = true) { sshKeyPath: String = "", allowInsecureTLS: Bool = false, preflight: Bool = true,
replaceExisting: Bool = true) {
self.id = id; self.name = name; self.proto = proto; self.host = host; self.port = port self.id = id; self.name = name; self.proto = proto; self.host = host; self.port = port
self.username = username; self.remoteDirectory = remoteDirectory; self.passive = passive self.username = username; self.remoteDirectory = remoteDirectory; self.passive = passive
self.uploadWithTempName = uploadWithTempName; self.renamePattern = renamePattern; self.variant = variant self.uploadWithTempName = uploadWithTempName; self.renamePattern = renamePattern; self.variant = variant
self.sshKeyPath = sshKeyPath; self.allowInsecureTLS = allowInsecureTLS; self.preflight = preflight self.sshKeyPath = sshKeyPath; self.allowInsecureTLS = allowInsecureTLS; self.preflight = preflight
self.replaceExisting = replaceExisting
} }
enum CodingKeys: String, CodingKey { enum CodingKeys: String, CodingKey {
case id, name, proto, host, port, username, remoteDirectory, passive, uploadWithTempName, renamePattern, case id, name, proto, host, port, username, remoteDirectory, passive, uploadWithTempName, renamePattern,
variant, sshKeyPath, allowInsecureTLS, preflight variant, sshKeyPath, allowInsecureTLS, preflight, replaceExisting
} }
/// Tolerant decoding – new options must never wipe the saved server profiles. /// Tolerant decoding – new options must never wipe the saved server profiles.
@@ -76,6 +81,7 @@ public struct FTPDestination: Codable, Identifiable, Hashable, Sendable {
sshKeyPath = v(.sshKeyPath, d.sshKeyPath) sshKeyPath = v(.sshKeyPath, d.sshKeyPath)
allowInsecureTLS = v(.allowInsecureTLS, d.allowInsecureTLS) allowInsecureTLS = v(.allowInsecureTLS, d.allowInsecureTLS)
preflight = v(.preflight, d.preflight) preflight = v(.preflight, d.preflight)
replaceExisting = v(.replaceExisting, d.replaceExisting)
} }
public var keychainAccount: String { "ftp-\(id.uuidString)" } public var keychainAccount: String { "ftp-\(id.uuidString)" }
@@ -158,8 +164,11 @@ public struct FTPUploader: Sendable {
let directory = baseURL(d) let directory = baseURL(d)
let key = directory.lowercased() + name.lowercased() let key = directory.lowercased() + name.lowercased()
try await Self.reservations.withName(key, name: name) { try await Self.reservations.withName(key, name: name) {
// only list the server folder when existing files must not be replaced (saves a login per file)
if !d.replaceExisting {
let names = try await listNames(d, curl: curl, password: password, createDirectories: true) let names = try await listNames(d, curl: curl, password: password, createDirectories: true)
if names.contains(name.lowercased()) { throw UploadError.remoteNameConflict(name) } if names.contains(name.lowercased()) { throw UploadError.remoteNameConflict(name) }
}
try await transfer(file: file, name: name, to: d, curl: curl, password: password, progress: progress) try await transfer(file: file, name: name, to: d, curl: curl, password: password, progress: progress)
} }
} }
@@ -177,8 +186,11 @@ public struct FTPUploader: Sendable {
let base = sftpPath(d) let base = sftpPath(d)
let source = Self.configQuote(base + tempName), target = Self.configQuote(base + name) let source = Self.configQuote(base + tempName), target = Self.configQuote(base + name)
args.insert(contentsOf: ["-Q", "-rename \(source) \(target)"], at: 0) args.insert(contentsOf: ["-Q", "-rename \(source) \(target)"], at: 0)
// "*" = ignore the error if there is no old file; some servers refuse renaming onto a file
if d.replaceExisting { args.insert(contentsOf: ["-Q", "-*rm \(target)"], at: 0) }
} else { } else {
args.insert(contentsOf: ["-Q", "-RNFR \(tempName)", "-Q", "-RNTO \(name)"], at: 0) args.insert(contentsOf: ["-Q", "-RNFR \(tempName)", "-Q", "-RNTO \(name)"], at: 0)
if d.replaceExisting { args.insert(contentsOf: ["-Q", "-*DELE \(name)"], at: 0) }
} }
} }
let result = try await FTPUploader.runStreaming(curl, args, stdin: credentials(d, password: password)) { line in let result = try await FTPUploader.runStreaming(curl, args, stdin: credentials(d, password: password)) { line in
@@ -56,7 +56,8 @@ public enum Preflight {
/// Reads the actual upload files without decoding their pixels. /// Reads the actual upload files without decoding their pixels.
static func imageSizeIssues(files: [URL], minimum: Int) -> [PreflightIssue] { static func imageSizeIssues(files: [URL], minimum: Int) -> [PreflightIssue] {
guard minimum > 0 else { return [] } guard minimum > 0 else { return [] }
return files.compactMap { file in // RAWs are not what the agency gets and ImageIO may not know a new camera yet → only the delivered images
return files.filter { !FileKind(url: $0).isRawLike }.compactMap { file in
guard let source = CGImageSourceCreateWithURL(file as CFURL, nil), guard let source = CGImageSourceCreateWithURL(file as CFURL, nil),
let info = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], let info = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
let width = info[kCGImagePropertyPixelWidth] as? Int, let width = info[kCGImagePropertyPixelWidth] as? Int,
+2 -2
View File
@@ -413,9 +413,9 @@ final class BugfixTests: XCTestCase {
XCTAssertTrue(lib.sets.first?.enabled ?? false) XCTAssertTrue(lib.sets.first?.enabled ?? false)
} }
func testDateOnlyUpdateClearsIIMTimeCreated() { func testDateOnlyUpdateKeepsIIMTimeCreated() {
let arguments = MetadataWriter.dateArguments("2026-11-03", writeIIM: true) let arguments = MetadataWriter.dateArguments("2026-11-03", writeIIM: true)
XCTAssertTrue(arguments.contains("-IPTC:TimeCreated=")) XCTAssertFalse(arguments.contains { $0.hasPrefix("-IPTC:TimeCreated") })
} }
func testDateCreatedKeepsTimeOfDay() { func testDateCreatedKeepsTimeOfDay() {
@@ -23,7 +23,7 @@ final class FTPUploaderTests: XCTestCase {
try script.write(to: curl, atomically: true, encoding: .utf8) try script.write(to: curl, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: curl.path) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: curl.path)
let uploader = FTPUploader(curlExecutable: curl.path) let uploader = FTPUploader(curlExecutable: curl.path)
let destination = FTPDestination(host: "example.test") let destination = FTPDestination(host: "example.test", replaceExisting: false)
let photo = directory.appendingPathComponent("photo.jpg") let photo = directory.appendingPathComponent("photo.jpg")
try Data([0]).write(to: photo) try Data([0]).write(to: photo)
@@ -54,41 +54,30 @@ final class IngestRecoveryTests: XCTestCase {
} }
} }
func testIncrementalRepairsMissingBackupAndPreservesEditedPrimary() async throws { func testIncrementalSkipsPhotosDeletedWhileCulling() async throws {
let dirs = try fixture() let dirs = try fixture()
let src = try makePhoto(in: dirs.source) _ = try makePhoto(in: dirs.source)
let history = dirs.root.appendingPathComponent("history.json") let history = dirs.root.appendingPathComponent("history.json")
let primary = dirs.primary.appendingPathComponent("photo-4.png")
let backup = dirs.backup.appendingPathComponent("photo-4.png")
_ = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 4) _ = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 4)
let edited = Data("edited primary".utf8) let copy = dirs.primary.appendingPathComponent("photo-4.png")
try edited.write(to: primary) try FileManager.default.removeItem(at: copy) // reject deleted in INPUT
let complete = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 5) let again = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 5)
XCTAssertEqual(complete.skipped, 1) XCTAssertEqual(again.skipped, 1)
try FileManager.default.removeItem(at: backup) XCTAssertTrue(again.copied.isEmpty)
_ = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 5) XCTAssertFalse(FileManager.default.fileExists(atPath: copy.path))
XCTAssertEqual(try Data(contentsOf: primary), edited)
XCTAssertEqual(try Data(contentsOf: backup), try Data(contentsOf: src))
XCTAssertFalse(FileManager.default.fileExists(atPath: dirs.primary.appendingPathComponent("photo-5.png").path)) XCTAssertFalse(FileManager.default.fileExists(atPath: dirs.primary.appendingPathComponent("photo-5.png").path))
} }
func testIncrementalDoesNotAcceptReplacedBackup() async throws { func testIncrementalIgnoresChangedFolderPattern() async throws {
let dirs = try fixture() let dirs = try fixture()
let src = try makePhoto(in: dirs.source) _ = try makePhoto(in: dirs.source)
let history = dirs.root.appendingPathComponent("history.json") let history = dirs.root.appendingPathComponent("history.json")
_ = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 4) _ = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history)
let previousBackup = dirs.backup.appendingPathComponent("photo-4.png") let next = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history,
let unrelated = Data(repeating: 1, count: try Data(contentsOf: src).count) folderPattern: "Spieltag 2")
try unrelated.write(to: previousBackup) XCTAssertEqual(next.skipped, 1)
XCTAssertTrue(next.copied.isEmpty)
_ = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 5)
XCTAssertEqual(try Data(contentsOf: previousBackup), unrelated)
for dir in [dirs.primary, dirs.backup] {
XCTAssertEqual(try Data(contentsOf: dir.appendingPathComponent("photo-4-1.png")), try Data(contentsOf: src))
}
} }
private func makePhoto(in source: URL) throws -> URL { private func makePhoto(in source: URL) throws -> URL {
@@ -99,14 +88,15 @@ final class IngestRecoveryTests: XCTestCase {
} }
@discardableResult @discardableResult
private func ingest(source: URL, primary: URL, backup: URL, history: URL? = nil, sequence: Int? = nil) async throws -> IngestResult { private func ingest(source: URL, primary: URL, backup: URL, history: URL? = nil, sequence: Int? = nil,
folderPattern: String = "") async throws -> IngestResult {
guard let exe = ExifTool.locate() else { throw XCTSkip("ExifTool fehlt") } guard let exe = ExifTool.locate() else { throw XCTSkip("ExifTool fehlt") }
var settings = IngestSettings() var settings = IngestSettings()
settings.primaryDestination = primary.path settings.primaryDestination = primary.path
settings.backupDestination = backup.path settings.backupDestination = backup.path
settings.secondaryEnabled = true settings.secondaryEnabled = true
settings.incremental = history != nil settings.incremental = history != nil
settings.folderPattern = "" settings.folderPattern = folderPattern
if let sequence { if let sequence {
settings.startSequence = sequence settings.startSequence = sequence
settings.renamePattern = "photo-{seqn}" settings.renamePattern = "photo-{seqn}"