Files
lichtkasten/Sources/LichtkastenCore/Upload/FTPUploader.swift
T

192 lines
8.9 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
public enum FTPProtocol: String, Codable, CaseIterable, Sendable {
case ftp = "FTP"
case ftpsExplicit = "FTPS (explizit, TLS)"
case ftpsImplicit = "FTPS (implizit)"
case sftp = "SFTP"
public var defaultPort: Int {
switch self {
case .ftp, .ftpsExplicit: return 21
case .ftpsImplicit: return 990
case .sftp: return 22
}
}
}
public enum UploadVariant: String, Codable, CaseIterable, Sendable {
case jpeg = "Nur JPEG"
case original = "Original (RAW/JPEG)"
case both = "JPEG + RAW"
}
/// An FTP server profile (PM: "Upload Photos → FTP"). The password lives in the macOS keychain.
public struct FTPDestination: Codable, Identifiable, Hashable, Sendable {
public var id: UUID
public var name: String
public var proto: FTPProtocol
public var host: String
public var port: Int
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.
public var uploadWithTempName: Bool
/// Optional rename pattern with variables, e.g. "{isodate}_{filenamebase}". Empty = keep name.
public var renamePattern: String
public var variant: UploadVariant
/// Path to an SSH private key for SFTP (optional; otherwise ssh-agent / password via curl).
public var sshKeyPath: String
public var allowInsecureTLS: Bool
public init(id: UUID = UUID(), name: String = "Neuer Server", proto: FTPProtocol = .ftp, host: String = "",
port: Int = 21, username: String = "", remoteDirectory: String = "/", passive: Bool = true,
uploadWithTempName: Bool = true, renamePattern: String = "", variant: UploadVariant = .jpeg,
sshKeyPath: String = "", allowInsecureTLS: Bool = false) {
self.id = id; self.name = name; self.proto = proto; self.host = host; self.port = port
self.username = username; self.remoteDirectory = remoteDirectory; self.passive = passive
self.uploadWithTempName = uploadWithTempName; self.renamePattern = renamePattern; self.variant = variant
self.sshKeyPath = sshKeyPath; self.allowInsecureTLS = allowInsecureTLS
}
public var keychainAccount: String { "ftp-\(id.uuidString)" }
}
public enum UploadError: LocalizedError {
case failed(String)
case curlMissingSFTP
public var errorDescription: String? {
switch self {
case .failed(let m): return m
case .curlMissingSFTP:
return "Das System-curl unterstützt kein SFTP. Bitte `brew install curl` ausführen (wird automatisch verwendet)."
}
}
}
/// FTP/FTPS/SFTP upload via curl (ships with macOS; Homebrew curl is preferred when present for SFTP).
public struct FTPUploader: Sendable {
public init() {}
static func curlBinary(needsSFTP: Bool) -> String? {
let candidates = ["/opt/homebrew/opt/curl/bin/curl", "/usr/local/opt/curl/bin/curl", "/usr/bin/curl"]
for c in candidates where FileManager.default.isExecutableFile(atPath: c) {
if !needsSFTP || supportsSFTP(c) { return c }
}
return nil
}
static func supportsSFTP(_ curl: String) -> Bool {
guard let out = try? runSync(curl, ["-V"], stdin: nil).stdout else { return false }
return out.contains(" sftp")
}
/// Escapes a value for curl's config file syntax.
static func configQuote(_ s: String) -> String {
"\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
static func encodePath(_ p: String) -> String {
p.split(separator: "/", omittingEmptySubsequences: true)
.map { String($0).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))) ?? String($0) }
.joined(separator: "/")
}
public func baseURL(_ d: FTPDestination) -> String {
let scheme: String
switch d.proto {
case .ftp, .ftpsExplicit: scheme = "ftp"
case .ftpsImplicit: scheme = "ftps"
case .sftp: scheme = "sftp"
}
var dir = FTPUploader.encodePath(d.remoteDirectory)
if !dir.isEmpty { dir += "/" }
// SFTP paths are absolute from root with "/~/" for home; FTP paths relative to login dir.
let prefix = d.proto == .sftp && !d.remoteDirectory.hasPrefix("/") ? "/~/" : "/"
return "\(scheme)://\(d.host):\(d.port)\(prefix)\(dir)"
}
/// Uploads one file. `remoteName` defaults to the local file name.
public func upload(file: URL, remoteName: String? = nil, to d: FTPDestination, password: String?) 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 ?? "")"))
var args = ["--silent", "--show-error", "--fail", "--ftp-create-dirs", "--retry", "2",
"--connect-timeout", "20", "-K", "-", "-T", file.path, url]
switch d.proto {
case .ftpsExplicit: args.insert("--ssl-reqd", at: 0)
case .sftp:
if !d.sshKeyPath.isEmpty { args.insert(contentsOf: ["--key", (d.sshKeyPath as NSString).expandingTildeInPath], at: 0) }
default: break
}
if d.allowInsecureTLS { args.insert("--insecure", at: 0) }
if !d.passive && d.proto != .sftp { args.insert(contentsOf: ["--ftp-port", "-"], 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)
} else {
args.insert(contentsOf: ["-Q", "-RNFR \(tempName)", "-Q", "-RNTO \(name)"], at: 0)
}
}
let result = try await FTPUploader.run(curl, args, stdin: config.joined(separator: "\n") + "\n")
if result.status != 0 {
throw UploadError.failed("Upload \(name) → \(d.name) fehlgeschlagen: \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))")
}
}
/// 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) }
}
// MARK: Process helpers
struct ProcResult { var status: Int32; var stdout: String; var stderr: String }
static func run(_ exe: String, _ args: [String], stdin: String?) async throws -> ProcResult {
try await withCheckedThrowingContinuation { cont in
DispatchQueue.global(qos: .utility).async {
do { cont.resume(returning: try runSync(exe, args, stdin: stdin)) } catch { cont.resume(throwing: error) }
}
}
}
static func runSync(_ exe: String, _ args: [String], stdin: String?) throws -> ProcResult {
let p = Process()
p.executableURL = URL(fileURLWithPath: exe)
p.arguments = args
let out = Pipe(), err = Pipe(), inp = Pipe()
p.standardOutput = out
p.standardError = err
p.standardInput = inp
try p.run()
if let stdin { inp.fileHandleForWriting.write(Data(stdin.utf8)) }
try? inp.fileHandleForWriting.close()
// Read both pipes concurrently to avoid dead-locks on large output.
var errData = Data()
let g = DispatchGroup()
g.enter()
DispatchQueue.global().async { errData = err.fileHandleForReading.readDataToEndOfFile(); g.leave() }
let outData = out.fileHandleForReading.readDataToEndOfFile()
g.wait()
p.waitUntilExit()
return ProcResult(status: p.terminationStatus, stdout: String(decoding: outData, as: UTF8.self),
stderr: String(decoding: errData, as: UTF8.self))
}
}