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 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 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 /// Agentur-Check before uploading to this server public var preflight: Bool /// PM "Replace existing file on server": a corrected image can be sent again under the same name. /// Off = the upload stops if the name already exists there. public var replaceExisting: 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, preflight: Bool = true, replaceExisting: Bool = true) { 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; self.preflight = preflight self.replaceExisting = replaceExisting } enum CodingKeys: String, CodingKey { case id, name, proto, host, port, username, remoteDirectory, passive, uploadWithTempName, renamePattern, variant, sshKeyPath, allowInsecureTLS, preflight, replaceExisting } /// Tolerant decoding – new options must never wipe the saved server profiles. public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) let d = FTPDestination() func v(_ k: CodingKeys, _ def: T) -> T { (try? c.decode(T.self, forKey: k)) ?? def } id = v(.id, UUID()) name = v(.name, d.name) proto = v(.proto, d.proto) host = v(.host, d.host) port = v(.port, d.port) username = v(.username, d.username) remoteDirectory = v(.remoteDirectory, d.remoteDirectory) passive = v(.passive, d.passive) uploadWithTempName = v(.uploadWithTempName, d.uploadWithTempName) renamePattern = v(.renamePattern, d.renamePattern) variant = v(.variant, d.variant) sshKeyPath = v(.sshKeyPath, d.sshKeyPath) allowInsecureTLS = v(.allowInsecureTLS, d.allowInsecureTLS) preflight = v(.preflight, d.preflight) replaceExisting = v(.replaceExisting, d.replaceExisting) } public var keychainAccount: String { "ftp-\(id.uuidString)" } } 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)." } } } /// FTP/FTPS/SFTP upload via curl (ships with macOS; Homebrew curl is preferred when present for SFTP). public struct FTPUploader: Sendable { 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"] 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 !name.isEmpty, name != ".", name != "..", !name.contains("/"), name.rangeOfCharacter(from: .controlCharacters.union(.newlines)) == nil else { throw UploadError.failed("Ungültiger Dateiname für den Upload.") } 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) { // only list the server folder when existing files must not be replaced (saves a login per file) if !d.replaceExisting { 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 base = sftpPath(d) let source = Self.configQuote(base + tempName), target = Self.configQuote(base + name) args.insert(contentsOf: ["-Q", "-rename \(source) \(target)"], at: 0) // "*" = ignore the error if there is no old file; some servers refuse renaming onto a file if d.replaceExisting { args.insert(contentsOf: ["-Q", "-*rm \(target)"], at: 0) } } else { args.insert(contentsOf: ["-Q", "-RNFR \(tempName)", "-Q", "-RNTO \(name)"], at: 0) if d.replaceExisting { args.insert(contentsOf: ["-Q", "-*DELE \(name)"], at: 0) } } } 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 { 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 = 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 /// 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)) } } 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() } }