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 ".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. /// `progress` receives the bytes sent so far (parsed from curl's progress meter, ~1×/s). 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 } 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.runStreaming(curl, args, stdin: config.joined(separator: "\n") + "\n") { line in if let sent = FTPUploader.uploadedBytes(fromProgressLine: line) { progress?(sent) } } if result.status != 0 { let msg = result.stderr.components(separatedBy: CharacterSet(charactersIn: "\r\n")) .filter { $0.contains("curl:") }.joined(separator: " ") throw UploadError.failed("Upload \(name) → \(d.name) fehlgeschlagen: \(msg.isEmpty ? "curl-Fehler \(result.status)" : msg)") } if let size = (try? FileManager.default.attributesOfItem(atPath: file.path)[.size] as? NSNumber)?.int64Value { progress?(size) } } /// 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 /// Parses curl's progress meter line, e.g. /// " 13 28.6M 0 0 13 3904k 0 8188k 0:00:03 --:--:-- 0:00:03 8184k" → 3904 KiB sent. public static func uploadedBytes(fromProgressLine line: String) -> Int64? { let t = line.split(separator: " ", omittingEmptySubsequences: true) guard t.count >= 12, Int(t[0]) != nil, Int(t[4]) != nil else { return nil } return parseCurlSize(String(t[5])) } static func parseCurlSize(_ s: String) -> Int64? { guard let last = s.last else { return nil } let mult: Double switch last { case "k": mult = 1024 case "M": mult = 1024 * 1024 case "G": mult = 1024 * 1024 * 1024 case "T": mult = 1024 * 1024 * 1024 * 1024 default: return Int64(s) } guard let v = Double(s.dropLast()) else { return nil } return Int64(v * mult) } /// Like `run`, but hands every stderr line (split at \r and \n) to `onLine` while the process runs. static func runStreaming(_ exe: String, _ args: [String], stdin: String?, onLine: @escaping @Sendable (String) -> Void) async throws -> ProcResult { try await withCheckedThrowingContinuation { cont in DispatchQueue.global(qos: .utility).async { do { 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 final class Buf: @unchecked Sendable { var all = Data(); var pending = ""; let lock = NSLock() } let buf = Buf() err.fileHandleForReading.readabilityHandler = { h in let d = h.availableData guard !d.isEmpty else { return } buf.lock.lock() buf.all.append(d) buf.pending += String(decoding: d, as: UTF8.self) var parts = buf.pending.components(separatedBy: CharacterSet(charactersIn: "\r\n")) buf.pending = parts.removeLast() buf.lock.unlock() for line in parts where !line.isEmpty { onLine(line) } } try p.run() if let stdin { inp.fileHandleForWriting.write(Data(stdin.utf8)) } try? inp.fileHandleForWriting.close() _ = out.fileHandleForReading.readDataToEndOfFile() p.waitUntilExit() err.fileHandleForReading.readabilityHandler = nil let rest = err.fileHandleForReading.readDataToEndOfFile() buf.lock.lock(); buf.all.append(rest); let all = buf.all; buf.lock.unlock() cont.resume(returning: ProcResult(status: p.terminationStatus, stdout: "", stderr: String(decoding: all, as: UTF8.self))) } catch { cont.resume(throwing: error) } } } } 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. final class Box: @unchecked Sendable { var data = Data() } let errBox = Box() let errHandle = err.fileHandleForReading let g = DispatchGroup() g.enter() DispatchQueue.global().async { errBox.data = errHandle.readDataToEndOfFile(); g.leave() } let outData = out.fileHandleForReading.readDataToEndOfFile() g.wait() let errData = errBox.data p.waitUntilExit() return ProcResult(status: p.terminationStatus, stdout: String(decoding: outData, as: UTF8.self), stderr: String(decoding: errData, as: UTF8.self)) } }