Kartenimport, Metadaten und Versand absichern
This commit is contained in:
1 parent
be6bd49da5
commit
427b6fa7b0
18 files changed
+643
-193
No files matched your search
@@ -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()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user