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
+643 -193

No files matched your search

+199 -116
View File
@@ -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<String> {
guard let d = try? Data(contentsOf: historyURL), let s = try? JSONDecoder().decode(Set<String>.self, from: d) else { return [] }
return s
private struct ImportedGroup: Codable {
let folders: [URL]
let name: String
}
static func saveHistory(_ s: Set<String>) {
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)
}
}
@@ -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]] = [:]
@@ -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[..<eq]), v = String(line[line.index(after: eq)...])
@@ -59,7 +61,13 @@ public struct LightroomJobResult: Sendable {
case "id": r.id = v
case "status": r.ok = v == "done"
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)
default: break
}
@@ -111,7 +111,7 @@ public struct MetadataWriter: Sendable {
var args = ["-XMP-photoshop:DateCreated=\(datePart)\(timePart.isEmpty ? "" : " " + timePart)"]
if writeIIM {
args.append("-IPTC:DateCreated=\(datePart)")
if !timePart.isEmpty { args.append("-IPTC:TimeCreated=\(timePart)") }
args.append("-IPTC:TimeCreated=\(timePart)")
}
return args
}
@@ -127,6 +127,7 @@ public enum PMSettingsImporter {
let n = raw.lowercased().replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "_", with: "")
.replacingOccurrences(of: "-", with: "").replacingOccurrences(of: "/", with: "")
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",
"byline": "creator", "photographer": "creator", "sublocation": "sublocation",
"location": "sublocation", "provincestate": "state", "stateprovince": "state",
@@ -137,7 +138,7 @@ public enum PMSettingsImporter {
return IPTCField.all.first { f in
let pm = f.pmLabel.lowercased().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)
}
}
+104 -30
View File
@@ -31,7 +31,7 @@ public struct FTPDestination: Codable, Identifiable, Hashable, Sendable {
public var username: String
public var remoteDirectory: String
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
/// 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<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
@@ -293,3 +356,14 @@ public struct FTPUploader: Sendable {
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 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)"))