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
+91 -129

No files matched your search

@@ -1,4 +1,3 @@
import CryptoKit
import Foundation
/// 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]
.appendingPathComponent("Lichtkasten", isDirectory: 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 {
let destinations: [URL]
let folderPattern: String
let preserveStructure: Bool
let sourceFolder: String
let renamePattern: String?
let files: [String]
/// Incremental ingest key like PM: original name + size + modification date on the card.
/// Independent of destination and naming – a photo that was ingested once is skipped, even if it was
/// deleted while culling or the next match uses another folder name. Costs one stat, no file read.
static func historyKey(_ url: URL) -> String {
let a = try? FileManager.default.attributesOfItem(atPath: url.path)
let size = (a?[.size] as? NSNumber)?.int64Value ?? 0
let m = Int((a?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0)
return "\(url.lastPathComponent)|\(size)|\(m)"
}
private struct ImportedGroup: Codable {
let folders: [URL]
let name: String
static func loadHistory(at url: URL) -> Set<String> {
guard let d = try? Data(contentsOf: url), let s = try? JSONDecoder().decode(Set<String>.self, from: d) else { return [] }
return s
}
private static func sourceFingerprint(_ url: URL) throws -> String {
let handle = try FileHandle(forReadingFrom: url)
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)
static func saveHistory(_ s: Set<String>, at url: URL) throws {
try JSONEncoder().encode(s).write(to: url, options: .atomic)
}
/// 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.")
}
// 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 skipped = 0
let keyEncoder = JSONEncoder()
keyEncoder.outputFormatting = [.sortedKeys]
typealias Entry = (item: PhotoItem, relativeFolder: String, locked: Bool, files: [URL], historyKey: String?)
var entries: [Entry] = []
progress(IngestProgress(done: 0, total: 0, currentFile: "Prüfe Quelldateien …"))
@@ -215,21 +194,9 @@ public enum IngestService {
? item.primary.deletingLastPathComponent().pathComponents
.dropFirst(source.pathComponents.count).joined(separator: "/")
: ""
var historyKey: String?
if historyFile != nil {
let key = HistoryKey(destinations: destRoots, folderPattern: settings.folderPattern,
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))
let key = historyFile != nil ? historyKey(item.primary) : nil
if let key, history.contains(key) { skipped += 1; continue }
entries.append((item, relative, locked, files, key))
}
}
progress(IngestProgress(done: 0, total: entries.count, currentFile: "Lese Aufnahmezeiten …"))
@@ -274,17 +241,9 @@ public enum IngestService {
return folder
}
// Reuse the recorded name when restoring a missing copy, including a sequence-based name.
let previous = entry.historyKey.flatMap { history[$0] }
let targets = previous?.folders ?? folders
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
}
// A name free in all destinations (or holding exactly this photo already) – never overwrite.
let targets = folders
let name = uniqueName(baseName, files: entry.files, in: targets, skipDuplicates: settings.skipDuplicates).name
var newCopies: [URL] = []
var newPrimary: URL?
do {
@@ -295,7 +254,7 @@ public enum IngestService {
try Task.checkCancellation()
let dest = destination(for: src, name: name, in: folder)
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)")
}
guard (try dest.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true else {
@@ -321,10 +280,10 @@ public enum IngestService {
copied.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 let key = entry.historyKey {
history[key] = ImportedGroup(folders: targets, name: name)
history.insert(key)
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 {
folder.appendingPathComponent(name).appendingPathExtension(source.pathExtension)
}
@@ -203,23 +203,22 @@ public enum FolderScanner {
let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey, .isHiddenKey]
var urls: [URL] = []
if recursive {
var scanError: Error?
guard let enumerator = fm.enumerator(at: folder, includingPropertiesForKeys: keys,
options: [.skipsHiddenFiles, .skipsPackageDescendants],
errorHandler: { _, error in
scanError = error
return false
}) else {
// the folder itself must be readable (card gone → error); a single unreadable subfolder or file
// 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],
errorHandler: { _, _ in true }) else {
throw CocoaError(.fileReadUnknown, userInfo: [NSURLErrorKey: folder])
}
for case let url as URL in enumerator { urls.append(url) }
if let scanError { throw scanError }
} else {
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 }
return try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true
return (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true
}
// Group by directory + lowercase base name
@@ -111,7 +111,8 @@ public struct MetadataWriter: Sendable {
var args = ["-XMP-photoshop:DateCreated=\(datePart)\(timePart.isEmpty ? "" : " " + timePart)"]
if writeIIM {
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
}
@@ -41,20 +41,25 @@ public struct FTPDestination: Codable, Identifiable, Hashable, Sendable {
public var allowInsecureTLS: Bool
/// Agentur-Check before uploading to this server
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 = "",
port: Int = 21, username: String = "", remoteDirectory: String = "/", passive: Bool = true,
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.username = username; self.remoteDirectory = remoteDirectory; self.passive = passive
self.uploadWithTempName = uploadWithTempName; self.renamePattern = renamePattern; self.variant = variant
self.sshKeyPath = sshKeyPath; self.allowInsecureTLS = allowInsecureTLS; self.preflight = preflight
self.replaceExisting = replaceExisting
}
enum CodingKeys: String, CodingKey {
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.
@@ -76,6 +81,7 @@ public struct FTPDestination: Codable, Identifiable, Hashable, Sendable {
sshKeyPath = v(.sshKeyPath, d.sshKeyPath)
allowInsecureTLS = v(.allowInsecureTLS, d.allowInsecureTLS)
preflight = v(.preflight, d.preflight)
replaceExisting = v(.replaceExisting, d.replaceExisting)
}
public var keychainAccount: String { "ftp-\(id.uuidString)" }
@@ -158,8 +164,11 @@ public struct FTPUploader: Sendable {
let directory = baseURL(d)
let key = directory.lowercased() + name.lowercased()
try await Self.reservations.withName(key, name: name) {
let names = try await listNames(d, curl: curl, password: password, createDirectories: true)
if names.contains(name.lowercased()) { throw UploadError.remoteNameConflict(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)
if names.contains(name.lowercased()) { throw UploadError.remoteNameConflict(name) }
}
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 source = Self.configQuote(base + tempName), target = Self.configQuote(base + name)
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 {
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
@@ -56,7 +56,8 @@ public enum Preflight {
/// Reads the actual upload files without decoding their pixels.
static func imageSizeIssues(files: [URL], minimum: Int) -> [PreflightIssue] {
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),
let info = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
let width = info[kCGImagePropertyPixelWidth] as? Int,