Kartenimport, Metadaten und Versand absichern

This commit is contained in:
Leon Tonhäuser committed 2026-11-05 09:23:44 +01:00
1 parent be6bd49da5
commit 427b6fa7b0
18 files changed
+638 -188

No files matched your search

@@ -80,7 +80,10 @@ local function writeResult(job, status, imported, exported, errors)
f:write('id=' .. job.id .. '\n') f:write('id=' .. job.id .. '\n')
f:write('status=' .. status .. '\n') f:write('status=' .. status .. '\n')
f:write('imported=' .. tostring(imported) .. '\n') f:write('imported=' .. tostring(imported) .. '\n')
for _, p in ipairs(exported) do f:write('exported=' .. p .. '\n') end for _, entry in ipairs(exported) do
f:write('exported=' .. entry.path .. '\n')
if entry.source then f:write('source=' .. entry.source .. '\n') end
end
for _, e in ipairs(errors) do f:write('error=' .. string.gsub(tostring(e), '\n', ' ') .. '\n') end for _, e in ipairs(errors) do f:write('error=' .. string.gsub(tostring(e), '\n', ' ') .. '\n') end
f:close() f:close()
os.rename(tmp, LrPathUtils.child(outbox, job.id .. '.result')) os.rename(tmp, LrPathUtils.child(outbox, job.id .. '.result'))
@@ -124,7 +127,7 @@ local function exportPhotos(job, photos, exported, errors)
for _, rendition in session:renditions() do for _, rendition in session:renditions() do
local ok, pathOrMessage = rendition:waitForRender() local ok, pathOrMessage = rendition:waitForRender()
if ok then if ok then
table.insert(exported, pathOrMessage) table.insert(exported, { path = pathOrMessage, source = rendition.photo:getRawMetadata("path") })
else else
table.insert(errors, 'Export: ' .. tostring(pathOrMessage)) table.insert(errors, 'Export: ' .. tostring(pathOrMessage))
end end
@@ -15,5 +15,5 @@ return {
LrLibraryMenuItems = { LrLibraryMenuItems = {
{ title = 'Lichtkasten: Inbox jetzt verarbeiten', file = 'ProcessNow.lua' }, { title = 'Lichtkasten: Inbox jetzt verarbeiten', file = 'ProcessNow.lua' },
}, },
VERSION = { major = 0, minor = 1, revision = 0, build = 1 }, VERSION = { major = 0, minor = 2, revision = 0, build = 2 },
} }
+4 -1
View File
@@ -75,6 +75,7 @@ Metadaten werden mit mehreren exiftool-Prozessen parallel gelesen und pro Ordner
`LightroomPlugin/LichtkastenBridge.lrplugin` ist ein kleines Lightroom-Classic-Plugin. `LightroomPlugin/LichtkastenBridge.lrplugin` ist ein kleines Lightroom-Classic-Plugin.
Installation: Einstellungen → Lightroom → **Plugin installieren**, danach Lightroom neu starten. Installation: Einstellungen → Lightroom → **Plugin installieren**, danach Lightroom neu starten.
Alternativ in Lightroom über **Datei → Zusatzmodul-Manager → Hinzufügen**. Alternativ in Lightroom über **Datei → Zusatzmodul-Manager → Hinzufügen**.
Für die IPTC-Nachbearbeitung und den automatischen Versand nach einem JPEG-Export wird die Bridge ab Version 0.2 benötigt.
Ablauf: Lichtkasten legt einen Auftrag nach `~/Library/Application Support/Lichtkasten/LRBridge/inbox`. Das Plugin Ablauf: Lichtkasten legt einen Auftrag nach `~/Library/Application Support/Lichtkasten/LRBridge/inbox`. Das Plugin
prüft diesen Ordner alle 2 Sekunden. Es importiert die Dateien (dabei liest LR die XMP-Sidecars mit Sternen und IPTC), prüft diesen Ordner alle 2 Sekunden. Es importiert die Dateien (dabei liest LR die XMP-Sidecars mit Sternen und IPTC),
@@ -174,7 +175,9 @@ Vor jedem FTP-Upload (⌘U, ⌘⇧U, Upload nach dem Lightroom-Export) prüft Li
Läuft alles durch, startet der Upload ohne Rückfrage. Sonst zeigt ein Fenster die Befunde pro Bild mit Läuft alles durch, startet der Upload ohne Rückfrage. Sonst zeigt ein Fenster die Befunde pro Bild mit
„Bearbeiten“ (öffnet das IPTC-Fenster), „Erneut prüfen“, „Nur fehlerfreie senden“ oder „Alle senden“. „Bearbeiten“ (öffnet das IPTC-Fenster), „Erneut prüfen“, „Nur fehlerfreie senden“ oder „Alle senden“.
Einstellungen → Agentur-Check legt Pflichtfelder und Regeln fest, pro FTP-Server lässt sich der Check abschalten. Einstellungen → Agentur-Check legt Pflichtfelder und Regeln fest, pro FTP-Server lässt sich der Check abschalten.
Immich-Uploads werden nicht geprüft. Immich-Uploads werden nicht geprüft. Beim FTP-/SFTP-Versand meldet Lichtkasten einen belegten Zielnamen als Fehler.
Für einen erneuten Versand unter demselben Namen muss die vorhandene Datei auf dem Server zuerst verschoben werden.
SFTP-Zielordner müssen bereits existieren und sich auflisten lassen.
## Gesendet-Status ## Gesendet-Status
+56 -30
View File
@@ -70,6 +70,8 @@ struct PendingUpload: Identifiable {
let id = UUID() let id = UUID()
let target: String let target: String
let targetName: String let targetName: String
var variant: UploadVariant
let skipAlreadySent: Bool
var items: [PhotoItem] var items: [PhotoItem]
/// item id → issues /// item id → issues
var issues: [String: [PreflightIssue]] var issues: [String: [PreflightIssue]]
@@ -203,7 +205,8 @@ final class AppState: ObservableObject {
@Published private(set) var sentLog = SentLog() @Published private(set) var sentLog = SentLog()
private var sentLogSaveTask: Task<Void, Never>? private var sentLogSaveTask: Task<Void, Never>?
/// Agentur-Check / double-send question waiting for the user (window "check") /// Agentur-Check / double-send question waiting for the user (window "check")
@Published var pendingUpload: PendingUpload? @Published private var pendingUploads: [PendingUpload] = []
var pendingUpload: PendingUpload? { pendingUploads.first }
/// Undo / redo of ratings, labels, tags and IPTC changes /// Undo / redo of ratings, labels, tags and IPTC changes
@Published private(set) var undoStack: [UndoEntry] = [] @Published private(set) var undoStack: [UndoEntry] = []
@Published private(set) var redoStack: [UndoEntry] = [] @Published private(set) var redoStack: [UndoEntry] = []
@@ -1081,35 +1084,47 @@ 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, sources: jobSources) } Task { await handleExported(result, 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, sources jobSources: [PhotoItem]) async { private func handleExported(_ result: LightroomJobResult, job: LightroomJob, sources jobSources: [PhotoItem]) async {
// Map exported JPEG → source item by base name (LR keeps the file name, may append "-2"). let sources = Dictionary(jobSources.map { original in
// Current state if the photo is still open (IPTC edited meanwhile), else the copy from the job. let path = (original.rawFile ?? original.primary).standardizedFileURL.path
let sources = jobSources.map { item($0.id) ?? $0 } return (path, item(original.id) ?? original)
if job.rewriteIPTCAfterExport, let w = writer { }, uniquingKeysWith: { first, _ in first })
for file in files { let writer = job.rewriteIPTCAfterExport ? self.writer : nil
let base = file.deletingPathExtension().lastPathComponent var exportedItems: [PhotoItem] = []
guard let src = sources.first(where: { base == $0.baseName || base.hasPrefix($0.baseName + "-") }) else { continue } var missingSources = 0
let jpegItem = PhotoItem(primary: file) for file in result.exported {
do { try await w.write(values: src.iptc, fields: IPTCField.all, to: jpegItem) } catch { report(error) } guard let path = result.exportSources[file]?.standardizedFileURL.path, let source = sources[path] else {
missingSources += 1
continue
}
var exported = PhotoItem(primary: file)
if job.rewriteIPTCAfterExport {
guard let writer else { continue }
do {
try await writer.write(values: source.iptc, fields: IPTCField.all, to: exported)
} catch {
report(error)
continue
} }
} }
// Exported JPEGs carry the IPTC of their RAW (needed for {event} album names, rename patterns …) exported.iptc = source.iptc
let exportedItems: [PhotoItem] = files.compactMap { file in exported.exif = source.exif
let base = file.deletingPathExtension().lastPathComponent exported.captureDate = source.captureDate
guard let src = sources.first(where: { base == $0.baseName || base.hasPrefix($0.baseName + "-") }) else { return nil } exportedItems.append(exported)
var it = PhotoItem(primary: file) }
it.iptc = src.iptc; it.exif = src.exif; it.captureDate = src.captureDate if missingSources > 0 && (job.rewriteIPTCAfterExport || !job.uploadTargets.isEmpty) {
return it alert = AppAlert(title: "Lightroom-Export ohne Originalzuordnung",
message: "Für \(missingSources) JPEG(s) wurden IPTC-Nachbearbeitung und automatischer Versand ausgesetzt. Bitte die Lichtkasten Bridge aktualisieren und Lightroom neu starten.")
} }
for target in job.uploadTargets { for target in job.uploadTargets {
requestUpload(exportedItems, to: target, skipAlreadySent: true) requestUpload(exportedItems, to: target, skipAlreadySent: true)
} }
if !job.uploadTargets.isEmpty { openWindow("tasks") } if !job.uploadTargets.isEmpty && pendingUpload == nil { openWindow("tasks") }
// SENT workflow: show the exported JPEGs for captioning. // SENT workflow: show the exported JPEGs for captioning.
if settings.lightroom.openSentAfterExport, let dir = job.exportFolder { if settings.lightroom.openSentAfterExport, let dir = job.exportFolder {
if folder != dir { lastRawFolder = folder; open(folder: dir) } else { refreshFolder() } if folder != dir { lastRawFolder = folder; open(folder: dir) } else { refreshFolder() }
@@ -1175,7 +1190,7 @@ final class AppState: ObservableObject {
var issues: [String: [PreflightIssue]] = [:] var issues: [String: [PreflightIssue]] = [:]
if runCheck { if runCheck {
for t in withFiles { for t in withFiles {
let i = preflightIssues(for: t) let i = preflightIssues(for: t, variant: variant)
if !i.isEmpty { issues[t.id] = i } if !i.isEmpty { issues[t.id] = i }
} }
} }
@@ -1186,41 +1201,52 @@ final class AppState: ObservableObject {
enqueueUpload(send, target: target, variant: variant) enqueueUpload(send, target: target, variant: variant)
return return
} }
pendingUpload = PendingUpload(target: target, targetName: name, items: withFiles, issues: issues, alreadySent: sentBefore) pendingUploads.append(PendingUpload(target: target, targetName: name, variant: variant, skipAlreadySent: skipAlreadySent ?? true,
items: withFiles, issues: issues, alreadySent: sentBefore))
openWindow("check") openWindow("check")
} }
/// Agentur-Check of one photo (current metadata). /// Agentur-Check of one photo (current metadata).
func preflightIssues(for item: PhotoItem) -> [PreflightIssue] { func preflightIssues(for item: PhotoItem, variant: UploadVariant) -> [PreflightIssue] {
let cur = self.item(item.id) ?? item let cur = self.item(item.id) ?? item
let open = openSuggestions(for: cur.id).map { s -> String in let open = openSuggestions(for: cur.id).map { s -> String in
let name = s.replacement.map { JerseyLogic.personName(replacement: $0, columns: []) } ?? "" let name = s.replacement.map { JerseyLogic.personName(replacement: $0, columns: []) } ?? ""
return [s.code ?? "#\(s.number)", name].filter { !$0.isEmpty }.joined(separator: " ") return [s.code ?? "#\(s.number)", name].filter { !$0.isEmpty }.joined(separator: " ")
} }
return Preflight.check(iptc: cur.iptc, exif: cur.exif, captureDate: cur.captureDate, codes: codes, return Preflight.check(iptc: cur.iptc, exif: cur.exif, captureDate: cur.captureDate, codes: codes,
options: settings.preflight, openSuggestions: open) options: settings.preflight, openSuggestions: open,
uploadFiles: uploadFiles(for: cur, variant: variant))
} }
/// Check window: run the check again (after fixing captions in the IPTC window). /// Check window: run the check again (after fixing captions in the IPTC window).
func recheckPendingUpload() { func recheckPendingUpload() {
guard var p = pendingUpload else { return } guard var p = pendingUpload, let variant = uploadVariant(p.target) else { return }
p.variant = variant
p.items = p.items.map { item($0.id) ?? $0 } p.items = p.items.map { item($0.id) ?? $0 }
var issues: [String: [PreflightIssue]] = [:] var issues: [String: [PreflightIssue]] = [:]
let destination = settings.ftpDestinations.first { $0.id.uuidString == p.target } let destination = settings.ftpDestinations.first { $0.id.uuidString == p.target }
if p.target != "immich" && (destination?.preflight ?? true) { if p.target != "immich" && (destination?.preflight ?? true) {
for t in p.items { let i = preflightIssues(for: t); if !i.isEmpty { issues[t.id] = i } } for t in p.items { let i = preflightIssues(for: t, variant: variant); if !i.isEmpty { issues[t.id] = i } }
} }
p.issues = issues p.issues = issues
p.alreadySent = Set(p.items.filter { sentLog.wasSent($0, to: p.target) }.map(\.id)) p.alreadySent = Set(p.items.filter { sentLog.wasSent($0, to: p.target) }.map(\.id))
pendingUpload = p pendingUploads[0] = p
} }
/// Check window: send these photos. /// Check window: send these photos.
func confirmPendingUpload(_ send: [PhotoItem]) { func confirmPendingUpload(_ send: [PhotoItem]) {
guard let p = pendingUpload, let variant = uploadVariant(p.target) else { pendingUpload = nil; return } guard let p = pendingUpload else { return }
pendingUpload = nil guard let variant = uploadVariant(p.target) else { discardPendingUpload(); return }
guard p.variant == variant else { recheckPendingUpload(); return }
discardPendingUpload()
guard !send.isEmpty else { return } guard !send.isEmpty else { return }
enqueueUpload(send.map { item($0.id) ?? $0 }, target: p.target, variant: variant) enqueueUpload(send, target: p.target, variant: variant)
}
func discardPendingUpload() {
guard !pendingUploads.isEmpty else { return }
pendingUploads.removeFirst()
recheckPendingUpload()
} }
private func enqueueUpload(_ items: [PhotoItem], target: String, variant: UploadVariant) { private func enqueueUpload(_ items: [PhotoItem], target: String, variant: UploadVariant) {
+10 -1
View File
@@ -111,18 +111,25 @@ final class UploadQueue: ObservableObject {
guard let state, !files.isEmpty else { return } guard let state, !files.isEmpty else { return }
let name: String let name: String
var pattern = "" var pattern = ""
var usedNames = Set<String>()
if target == "immich" { if target == "immich" {
name = "Immich" name = "Immich"
} else if let d = state.settings.ftpDestinations.first(where: { $0.id.uuidString == target }) { } else if let d = state.settings.ftpDestinations.first(where: { $0.id.uuidString == target }) {
name = d.name name = d.name
pattern = d.renamePattern pattern = d.renamePattern
let uploader = FTPUploader()
let directory = uploader.baseURL(d).lowercased()
let matchingProfiles = Set(state.settings.ftpDestinations.filter {
uploader.baseURL($0).lowercased() == directory
}.map { $0.id.uuidString })
usedNames = Set(jobs.filter { !$0.isFinished && matchingProfiles.contains($0.target) }
.map { $0.remoteName.lowercased() })
} else { return } } else { return }
var batchRef: UUID? var batchRef: UUID?
let batch = state.tasks.start(.upload, title: "Upload → \(name)", total: files.count) { [weak self] in let batch = state.tasks.start(.upload, title: "Upload → \(name)", total: files.count) { [weak self] in
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
@@ -228,6 +235,8 @@ final class UploadQueue: ObservableObject {
remoteName: job.remoteName, size: job.fileSize) remoteName: job.remoteName, size: job.fileSize)
setStatus(job.id, .done) setStatus(job.id, .done)
} }
} catch UploadError.remoteNameConflict(let name) {
setStatus(job.id, .failed(UploadError.remoteNameConflict(name).localizedDescription))
} catch { } catch {
if let i = jobs.firstIndex(where: { $0.id == job.id }), jobs[i].attempts < 3 { if let i = jobs.firstIndex(where: { $0.id == job.id }), jobs[i].attempts < 3 {
jobs[i].status = .waiting jobs[i].status = .waiting
@@ -22,6 +22,10 @@ struct PreflightWindow: View {
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, maxHeight: .infinity)
} }
} }
.onChange(of: state.pendingUpload?.id, initial: true) { _, _ in
skipSent = state.pendingUpload?.skipAlreadySent ?? true
showOK = false
}
.frame(minWidth: 760, minHeight: 520) .frame(minWidth: 760, minHeight: 520)
.background(LK.ground) .background(LK.ground)
} }
@@ -94,8 +98,8 @@ struct PreflightWindow: View {
Rectangle().fill(LK.border).frame(height: 1) Rectangle().fill(LK.border).frame(height: 1)
HStack(spacing: 10) { HStack(spacing: 10) {
Button("Abbrechen") { Button("Abbrechen") {
state.pendingUpload = nil state.discardPendingUpload()
dismissWindow(id: "check") if state.pendingUpload == nil { dismissWindow(id: "check") }
} }
.buttonStyle(LKButtonStyle()) .buttonStyle(LKButtonStyle())
.keyboardShortcut(.cancelAction) .keyboardShortcut(.cancelAction)
@@ -125,9 +129,11 @@ struct PreflightWindow: View {
private func send(_ items: [PhotoItem]) { private func send(_ items: [PhotoItem]) {
state.confirmPendingUpload(items) state.confirmPendingUpload(items)
if state.pendingUpload == nil {
state.openWindow("tasks") state.openWindow("tasks")
dismissWindow(id: "check") dismissWindow(id: "check")
} }
}
// MARK: Row per photo // MARK: Row per photo
+196 -113
View File
@@ -1,3 +1,4 @@
import CryptoKit
import Foundation import Foundation
/// PM Ingest "Filter Files": in-camera protected (locked) photos. /// PM Ingest "Filter Files": in-camera protected (locked) photos.
@@ -110,24 +111,43 @@ 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.json") return d.appendingPathComponent("ingest-history-v2.json")
} }
/// Incremental ingest key: original name + size + capture/mod date (survives card re-insert). private struct HistoryKey: Codable {
static func historyKey(_ url: URL) -> String { let destinations: [URL]
let a = try? FileManager.default.attributesOfItem(atPath: url.path) let folderPattern: String
let size = (a?[.size] as? NSNumber)?.int64Value ?? 0 let preserveStructure: Bool
let m = Int((a?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0) let sourceFolder: String
return "\(url.lastPathComponent)|\(size)|\(m)" let renamePattern: String?
let files: [String]
} }
static func loadHistory() -> Set<String> { private struct ImportedGroup: Codable {
guard let d = try? Data(contentsOf: historyURL), let s = try? JSONDecoder().decode(Set<String>.self, from: d) else { return [] } let folders: [URL]
return s let name: String
} }
static func saveHistory(_ s: Set<String>) { private static func sourceFingerprint(_ url: URL) throws -> String {
if let d = try? JSONEncoder().encode(s) { try? d.write(to: historyURL, options: .atomic) } 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)
} }
/// 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).
@@ -144,31 +164,73 @@ public enum IngestService {
onFolder: (@Sendable (URL) -> Void)? = nil, onFolder: (@Sendable (URL) -> Void)? = nil,
onSequence: (@Sendable (Int) -> Void)? = nil, onSequence: (@Sendable (Int) -> Void)? = nil,
progress: @escaping @Sendable (IngestProgress) -> Void) async throws -> IngestResult { progress: @escaping @Sendable (IngestProgress) -> Void) async throws -> IngestResult {
try await run(sources: sources, settings: settings, exiftool: exiftool,
historyFile: settings.incremental ? historyURL : nil,
onFolder: onFolder, onSequence: onSequence, progress: progress)
}
static func run(sources: [URL], settings: IngestSettings, exiftool: ExifTool, historyFile: URL?,
onFolder: (@Sendable (URL) -> Void)? = nil,
onSequence: (@Sendable (Int) -> Void)? = nil,
progress: @escaping @Sendable (IngestProgress) -> Void) async throws -> IngestResult {
let fm = FileManager.default let fm = FileManager.default
guard !settings.primaryDestination.isEmpty else { throw UploadError.failed("Kein Ziel für den Ingest gewählt.") } guard !settings.primaryDestination.isEmpty else { throw UploadError.failed("Kein Ziel für den Ingest gewählt.") }
// 1. scan + filters let destRoots = ([settings.primaryDestination] +
var entries: [(item: PhotoItem, root: URL, locked: Bool)] = [] (settings.secondaryEnabled && !settings.backupDestination.isEmpty ? [settings.backupDestination] : []))
for s in sources { .map { URL(fileURLWithPath: $0, isDirectory: true).resolvingSymlinksInPath().standardizedFileURL }
let ro = volumeIsReadOnly(s) guard Set(destRoots).count == destRoots.count else {
for item in try FolderScanner.scan(folder: s, recursive: true) { throw UploadError.failed("Hauptziel und Backup-Ziel müssen verschieden sein.")
entries.append((item, s, isLocked(item.primary, volumeReadOnly: ro)))
} }
}
entries = entries.filter { e in // A history entry proves which full group was copied to these destinations.
switch settings.lockedFilter { var history = historyFile.map { loadHistory(at: $0) } ?? [:]
case .all: break var historyChanged = false
case .lockedOnly: if !e.locked { return false }
case .unlockedOnly: if e.locked { return false }
}
return true
}
var history = settings.incremental ? loadHistory() : []
var skipped = 0 var skipped = 0
if settings.incremental { let keyEncoder = JSONEncoder()
let before = entries.count keyEncoder.outputFormatting = [.sortedKeys]
entries = entries.filter { !history.contains(historyKey($0.item.primary)) } typealias Entry = (item: PhotoItem, relativeFolder: String, locked: Bool, files: [URL], historyKey: String?)
skipped = before - entries.count var entries: [Entry] = []
progress(IngestProgress(done: 0, total: 0, currentFile: "Prüfe Quelldateien …"))
for source in sources {
let readOnly = volumeIsReadOnly(source)
for item in try FolderScanner.scan(folder: source, recursive: true) {
try Task.checkCancellation()
let locked = isLocked(item.primary, volumeReadOnly: readOnly)
if settings.lockedFilter == .lockedOnly && !locked { continue }
if settings.lockedFilter == .unlockedOnly && locked { continue }
var files = [item.primary] + item.companions
switch settings.rawFilter {
case .all: break
case .rawOnly: files = files.filter { FileKind(url: $0).isRawLike }
case .nonRawOnly: files = files.filter { !FileKind(url: $0).isRawLike }
}
guard !files.isEmpty else { continue }
if item.kind.usesSidecar, files.contains(item.primary), fm.fileExists(atPath: item.sidecarURL.path) {
files.append(item.sidecarURL)
}
let relative = settings.preserveStructure
? 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))
}
} }
progress(IngestProgress(done: 0, total: entries.count, currentFile: "Lese Aufnahmezeiten …")) progress(IngestProgress(done: 0, total: entries.count, currentFile: "Lese Aufnahmezeiten …"))
@@ -186,90 +248,89 @@ public enum IngestService {
var copied: [URL] = [] var copied: [URL] = []
var lockedCopies: [URL] = [] var lockedCopies: [URL] = []
var seq = settings.startSequence var seq = settings.startSequence
let total = entries.reduce(0) { total, e in let total = entries.reduce(0) { $0 + $1.files.filter { $0.pathExtension.lowercased() != "xmp" }.count }
let n = 1 + e.item.companions.count
return total + n
}
var done = 0 var done = 0
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
// also after a cancel/error the next number is handed back, so the next ingest continues there
defer { defer {
if settings.incremental { saveHistory(history) } if historyChanged, let historyFile { try? saveHistory(history, at: historyFile) }
if settings.sequenceEnabled { onSequence?(seq) } if settings.sequenceEnabled { onSequence?(seq) }
} }
for e in entries { for entry in entries {
try Task.checkCancellation() try Task.checkCancellation()
let item = e.item let item = entry.item
let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, sequence: settings.sequenceEnabled ? seq : nil, iptc: item.iptc) let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif,
sequence: settings.sequenceEnabled ? seq : nil, iptc: item.iptc)
let sub = VariableExpander.expand(settings.folderPattern, context: ctx) let sub = VariableExpander.expand(settings.folderPattern, context: ctx)
.replacingOccurrences(of: ":", with: "-") .replacingOccurrences(of: ":", with: "-")
.trimmingCharacters(in: .whitespaces) .trimmingCharacters(in: .whitespaces)
var baseName = item.baseName let baseName = settings.renameEnabled && !settings.renamePattern.isEmpty
if settings.renameEnabled, !settings.renamePattern.isEmpty { ? VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-")
baseName = VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-") : item.baseName
} let folders = destRoots.map { root in
// Card structure (DCIM/100NZ8_1) below the destination if requested var folder = root
let rel = settings.preserveStructure
? item.primary.deletingLastPathComponent().path.replacingOccurrences(of: e.root.path, with: "")
.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
: ""
var rawFiles = [item.primary] + item.companions
switch settings.rawFilter {
case .all: break
case .rawOnly: rawFiles = rawFiles.filter { FileKind(url: $0).isRawLike }
case .nonRawOnly: rawFiles = rawFiles.filter { !FileKind(url: $0).isRawLike }
}
guard !rawFiles.isEmpty else { continue }
if settings.sequenceEnabled { seq += 1 } // only photos that are really copied get a number
var files = rawFiles
if item.kind.usesSidecar, fm.fileExists(atPath: item.sidecarURL.path), rawFiles.contains(item.primary) { files.append(item.sidecarURL) }
// Name for this photo in every destination: an existing file is never deleted. Same name + same size
// = already copied (skip); same name, other photo (second body, second card) → "-1", "-2" …
var targetName = baseName
var skipGroup = false
if let primaryFolder = destRoots.first.map({ root -> URL in
var f = URL(fileURLWithPath: root)
if !sub.isEmpty { f.appendPathComponent(sub, isDirectory: true) }
if !rel.isEmpty { f.appendPathComponent(rel, isDirectory: true) }
return f
}) {
(targetName, skipGroup) = uniqueName(baseName, files: files, in: primaryFolder,
skipDuplicates: settings.skipDuplicates)
}
for destRoot in destRoots {
var folder = URL(fileURLWithPath: destRoot)
if !sub.isEmpty { folder.appendPathComponent(sub, isDirectory: true) } if !sub.isEmpty { folder.appendPathComponent(sub, isDirectory: true) }
if !rel.isEmpty { folder.appendPathComponent(rel, isDirectory: true) } if !entry.relativeFolder.isEmpty { folder.appendPathComponent(entry.relativeFolder, isDirectory: true) }
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
}
var newCopies: [URL] = []
var newPrimary: URL?
do {
for (folderIndex, folder) in targets.enumerated() {
try fm.createDirectory(at: folder, withIntermediateDirectories: true) try fm.createDirectory(at: folder, withIntermediateDirectories: true)
let isPrimary = destRoot == settings.primaryDestination if folderIndex == 0, usedFolders.insert(folder).inserted { onFolder?(folder) }
if isPrimary, usedFolders.insert(folder).inserted { onFolder?(folder) } for (fileIndex, src) in entry.files.enumerated() {
for (n, src) in files.enumerated() { try Task.checkCancellation()
let dest = folder.appendingPathComponent(targetName).appendingPathExtension(src.pathExtension) let dest = destination(for: src, name: name, in: folder)
if skipGroup || fm.fileExists(atPath: dest.path) { if fm.fileExists(atPath: dest.path) {
// already there (duplicate, or the backup already has it) – never overwrite if !(canRestore && folderIndex == 0) && !fm.contentsEqual(atPath: src.path, andPath: dest.path) {
if isPrimary, n == 0, src.pathExtension.lowercased() != "xmp" { done += 1 } throw UploadError.failed("Die Zieldatei wurde zwischenzeitlich geändert: \(dest.path)")
continue
} }
guard (try dest.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true else {
throw UploadError.failed("Die Zieldatei ist keine reguläre Datei: \(dest.path)")
}
} else {
try copy(src, to: dest) try copy(src, to: dest)
if isPrimary { newCopies.append(dest)
if n == 0 { if folderIndex == 0 && fileIndex == 0 { newPrimary = dest }
copied.append(dest)
if e.locked { lockedCopies.append(dest) }
} }
if src.pathExtension.lowercased() != "xmp" { if folderIndex == 0 && src.pathExtension.lowercased() != "xmp" {
done += 1 done += 1
progress(IngestProgress(done: done, total: total, currentFile: src.lastPathComponent)) progress(IngestProgress(done: done, total: total, currentFile: src.lastPathComponent))
} }
} }
} }
} catch {
// A group can be retried with its original name after a failure.
for file in newCopies.reversed() { try? fm.removeItem(at: file) }
throw error
} }
if settings.incremental { history.insert(historyKey(item.primary)) } if let newPrimary {
copied.append(newPrimary)
if entry.locked { lockedCopies.append(newPrimary) }
}
if settings.sequenceEnabled && previous == nil { seq += 1 }
if newCopies.isEmpty { skipped += 1 }
if let key = entry.historyKey {
history[key] = ImportedGroup(folders: targets, name: name)
historyChanged = true
}
}
if historyChanged, let historyFile {
try saveHistory(history, at: historyFile)
historyChanged = false
} }
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)
@@ -291,27 +352,49 @@ 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 /// A shared name across destinations that either has no collision or can resume a partial copy.
/// (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) { static func uniqueName(_ base: String, files: [URL], in folder: URL, skipDuplicates: Bool) -> (name: String, skip: Bool) {
let fm = FileManager.default uniqueName(base, files: files, in: [folder], skipDuplicates: skipDuplicates)
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 { private static func uniqueName(_ base: String, files: [URL], in folders: [URL], skipDuplicates: Bool) -> (name: String, skip: Bool) {
func size(_ u: URL) -> Int64? { let fm = FileManager.default
guard let attrs = try? FileManager.default.attributesOfItem(atPath: u.path) else { return nil } var suffix = 0
return (attrs[.size] as? NSNumber)?.int64Value while true {
let name = suffix == 0 ? base : "\(base)-\(suffix)"
var missing = false
var conflict = false
for folder in folders {
for src in files {
let dest = destination(for: src, name: name, in: folder)
if !fm.fileExists(atPath: dest.path) {
missing = true
} else if !skipDuplicates || !fm.contentsEqual(atPath: src.path, andPath: dest.path) {
conflict = true
break
} }
let sa = size(a) }
return sa != nil && sa == size(b) if conflict { break }
}
if !conflict { return (name, !missing) }
suffix += 1
}
}
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,13 +203,24 @@ 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 {
if let e = fm.enumerator(at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles, .skipsPackageDescendants]) { var scanError: Error?
for case let u as URL in e { urls.append(u) } guard let enumerator = fm.enumerator(at: folder, includingPropertiesForKeys: keys,
options: [.skipsHiddenFiles, .skipsPackageDescendants],
errorHandler: { _, error in
scanError = error
return false
}) else {
throw CocoaError(.fileReadUnknown, userInfo: [NSURLErrorKey: folder])
} }
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 = urls.filter { !$0.lastPathComponent.hasPrefix("._") && FileKind(url: $0).isImage } urls = try urls.filter { url in
guard !url.lastPathComponent.hasPrefix("._"), FileKind(url: url).isImage else { return false }
return try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true
}
// Group by directory + lowercase base name // Group by directory + lowercase base name
var groups: [String: [URL]] = [:] var groups: [String: [URL]] = [:]
@@ -49,9 +49,11 @@ public struct LightroomJobResult: Sendable {
public var imported: Int public var imported: Int
public var exported: [URL] public var exported: [URL]
public var errors: [String] public var errors: [String]
public private(set) var exportSources: [URL: URL] = [:]
public static func parse(_ text: String) -> LightroomJobResult { public static func parse(_ text: String) -> LightroomJobResult {
var r = LightroomJobResult(id: "", ok: false, imported: 0, exported: [], errors: []) var r = LightroomJobResult(id: "", ok: false, imported: 0, exported: [], errors: [])
var lastExport: URL?
for line in text.components(separatedBy: .newlines) { for line in text.components(separatedBy: .newlines) {
guard let eq = line.firstIndex(of: "=") else { continue } guard let eq = line.firstIndex(of: "=") else { continue }
let k = String(line[..<eq]), v = String(line[line.index(after: eq)...]) let k = String(line[..<eq]), v = String(line[line.index(after: eq)...])
@@ -59,7 +61,13 @@ public struct LightroomJobResult: Sendable {
case "id": r.id = v case "id": r.id = v
case "status": r.ok = v == "done" case "status": r.ok = v == "done"
case "imported": r.imported = Int(v) ?? 0 case "imported": r.imported = Int(v) ?? 0
case "exported": r.exported.append(URL(fileURLWithPath: v)) case "exported":
let file = URL(fileURLWithPath: v)
r.exported.append(file)
lastExport = file
case "source":
if let file = lastExport, v.hasPrefix("/") { r.exportSources[file] = URL(fileURLWithPath: v) }
lastExport = nil
case "error": r.errors.append(v) case "error": r.errors.append(v)
default: break default: break
} }
@@ -111,7 +111,7 @@ 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)")
if !timePart.isEmpty { args.append("-IPTC:TimeCreated=\(timePart)") } args.append("-IPTC:TimeCreated=\(timePart)")
} }
return args return args
} }
@@ -127,6 +127,7 @@ public enum PMSettingsImporter {
let n = raw.lowercased().replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "_", with: "") let n = raw.lowercased().replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "_", with: "")
.replacingOccurrences(of: "-", with: "").replacingOccurrences(of: "/", with: "") .replacingOccurrences(of: "-", with: "").replacingOccurrences(of: "/", with: "")
guard !n.isEmpty else { return nil } guard !n.isEmpty else { return nil }
if let field = IPTCField.all.first(where: { $0.id.lowercased() == n }) { return field }
let aliases: [String: String] = ["captionabstract": "caption", "description": "caption", "caption": "caption", let aliases: [String: String] = ["captionabstract": "caption", "description": "caption", "caption": "caption",
"byline": "creator", "photographer": "creator", "sublocation": "sublocation", "byline": "creator", "photographer": "creator", "sublocation": "sublocation",
"location": "sublocation", "provincestate": "state", "stateprovince": "state", "location": "sublocation", "provincestate": "state", "stateprovince": "state",
@@ -137,7 +138,7 @@ public enum PMSettingsImporter {
return IPTCField.all.first { f in return IPTCField.all.first { f in
let pm = f.pmLabel.lowercased().replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "/", with: "") let pm = f.pmLabel.lowercased().replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "/", with: "")
.replacingOccurrences(of: "'", with: "").replacingOccurrences(of: ".", with: "") .replacingOccurrences(of: "'", with: "").replacingOccurrences(of: ".", with: "")
return f.id.lowercased() == n || pm == n || (f.iimTag?.lowercased().replacingOccurrences(of: "iptc:", with: "") return pm == n || (f.iimTag?.lowercased().replacingOccurrences(of: "iptc:", with: "")
.replacingOccurrences(of: "-", with: "") == n) .replacingOccurrences(of: "-", with: "") == n)
} }
} }
+104 -30
View File
@@ -31,7 +31,7 @@ public struct FTPDestination: Codable, Identifiable, Hashable, Sendable {
public var username: String public var username: String
public var remoteDirectory: String public var remoteDirectory: String
public var passive: Bool public var passive: Bool
/// Upload as "<name>.part" and rename when complete – agency ingest never sees half files. /// Upload under a unique .part name and rename when complete.
public var uploadWithTempName: Bool public var uploadWithTempName: Bool
/// Optional rename pattern with variables, e.g. "{isodate}_{filenamebase}". Empty = keep name. /// Optional rename pattern with variables, e.g. "{isodate}_{filenamebase}". Empty = keep name.
public var renamePattern: String public var renamePattern: String
@@ -83,11 +83,13 @@ public struct FTPDestination: Codable, Identifiable, Hashable, Sendable {
public enum UploadError: LocalizedError { public enum UploadError: LocalizedError {
case failed(String) case failed(String)
case remoteNameConflict(String)
case curlMissingSFTP case curlMissingSFTP
public var errorDescription: String? { public var errorDescription: String? {
switch self { switch self {
case .failed(let m): return m case .failed(let m): return m
case .remoteNameConflict(let name): return "Der Zielname „\(name)“ ist bereits belegt."
case .curlMissingSFTP: case .curlMissingSFTP:
return "Das System-curl unterstützt kein SFTP. Bitte `brew install curl` ausführen (wird automatisch verwendet)." return "Das System-curl unterstützt kein SFTP. Bitte `brew install curl` ausführen (wird automatisch verwendet)."
} }
@@ -96,7 +98,12 @@ public enum UploadError: LocalizedError {
/// FTP/FTPS/SFTP upload via curl (ships with macOS; Homebrew curl is preferred when present for SFTP). /// FTP/FTPS/SFTP upload via curl (ships with macOS; Homebrew curl is preferred when present for SFTP).
public struct FTPUploader: Sendable { public struct FTPUploader: Sendable {
public init() {} private let curlExecutable: String?
private static let reservations = RemoteNameReservations()
public init() { curlExecutable = nil }
init(curlExecutable: String) { self.curlExecutable = curlExecutable }
static func curlBinary(needsSFTP: Bool) -> String? { static func curlBinary(needsSFTP: Bool) -> String? {
let candidates = ["/opt/homebrew/opt/curl/bin/curl", "/usr/local/opt/curl/bin/curl", "/usr/bin/curl"] let candidates = ["/opt/homebrew/opt/curl/bin/curl", "/usr/local/opt/curl/bin/curl", "/usr/bin/curl"]
@@ -141,33 +148,40 @@ public struct FTPUploader: Sendable {
public func upload(file: URL, remoteName: String? = nil, to d: FTPDestination, password: String?, public func upload(file: URL, remoteName: String? = nil, to d: FTPDestination, password: String?,
progress: (@Sendable (Int64) -> Void)? = nil) async throws { progress: (@Sendable (Int64) -> Void)? = nil) async throws {
let name = remoteName ?? file.lastPathComponent let name = remoteName ?? file.lastPathComponent
guard let curl = FTPUploader.curlBinary(needsSFTP: d.proto == .sftp) else { throw UploadError.curlMissingSFTP } guard !name.isEmpty, name != ".", name != "..",
let tempName = d.uploadWithTempName ? name + ".part" : name !name.contains("/"), name.rangeOfCharacter(from: .controlCharacters.union(.newlines)) == nil else {
let url = baseURL(d) + FTPUploader.encodePath(tempName) throw UploadError.failed("Ungültiger Dateiname für den Upload.")
var config: [String] = []
config.append("user = " + FTPUploader.configQuote("\(d.username):\(password ?? "")"))
// No --silent: the progress meter on stderr gives the live upload rate.
var args = ["--show-error", "--fail", "--ftp-create-dirs", "--retry", "2", "-o", "/dev/null",
"--connect-timeout", "20", "-K", "-", "-T", file.path, url]
switch d.proto {
case .ftpsExplicit: args.insert("--ssl-reqd", at: 0)
case .sftp:
if !d.sshKeyPath.isEmpty { args.insert(contentsOf: ["--key", (d.sshKeyPath as NSString).expandingTildeInPath], at: 0) }
default: break
} }
if d.allowInsecureTLS { args.insert("--insecure", at: 0) } guard let curl = curlExecutable ?? FTPUploader.curlBinary(needsSFTP: d.proto == .sftp) else {
if !d.passive && d.proto != .sftp { args.insert(contentsOf: ["--ftp-port", "-"], at: 0) } throw UploadError.curlMissingSFTP
}
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) }
try await transfer(file: file, name: name, to: d, curl: curl, password: password, progress: progress)
}
}
private func transfer(file: URL, name: String, to d: FTPDestination, curl: String, password: String?,
progress: (@Sendable (Int64) -> Void)?) async throws {
let tempName = d.uploadWithTempName ? "lichtkasten-\(UUID().uuidString).part" : name
let url = baseURL(d) + Self.encodePath(tempName)
// No --silent: the progress meter on stderr gives the live upload rate.
var args = connectionOptions(d) + ["--show-error", "--fail", "--ftp-create-dirs", "-o", "/dev/null",
"--connect-timeout", "20", "-K", "-", "-T", file.path, url]
if d.uploadWithTempName { args.insert(contentsOf: ["--retry", "2"], at: 0) }
if d.uploadWithTempName { if d.uploadWithTempName {
if d.proto == .sftp { if d.proto == .sftp {
let dir = d.remoteDirectory.hasPrefix("/") ? d.remoteDirectory : "~/" + d.remoteDirectory let base = sftpPath(d)
let base = dir.hasSuffix("/") ? dir : dir + "/" let source = Self.configQuote(base + tempName), target = Self.configQuote(base + name)
args.insert(contentsOf: ["-Q", "-rename \"\(base)\(tempName)\" \"\(base)\(name)\""], at: 0) args.insert(contentsOf: ["-Q", "-rename \(source) \(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)
} }
} }
let result = try await FTPUploader.runStreaming(curl, args, stdin: config.joined(separator: "\n") + "\n") { line in let result = try await FTPUploader.runStreaming(curl, args, stdin: credentials(d, password: password)) { line in
if let sent = FTPUploader.uploadedBytes(fromProgressLine: line) { progress?(sent) } if let sent = FTPUploader.uploadedBytes(fromProgressLine: line) { progress?(sent) }
} }
if result.status != 0 { if result.status != 0 {
@@ -182,14 +196,63 @@ public struct FTPUploader: Sendable {
/// Checks login + directory listing. /// Checks login + directory listing.
public func testConnection(_ d: FTPDestination, password: String?) async throws { public func testConnection(_ d: FTPDestination, password: String?) async throws {
guard let curl = FTPUploader.curlBinary(needsSFTP: d.proto == .sftp) else { throw UploadError.curlMissingSFTP } guard let curl = curlExecutable ?? Self.curlBinary(needsSFTP: d.proto == .sftp) else {
var args = ["--silent", "--show-error", "--fail", "--connect-timeout", "15", "-K", "-", "--list-only", baseURL(d)] throw UploadError.curlMissingSFTP
if d.proto == .ftpsExplicit { args.insert("--ssl-reqd", at: 0) } }
if d.allowInsecureTLS { args.insert("--insecure", at: 0) } _ = try await listNames(d, curl: curl, password: password, createDirectories: false)
if d.proto == .sftp, !d.sshKeyPath.isEmpty { args.insert(contentsOf: ["--key", (d.sshKeyPath as NSString).expandingTildeInPath], at: 0) } }
let cfg = "user = " + FTPUploader.configQuote("\(d.username):\(password ?? "")") + "\n"
let r = try await FTPUploader.run(curl, args, stdin: cfg) private func listNames(_ d: FTPDestination, curl: String, password: String?,
if r.status != 0 { throw UploadError.failed(r.stderr.isEmpty ? "Verbindung fehlgeschlagen (curl \(r.status))" : r.stderr) } createDirectories: Bool) async throws -> Set<String> {
var options = connectionOptions(d) + ["--silent", "--show-error", "--fail", "--connect-timeout", "15",
"--max-time", "60", "-K", "-"]
if createDirectories && d.proto != .sftp { options.append("--ftp-create-dirs") }
let url = baseURL(d)
let config = credentials(d, password: password)
// NLST may omit directories and symbolic links. Prefer the machine-readable FTP listing.
if createDirectories && d.proto != .sftp {
let detailed = try await Self.run(curl, options + ["--request", "MLSD", url], stdin: config)
if detailed.status == 0 {
let entries = detailed.stdout.split(whereSeparator: \.isNewline)
let names = entries.compactMap { entry -> String? in
guard let separator = entry.firstIndex(of: " "), entry[..<separator].hasSuffix(";") else { return nil }
return String(entry[entry.index(after: separator)...]).lowercased()
}
if names.count == entries.count { return Set(names) }
}
}
let result = try await Self.run(curl, options + ["--list-only", url], stdin: config)
guard result.status == 0 else {
let detail = result.stderr.isEmpty ? "curl \(result.status)" : result.stderr
let hint = d.proto == .sftp ? " Der SFTP-Zielordner muss vorhanden und lesbar sein." : ""
throw UploadError.failed("Zielordner „\(d.name)“ konnte nicht geprüft werden: \(detail)\(hint)")
}
return Set(result.stdout.components(separatedBy: .newlines).compactMap { line in
line.split(separator: "/").last.map { $0.lowercased() }
})
}
private func sftpPath(_ d: FTPDestination) -> String {
let prefix = d.remoteDirectory.hasPrefix("/") ? "/" : "~/"
let components = d.remoteDirectory.split(separator: "/")
return components.isEmpty ? prefix : prefix + components.joined(separator: "/") + "/"
}
private func credentials(_ d: FTPDestination, password: String?) -> String {
"user = " + Self.configQuote("\(d.username):\(password ?? "")") + "\n"
}
private func connectionOptions(_ d: FTPDestination) -> [String] {
var args = ["--globoff"]
if d.proto == .ftpsExplicit { args.append("--ssl-reqd") }
if d.allowInsecureTLS { args.append("--insecure") }
if d.proto == .sftp, !d.sshKeyPath.isEmpty {
args += ["--key", (d.sshKeyPath as NSString).expandingTildeInPath]
}
if !d.passive && d.proto != .sftp { args += ["--ftp-port", "-"] }
return args
} }
// MARK: Process helpers // MARK: Process helpers
@@ -293,3 +356,14 @@ public struct FTPUploader: Sendable {
stderr: String(decoding: errData, as: UTF8.self)) stderr: String(decoding: errData, as: UTF8.self))
} }
} }
private actor RemoteNameReservations {
private var active = Set<String>()
func withName(_ key: String, name: String, operation: @Sendable () async throws -> Void) async throws {
guard active.insert(key).inserted else { throw UploadError.remoteNameConflict(name) }
defer { active.remove(key) }
try await operation()
}
}
+21 -2
View File
@@ -1,4 +1,5 @@
import Foundation import Foundation
import ImageIO
/// Agentur-Check: what is checked before photos go to an agency server. /// Agentur-Check: what is checked before photos go to an agency server.
public struct PreflightOptions: Codable, Hashable, Sendable { public struct PreflightOptions: Codable, Hashable, Sendable {
@@ -52,9 +53,25 @@ public struct PreflightIssue: Hashable, Identifiable, Sendable {
} }
public enum Preflight { 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
guard let source = CGImageSourceCreateWithURL(file as CFURL, nil),
let info = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
let width = info[kCGImagePropertyPixelWidth] as? Int,
let height = info[kCGImagePropertyPixelHeight] as? Int else {
return PreflightIssue(.error, "\(file.lastPathComponent): Bildgröße nicht lesbar")
}
let edge = max(width, height)
guard edge < minimum else { return nil }
return PreflightIssue(.error, "\(file.lastPathComponent): \(edge) px lange Kante (mindestens \(minimum) px)")
}
}
/// Checks one photo. `openSuggestions` = codes/names of jersey suggestions still open. /// Checks one photo. `openSuggestions` = codes/names of jersey suggestions still open.
public static func check(iptc: IPTCValues, exif: [String: String], captureDate: Date?, codes: CodeReplacements, public static func check(iptc: IPTCValues, exif: [String: String], captureDate: Date?, codes: CodeReplacements,
options: PreflightOptions, openSuggestions: [String] = []) -> [PreflightIssue] { options: PreflightOptions, openSuggestions: [String] = [], uploadFiles: [URL]? = nil) -> [PreflightIssue] {
var issues: [PreflightIssue] = [] var issues: [PreflightIssue] = []
// 1. required fields // 1. required fields
@@ -134,7 +151,9 @@ public enum Preflight {
} }
// 7. image size // 7. image size
if options.minLongEdge > 0, if let uploadFiles {
issues += imageSizeIssues(files: uploadFiles, minimum: options.minLongEdge)
} else if options.minLongEdge > 0,
let w = exif["ImageWidth"].flatMap({ Int($0) }), let h = exif["ImageHeight"].flatMap({ Int($0) }), let w = exif["ImageWidth"].flatMap({ Int($0) }), let h = exif["ImageHeight"].flatMap({ Int($0) }),
max(w, h) < options.minLongEdge { max(w, h) < options.minLongEdge {
issues.append(PreflightIssue(.error, "Bild zu klein: \(max(w, h)) px lange Kante (mindestens \(options.minLongEdge) px)")) issues.append(PreflightIssue(.error, "Bild zu klein: \(max(w, h)) px lange Kante (mindestens \(options.minLongEdge) px)"))
@@ -413,6 +413,11 @@ final class BugfixTests: XCTestCase {
XCTAssertTrue(lib.sets.first?.enabled ?? false) XCTAssertTrue(lib.sets.first?.enabled ?? false)
} }
func testDateOnlyUpdateClearsIIMTimeCreated() {
let arguments = MetadataWriter.dateArguments("2026-11-03", writeIIM: true)
XCTAssertTrue(arguments.contains("-IPTC:TimeCreated="))
}
func testDateCreatedKeepsTimeOfDay() { func testDateCreatedKeepsTimeOfDay() {
var item = PhotoItem(primary: URL(fileURLWithPath: "/x/a.jpg")) 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) item.apply(fileMeta: ["XMP-photoshop:DateCreated": .string("2026:11:02 18:31:05+01:00")], sidecarMeta: nil)
@@ -0,0 +1,37 @@
import Foundation
import XCTest
@testable import LichtkastenCore
final class DeliveryTests: XCTestCase {
func testMinimumEdgeUsesTheFileOnDisk() throws {
let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".png")
let image = try XCTUnwrap(Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jS0sAAAAASUVORK5CYII="))
try image.write(to: file)
defer { try? FileManager.default.removeItem(at: file) }
var options = PreflightOptions()
options.requiredFields = []
options.minLongEdge = 2
let issues = Preflight.check(iptc: IPTCValues(), exif: ["ImageWidth": "4000", "ImageHeight": "3000"],
captureDate: nil, codes: CodeReplacements(), options: options,
uploadFiles: [file])
XCTAssertEqual(issues.count, 1)
XCTAssertEqual(issues.first?.severity, .error)
XCTAssertTrue(issues.first?.message.contains("1 px") == true)
}
func testExportResultKeepsOriginalPathForEachJPEG() {
let result = LightroomJobResult.parse("""
exported=/sent/DSC_0001-2.jpg
source=/raw/DSC_0001-2.nef
exported=/sent/DSC_0001-3.jpg
source=/raw/DSC_0001.nef
exported=/sent/legacy.jpg
""")
XCTAssertEqual(result.exportSources[URL(fileURLWithPath: "/sent/DSC_0001-2.jpg")]?.path,
"/raw/DSC_0001-2.nef")
XCTAssertEqual(result.exportSources[URL(fileURLWithPath: "/sent/DSC_0001-3.jpg")]?.path,
"/raw/DSC_0001.nef")
XCTAssertNil(result.exportSources[URL(fileURLWithPath: "/sent/legacy.jpg")])
}
}
@@ -0,0 +1,38 @@
import Foundation
@testable import LichtkastenCore
import XCTest
final class FTPUploaderTests: XCTestCase {
func testExistingRemoteFileStopsUpload() async throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
let curl = directory.appendingPathComponent("curl")
let uploaded = directory.appendingPathComponent("uploaded")
let script = """
#!/bin/sh
for arg do
if [ "$arg" = "MLSD" ]; then
printf '%s\\r\\n' 'type=file; other.jpg' 'type=OS.unix=slink; PHOTO.jpg'
exit 0
fi
done
touch '\(uploaded.path)'
"""
try script.write(to: curl, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: curl.path)
let uploader = FTPUploader(curlExecutable: curl.path)
let destination = FTPDestination(host: "example.test")
let photo = directory.appendingPathComponent("photo.jpg")
try Data([0]).write(to: photo)
do {
try await uploader.upload(file: photo, to: destination, password: nil)
XCTFail("An existing remote filename should stop the upload")
} catch UploadError.remoteNameConflict(let name) {
XCTAssertEqual(name, "photo.jpg")
}
XCTAssertFalse(FileManager.default.fileExists(atPath: uploaded.path))
}
}
@@ -0,0 +1,117 @@
import Foundation
import XCTest
@testable import LichtkastenCore
final class IngestRecoveryTests: XCTestCase {
private func fixture() throws -> (root: URL, source: URL, primary: URL, backup: URL) {
let fm = FileManager.default
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
let source = root.appendingPathComponent("card", isDirectory: true)
let primary = root.appendingPathComponent("primary", isDirectory: true)
let backup = root.appendingPathComponent("backup", isDirectory: true)
for dir in [source, primary, backup] { try fm.createDirectory(at: dir, withIntermediateDirectories: true) }
addTeardownBlock { try fm.removeItem(at: root) }
return (root, source, primary, backup)
}
func testEqualSizeDoesNotIdentifyDuplicate() throws {
let dirs = try fixture()
let src = dirs.source.appendingPathComponent("DSC_0001.NEF")
try Data([1, 2]).write(to: src)
try Data([2, 1]).write(to: dirs.primary.appendingPathComponent(src.lastPathComponent))
let result = IngestService.uniqueName("DSC_0001", files: [src], in: dirs.primary, skipDuplicates: true)
XCTAssertEqual(result.name, "DSC_0001-1")
XCTAssertFalse(result.skip)
}
func testMissingRecursiveSourceThrows() throws {
let dirs = try fixture()
XCTAssertThrowsError(try FolderScanner.scan(folder: dirs.root.appendingPathComponent("missing"), recursive: true))
}
func testRetryFillsBackupWhenPrimaryAlreadyExists() async throws {
let dirs = try fixture()
let src = try makePhoto(in: dirs.source)
try FileManager.default.copyItem(at: src, to: dirs.primary.appendingPathComponent(src.lastPathComponent))
try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup)
XCTAssertEqual(try Data(contentsOf: dirs.backup.appendingPathComponent(src.lastPathComponent)), try Data(contentsOf: src))
}
func testBackupNameCollisionAllocatesSameNewNameInBothDestinations() async throws {
let dirs = try fixture()
let src = try makePhoto(in: dirs.source)
let unrelated = Data("unrelated backup".utf8)
let existing = dirs.backup.appendingPathComponent(src.lastPathComponent)
try unrelated.write(to: existing)
try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup)
XCTAssertEqual(try Data(contentsOf: existing), unrelated)
for dir in [dirs.primary, dirs.backup] {
XCTAssertEqual(try Data(contentsOf: dir.appendingPathComponent("photo-1.png")), try Data(contentsOf: src))
}
}
func testIncrementalRepairsMissingBackupAndPreservesEditedPrimary() async throws {
let dirs = try fixture()
let src = try makePhoto(in: dirs.source)
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)
let edited = Data("edited primary".utf8)
try edited.write(to: primary)
let complete = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 5)
XCTAssertEqual(complete.skipped, 1)
try FileManager.default.removeItem(at: backup)
_ = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 5)
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))
}
func testIncrementalDoesNotAcceptReplacedBackup() async throws {
let dirs = try fixture()
let src = try makePhoto(in: dirs.source)
let history = dirs.root.appendingPathComponent("history.json")
_ = try await ingest(source: dirs.source, primary: dirs.primary, backup: dirs.backup, history: history, sequence: 4)
let previousBackup = dirs.backup.appendingPathComponent("photo-4.png")
let unrelated = Data(repeating: 1, count: try Data(contentsOf: src).count)
try unrelated.write(to: previousBackup)
_ = 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 {
let png = try XCTUnwrap(Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jP1sAAAAASUVORK5CYII="))
let photo = source.appendingPathComponent("photo.png")
try png.write(to: photo)
return photo
}
@discardableResult
private func ingest(source: URL, primary: URL, backup: URL, history: URL? = nil, sequence: Int? = nil) async throws -> IngestResult {
guard let exe = ExifTool.locate() else { throw XCTSkip("ExifTool fehlt") }
var settings = IngestSettings()
settings.primaryDestination = primary.path
settings.backupDestination = backup.path
settings.secondaryEnabled = true
settings.incremental = history != nil
settings.folderPattern = ""
if let sequence {
settings.startSequence = sequence
settings.renamePattern = "photo-{seqn}"
}
return try await IngestService.run(sources: [source], settings: settings,
exiftool: ExifTool(executable: exe), historyFile: history) { _ in }
}
}
@@ -0,0 +1,10 @@
# Korrekturen aus dem Projekt-Audit
- [x] Kartenimport (Befunde 1, 2, 7). Dateiinhalte an beiden Zielen prüfen, fehlende Kopien vervollständigen, Konflikte umbenennen und Lesefehler melden. Gleich große unterschiedliche Dateien, fehlende Backups und unlesbare Quellen testen.
- [x] Metadaten (Befunde 8, 9). Feld-IDs vor Anzeigenamen auflösen und bei einem reinen Datum die alte IIM-Uhrzeit löschen. Den vorhandenen Importtest und die erzeugten ExifTool-Argumente prüfen.
- [x] Lightroom (Befund 3). JPEG und Originalpfad im Bridge-Ergebnis koppeln. Unklare Zuordnungen älterer Plugins vom automatischen Umschreiben und Versand ausschließen.
- [x] Agentur-Check (Befunde 4, 5). Prüfungen nacheinander anzeigen und die Pixelmaße der tatsächlichen Versanddateien prüfen. Mehrere FTP-Ziele und verkleinerte JPEGs abdecken.
- [x] FTP (Befund 6). Zielnamen über Aufträge hinweg reservieren und belegte Namen auf dem Server als Konflikt behandeln.
- [x] Vollständige Swift-Tests, ARM64-Release-Build und Diff-Prüfung ausführen.
Alle 42 Swift-Tests bestanden. Der ARM64-Release-Build lief mit dem nativen SwiftPM-Buildsystem durch. Lightroom Classic und reale FTP-/SFTP-Server wurden nicht live getestet. Für die Nachbearbeitung und den automatischen Versand wird die Bridge 0.2 benötigt.