diff --git a/LightroomPlugin/LichtkastenBridge.lrplugin/Bridge.lua b/LightroomPlugin/LichtkastenBridge.lrplugin/Bridge.lua index 3eadb7b..9af954c 100644 --- a/LightroomPlugin/LichtkastenBridge.lrplugin/Bridge.lua +++ b/LightroomPlugin/LichtkastenBridge.lrplugin/Bridge.lua @@ -80,7 +80,10 @@ local function writeResult(job, status, imported, exported, errors) f:write('id=' .. job.id .. '\n') f:write('status=' .. status .. '\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 f:close() 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 local ok, pathOrMessage = rendition:waitForRender() if ok then - table.insert(exported, pathOrMessage) + table.insert(exported, { path = pathOrMessage, source = rendition.photo:getRawMetadata("path") }) else table.insert(errors, 'Export: ' .. tostring(pathOrMessage)) end diff --git a/LightroomPlugin/LichtkastenBridge.lrplugin/Info.lua b/LightroomPlugin/LichtkastenBridge.lrplugin/Info.lua index 49038d6..cd26a6e 100644 --- a/LightroomPlugin/LichtkastenBridge.lrplugin/Info.lua +++ b/LightroomPlugin/LichtkastenBridge.lrplugin/Info.lua @@ -15,5 +15,5 @@ return { LrLibraryMenuItems = { { 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 }, } diff --git a/README.md b/README.md index b7f3d8d..f5846fd 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ Metadaten werden mit mehreren exiftool-Prozessen parallel gelesen und pro Ordner `LightroomPlugin/LichtkastenBridge.lrplugin` ist ein kleines Lightroom-Classic-Plugin. Installation: Einstellungen → Lightroom → **Plugin installieren**, danach Lightroom neu starten. 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 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 „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. -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 diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift index 65d435e..418f93d 100644 --- a/Sources/Lichtkasten/Services/AppState.swift +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -70,6 +70,8 @@ struct PendingUpload: Identifiable { let id = UUID() let target: String let targetName: String + var variant: UploadVariant + let skipAlreadySent: Bool var items: [PhotoItem] /// item id → issues var issues: [String: [PreflightIssue]] @@ -203,7 +205,8 @@ final class AppState: ObservableObject { @Published private(set) var sentLog = SentLog() private var sentLogSaveTask: Task? /// 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 @Published private(set) var undoStack: [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" 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. - private func handleExported(_ files: [URL], job: LightroomJob, sources jobSources: [PhotoItem]) async { - // Map exported JPEG → source item by base name (LR keeps the file name, may append "-2"). - // Current state if the photo is still open (IPTC edited meanwhile), else the copy from the job. - let sources = jobSources.map { item($0.id) ?? $0 } - if job.rewriteIPTCAfterExport, let w = writer { - for file in files { - let base = file.deletingPathExtension().lastPathComponent - guard let src = sources.first(where: { base == $0.baseName || base.hasPrefix($0.baseName + "-") }) else { continue } - let jpegItem = PhotoItem(primary: file) - do { try await w.write(values: src.iptc, fields: IPTCField.all, to: jpegItem) } catch { report(error) } + private func handleExported(_ result: LightroomJobResult, job: LightroomJob, sources jobSources: [PhotoItem]) async { + let sources = Dictionary(jobSources.map { original in + let path = (original.rawFile ?? original.primary).standardizedFileURL.path + return (path, item(original.id) ?? original) + }, uniquingKeysWith: { first, _ in first }) + let writer = job.rewriteIPTCAfterExport ? self.writer : nil + var exportedItems: [PhotoItem] = [] + var missingSources = 0 + for file in result.exported { + 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.iptc = source.iptc + exported.exif = source.exif + exported.captureDate = source.captureDate + exportedItems.append(exported) } - // Exported JPEGs carry the IPTC of their RAW (needed for {event} album names, rename patterns …) - let exportedItems: [PhotoItem] = files.compactMap { file in - let base = file.deletingPathExtension().lastPathComponent - guard let src = sources.first(where: { base == $0.baseName || base.hasPrefix($0.baseName + "-") }) else { return nil } - var it = PhotoItem(primary: file) - it.iptc = src.iptc; it.exif = src.exif; it.captureDate = src.captureDate - return it + if missingSources > 0 && (job.rewriteIPTCAfterExport || !job.uploadTargets.isEmpty) { + 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 { 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. if settings.lightroom.openSentAfterExport, let dir = job.exportFolder { if folder != dir { lastRawFolder = folder; open(folder: dir) } else { refreshFolder() } @@ -1175,7 +1190,7 @@ final class AppState: ObservableObject { var issues: [String: [PreflightIssue]] = [:] if runCheck { for t in withFiles { - let i = preflightIssues(for: t) + let i = preflightIssues(for: t, variant: variant) if !i.isEmpty { issues[t.id] = i } } } @@ -1186,41 +1201,52 @@ final class AppState: ObservableObject { enqueueUpload(send, target: target, variant: variant) 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") } /// 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 open = openSuggestions(for: cur.id).map { s -> String in let name = s.replacement.map { JerseyLogic.personName(replacement: $0, columns: []) } ?? "" 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, - 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). 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 } var issues: [String: [PreflightIssue]] = [:] let destination = settings.ftpDestinations.first { $0.id.uuidString == p.target } 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.alreadySent = Set(p.items.filter { sentLog.wasSent($0, to: p.target) }.map(\.id)) - pendingUpload = p + pendingUploads[0] = p } /// Check window: send these photos. func confirmPendingUpload(_ send: [PhotoItem]) { - guard let p = pendingUpload, let variant = uploadVariant(p.target) else { pendingUpload = nil; return } - pendingUpload = nil + guard let p = pendingUpload else { return } + guard let variant = uploadVariant(p.target) else { discardPendingUpload(); return } + guard p.variant == variant else { recheckPendingUpload(); return } + discardPendingUpload() 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) { diff --git a/Sources/Lichtkasten/Services/UploadQueue.swift b/Sources/Lichtkasten/Services/UploadQueue.swift index cbaae24..e25930e 100644 --- a/Sources/Lichtkasten/Services/UploadQueue.swift +++ b/Sources/Lichtkasten/Services/UploadQueue.swift @@ -111,18 +111,25 @@ final class UploadQueue: ObservableObject { guard let state, !files.isEmpty else { return } let name: String var pattern = "" + var usedNames = Set() if target == "immich" { name = "Immich" } else if let d = state.settings.ftpDestinations.first(where: { $0.id.uuidString == target }) { name = d.name 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 } var batchRef: UUID? let batch = state.tasks.start(.upload, title: "Upload → \(name)", total: files.count) { [weak self] in if let b = batchRef { self?.cancelBatch(b) } } batchRef = batch - var usedNames = Set() for f in files { let src = sourceItems.first { $0.primary == f || $0.companions.contains(f) } var remote = f.lastPathComponent @@ -228,6 +235,8 @@ final class UploadQueue: ObservableObject { remoteName: job.remoteName, size: job.fileSize) setStatus(job.id, .done) } + } catch UploadError.remoteNameConflict(let name) { + setStatus(job.id, .failed(UploadError.remoteNameConflict(name).localizedDescription)) } catch { if let i = jobs.firstIndex(where: { $0.id == job.id }), jobs[i].attempts < 3 { jobs[i].status = .waiting diff --git a/Sources/Lichtkasten/Views/PreflightWindow.swift b/Sources/Lichtkasten/Views/PreflightWindow.swift index 4bc0bd7..aea76a3 100644 --- a/Sources/Lichtkasten/Views/PreflightWindow.swift +++ b/Sources/Lichtkasten/Views/PreflightWindow.swift @@ -22,6 +22,10 @@ struct PreflightWindow: View { .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) .background(LK.ground) } @@ -94,8 +98,8 @@ struct PreflightWindow: View { Rectangle().fill(LK.border).frame(height: 1) HStack(spacing: 10) { Button("Abbrechen") { - state.pendingUpload = nil - dismissWindow(id: "check") + state.discardPendingUpload() + if state.pendingUpload == nil { dismissWindow(id: "check") } } .buttonStyle(LKButtonStyle()) .keyboardShortcut(.cancelAction) @@ -125,8 +129,10 @@ struct PreflightWindow: View { private func send(_ items: [PhotoItem]) { state.confirmPendingUpload(items) - state.openWindow("tasks") - dismissWindow(id: "check") + if state.pendingUpload == nil { + state.openWindow("tasks") + dismissWindow(id: "check") + } } // MARK: Row per photo diff --git a/Sources/LichtkastenCore/Ingest/IngestService.swift b/Sources/LichtkastenCore/Ingest/IngestService.swift index ee93d08..118d88f 100644 --- a/Sources/LichtkastenCore/Ingest/IngestService.swift +++ b/Sources/LichtkastenCore/Ingest/IngestService.swift @@ -1,3 +1,4 @@ +import CryptoKit import Foundation /// 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] .appendingPathComponent("Lichtkasten", isDirectory: 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). - 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 HistoryKey: Codable { + let destinations: [URL] + let folderPattern: String + let preserveStructure: Bool + let sourceFolder: String + let renamePattern: String? + let files: [String] } - static func loadHistory() -> Set { - guard let d = try? Data(contentsOf: historyURL), let s = try? JSONDecoder().decode(Set.self, from: d) else { return [] } - return s + private struct ImportedGroup: Codable { + let folders: [URL] + let name: String } - static func saveHistory(_ s: Set) { - if let d = try? JSONEncoder().encode(s) { try? d.write(to: historyURL, options: .atomic) } + 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) } /// 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, onSequence: (@Sendable (Int) -> Void)? = nil, 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 guard !settings.primaryDestination.isEmpty else { throw UploadError.failed("Kein Ziel für den Ingest gewählt.") } - // 1. scan + filters - var entries: [(item: PhotoItem, root: URL, locked: Bool)] = [] - for s in sources { - let ro = volumeIsReadOnly(s) - for item in try FolderScanner.scan(folder: s, recursive: true) { - entries.append((item, s, isLocked(item.primary, volumeReadOnly: ro))) - } + let destRoots = ([settings.primaryDestination] + + (settings.secondaryEnabled && !settings.backupDestination.isEmpty ? [settings.backupDestination] : [])) + .map { URL(fileURLWithPath: $0, isDirectory: true).resolvingSymlinksInPath().standardizedFileURL } + guard Set(destRoots).count == destRoots.count else { + throw UploadError.failed("Hauptziel und Backup-Ziel müssen verschieden sein.") } - entries = entries.filter { e in - switch settings.lockedFilter { - case .all: break - case .lockedOnly: if !e.locked { return false } - case .unlockedOnly: if e.locked { return false } - } - return true - } - var history = settings.incremental ? loadHistory() : [] + + // A history entry proves which full group was copied to these destinations. + var history = historyFile.map { loadHistory(at: $0) } ?? [:] + var historyChanged = false var skipped = 0 - if settings.incremental { - let before = entries.count - entries = entries.filter { !history.contains(historyKey($0.item.primary)) } - skipped = before - entries.count + 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 …")) + 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 …")) @@ -186,90 +248,89 @@ public enum IngestService { var copied: [URL] = [] var lockedCopies: [URL] = [] var seq = settings.startSequence - let total = entries.reduce(0) { total, e in - let n = 1 + e.item.companions.count - return total + n - } + let total = entries.reduce(0) { $0 + $1.files.filter { $0.pathExtension.lowercased() != "xmp" }.count } var done = 0 - let destRoots = [settings.primaryDestination] + (settings.secondaryEnabled && !settings.backupDestination.isEmpty ? [settings.backupDestination] : []) progress(IngestProgress(done: 0, total: total, currentFile: "Starte …")) - // also after a cancel/error: what was copied is not copied again next time - // also after a cancel/error the next number is handed back, so the next ingest continues there defer { - if settings.incremental { saveHistory(history) } + if historyChanged, let historyFile { try? saveHistory(history, at: historyFile) } if settings.sequenceEnabled { onSequence?(seq) } } - for e in entries { + for entry in entries { try Task.checkCancellation() - let item = e.item - let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, sequence: settings.sequenceEnabled ? seq : nil, iptc: item.iptc) + let item = entry.item + 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) .replacingOccurrences(of: ":", with: "-") .trimmingCharacters(in: .whitespaces) - var baseName = item.baseName - if settings.renameEnabled, !settings.renamePattern.isEmpty { - baseName = VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-") - } - // Card structure (DCIM/100NZ8_1) below the destination if requested - 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) + let baseName = settings.renameEnabled && !settings.renamePattern.isEmpty + ? VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-") + : item.baseName + let folders = destRoots.map { root in + var folder = root if !sub.isEmpty { folder.appendPathComponent(sub, isDirectory: true) } - if !rel.isEmpty { folder.appendPathComponent(rel, isDirectory: true) } - try fm.createDirectory(at: folder, withIntermediateDirectories: true) - let isPrimary = destRoot == settings.primaryDestination - if isPrimary, usedFolders.insert(folder).inserted { onFolder?(folder) } - for (n, src) in files.enumerated() { - let dest = folder.appendingPathComponent(targetName).appendingPathExtension(src.pathExtension) - if skipGroup || fm.fileExists(atPath: dest.path) { - // already there (duplicate, or the backup already has it) – never overwrite - if isPrimary, n == 0, src.pathExtension.lowercased() != "xmp" { done += 1 } - continue - } - try copy(src, to: dest) - if isPrimary { - if n == 0 { - copied.append(dest) - if e.locked { lockedCopies.append(dest) } + 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) + if folderIndex == 0, usedFolders.insert(folder).inserted { onFolder?(folder) } + for (fileIndex, src) in entry.files.enumerated() { + 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) { + throw UploadError.failed("Die Zieldatei wurde zwischenzeitlich geändert: \(dest.path)") + } + 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) + newCopies.append(dest) + if folderIndex == 0 && fileIndex == 0 { newPrimary = dest } } - if src.pathExtension.lowercased() != "xmp" { + if folderIndex == 0 && src.pathExtension.lowercased() != "xmp" { done += 1 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, lockedCopies: lockedCopies, nextSequence: seq, skipped: skipped) @@ -291,27 +352,49 @@ public enum IngestService { return last.isEmpty ? "diskutil eject fehlgeschlagen" : last } - /// Base name that collides with no other photo in `folder`. If the photo itself is already there - /// (same name and size of its main file) and duplicates are skipped, `skip` is true. + /// A shared name across destinations that either has no collision or can resume a partial copy. static func uniqueName(_ base: String, files: [URL], in folder: URL, skipDuplicates: Bool) -> (name: String, skip: Bool) { - let fm = FileManager.default - func dest(_ name: String, _ src: URL) -> URL { folder.appendingPathComponent(name).appendingPathExtension(src.pathExtension) } - if let main = files.first, fm.fileExists(atPath: dest(base, main).path) { - if skipDuplicates, sameSize(main, dest(base, main)) { return (base, true) } - } else if !files.contains(where: { fm.fileExists(atPath: dest(base, $0).path) }) { - return (base, false) - } - var n = 1 - while files.contains(where: { fm.fileExists(atPath: dest("\(base)-\(n)", $0).path) }) { n += 1 } - return ("\(base)-\(n)", false) + uniqueName(base, files: files, in: [folder], skipDuplicates: skipDuplicates) } - static func sameSize(_ a: URL, _ b: URL) -> Bool { - func size(_ u: URL) -> Int64? { - guard let attrs = try? FileManager.default.attributesOfItem(atPath: u.path) else { return nil } - return (attrs[.size] as? NSNumber)?.int64Value + private static func uniqueName(_ base: String, files: [URL], in folders: [URL], skipDuplicates: Bool) -> (name: String, skip: Bool) { + let fm = FileManager.default + var suffix = 0 + 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 + } + } + if conflict { break } + } + if !conflict { return (name, !missing) } + suffix += 1 } - let sa = size(a) - return sa != nil && sa == size(b) + } + + 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) } } diff --git a/Sources/LichtkastenCore/Library/PhotoItem.swift b/Sources/LichtkastenCore/Library/PhotoItem.swift index 9d6f893..c4178d8 100644 --- a/Sources/LichtkastenCore/Library/PhotoItem.swift +++ b/Sources/LichtkastenCore/Library/PhotoItem.swift @@ -203,13 +203,24 @@ public enum FolderScanner { let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey, .isHiddenKey] var urls: [URL] = [] if recursive { - if let e = fm.enumerator(at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles, .skipsPackageDescendants]) { - for case let u as URL in e { urls.append(u) } + var scanError: Error? + 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 { 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 var groups: [String: [URL]] = [:] diff --git a/Sources/LichtkastenCore/Lightroom/LightroomBridge.swift b/Sources/LichtkastenCore/Lightroom/LightroomBridge.swift index 32a7594..d3c08be 100644 --- a/Sources/LichtkastenCore/Lightroom/LightroomBridge.swift +++ b/Sources/LichtkastenCore/Lightroom/LightroomBridge.swift @@ -49,9 +49,11 @@ public struct LightroomJobResult: Sendable { public var imported: Int public var exported: [URL] public var errors: [String] + public private(set) var exportSources: [URL: URL] = [:] public static func parse(_ text: String) -> LightroomJobResult { var r = LightroomJobResult(id: "", ok: false, imported: 0, exported: [], errors: []) + var lastExport: URL? for line in text.components(separatedBy: .newlines) { guard let eq = line.firstIndex(of: "=") else { continue } let k = String(line[...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 /// Optional rename pattern with variables, e.g. "{isodate}_{filenamebase}". Empty = keep name. public var renamePattern: String @@ -83,11 +83,13 @@ public struct FTPDestination: Codable, Identifiable, Hashable, Sendable { public enum UploadError: LocalizedError { case failed(String) + case remoteNameConflict(String) case curlMissingSFTP public var errorDescription: String? { switch self { case .failed(let m): return m + case .remoteNameConflict(let name): return "Der Zielname „\(name)“ ist bereits belegt." case .curlMissingSFTP: 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). 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? { 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?, progress: (@Sendable (Int64) -> Void)? = nil) async throws { let name = remoteName ?? file.lastPathComponent - guard let curl = FTPUploader.curlBinary(needsSFTP: d.proto == .sftp) else { throw UploadError.curlMissingSFTP } - let tempName = d.uploadWithTempName ? name + ".part" : name - let url = baseURL(d) + FTPUploader.encodePath(tempName) - - 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 + guard !name.isEmpty, name != ".", name != "..", + !name.contains("/"), name.rangeOfCharacter(from: .controlCharacters.union(.newlines)) == nil else { + throw UploadError.failed("Ungültiger Dateiname für den Upload.") } - if d.allowInsecureTLS { args.insert("--insecure", at: 0) } - if !d.passive && d.proto != .sftp { args.insert(contentsOf: ["--ftp-port", "-"], at: 0) } + guard let curl = curlExecutable ?? FTPUploader.curlBinary(needsSFTP: d.proto == .sftp) else { + 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.proto == .sftp { - let dir = d.remoteDirectory.hasPrefix("/") ? d.remoteDirectory : "~/" + d.remoteDirectory - let base = dir.hasSuffix("/") ? dir : dir + "/" - args.insert(contentsOf: ["-Q", "-rename \"\(base)\(tempName)\" \"\(base)\(name)\""], at: 0) + let base = sftpPath(d) + let source = Self.configQuote(base + tempName), target = Self.configQuote(base + name) + args.insert(contentsOf: ["-Q", "-rename \(source) \(target)"], at: 0) } else { 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 result.status != 0 { @@ -182,14 +196,63 @@ public struct FTPUploader: Sendable { /// Checks login + directory listing. public func testConnection(_ d: FTPDestination, password: String?) async throws { - guard let curl = FTPUploader.curlBinary(needsSFTP: d.proto == .sftp) else { throw UploadError.curlMissingSFTP } - var args = ["--silent", "--show-error", "--fail", "--connect-timeout", "15", "-K", "-", "--list-only", baseURL(d)] - if d.proto == .ftpsExplicit { args.insert("--ssl-reqd", at: 0) } - if d.allowInsecureTLS { args.insert("--insecure", at: 0) } - 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) - if r.status != 0 { throw UploadError.failed(r.stderr.isEmpty ? "Verbindung fehlgeschlagen (curl \(r.status))" : r.stderr) } + guard let curl = curlExecutable ?? Self.curlBinary(needsSFTP: d.proto == .sftp) else { + throw UploadError.curlMissingSFTP + } + _ = try await listNames(d, curl: curl, password: password, createDirectories: false) + } + + private func listNames(_ d: FTPDestination, curl: String, password: String?, + createDirectories: Bool) async throws -> Set { + 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[.. 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 @@ -293,3 +356,14 @@ public struct FTPUploader: Sendable { stderr: String(decoding: errData, as: UTF8.self)) } } + + +private actor RemoteNameReservations { + private var active = Set() + + 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() + } +} diff --git a/Sources/LichtkastenCore/Upload/Preflight.swift b/Sources/LichtkastenCore/Upload/Preflight.swift index b9d95f8..e83bc06 100644 --- a/Sources/LichtkastenCore/Upload/Preflight.swift +++ b/Sources/LichtkastenCore/Upload/Preflight.swift @@ -1,4 +1,5 @@ import Foundation +import ImageIO /// Agentur-Check: what is checked before photos go to an agency server. public struct PreflightOptions: Codable, Hashable, Sendable { @@ -52,9 +53,25 @@ public struct PreflightIssue: Hashable, Identifiable, Sendable { } 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. 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] = [] // 1. required fields @@ -134,7 +151,9 @@ public enum Preflight { } // 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) }), max(w, h) < options.minLongEdge { issues.append(PreflightIssue(.error, "Bild zu klein: \(max(w, h)) px lange Kante (mindestens \(options.minLongEdge) px)")) diff --git a/Tests/LichtkastenCoreTests/CoreTests.swift b/Tests/LichtkastenCoreTests/CoreTests.swift index 5fd8a94..ea910ba 100644 --- a/Tests/LichtkastenCoreTests/CoreTests.swift +++ b/Tests/LichtkastenCoreTests/CoreTests.swift @@ -413,6 +413,11 @@ final class BugfixTests: XCTestCase { XCTAssertTrue(lib.sets.first?.enabled ?? false) } + func testDateOnlyUpdateClearsIIMTimeCreated() { + let arguments = MetadataWriter.dateArguments("2026-11-03", writeIIM: true) + XCTAssertTrue(arguments.contains("-IPTC:TimeCreated=")) + } + func testDateCreatedKeepsTimeOfDay() { var item = PhotoItem(primary: URL(fileURLWithPath: "/x/a.jpg")) item.apply(fileMeta: ["XMP-photoshop:DateCreated": .string("2026:11:02 18:31:05+01:00")], sidecarMeta: nil) diff --git a/Tests/LichtkastenCoreTests/DeliveryTests.swift b/Tests/LichtkastenCoreTests/DeliveryTests.swift new file mode 100644 index 0000000..cfdaa34 --- /dev/null +++ b/Tests/LichtkastenCoreTests/DeliveryTests.swift @@ -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")]) + } +} diff --git a/Tests/LichtkastenCoreTests/FTPUploaderTests.swift b/Tests/LichtkastenCoreTests/FTPUploaderTests.swift new file mode 100644 index 0000000..907ac6d --- /dev/null +++ b/Tests/LichtkastenCoreTests/FTPUploaderTests.swift @@ -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)) + } +} diff --git a/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift b/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift new file mode 100644 index 0000000..c89f5d4 --- /dev/null +++ b/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift @@ -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 } + } +} diff --git a/docs/superpowers/plans/2026-11-05-audit-korrekturen.md b/docs/superpowers/plans/2026-11-05-audit-korrekturen.md new file mode 100644 index 0000000..8d2c6a4 --- /dev/null +++ b/docs/superpowers/plans/2026-11-05-audit-korrekturen.md @@ -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.