Live-Upload-Rate (MB/s, Mbit/s, Restzeit) für FTP (curl-Fortschritt) und Immich, Fortschritt pro Datei
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
This commit is contained in:
1 parent
2bf0d851aa
commit
5505fa1f37
5 files changed
+198
-12
No files matched your search
@@ -109,7 +109,9 @@ public struct FTPUploader: Sendable {
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// `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
|
||||
@@ -117,7 +119,8 @@ public struct FTPUploader: Sendable {
|
||||
|
||||
var config: [String] = []
|
||||
config.append("user = " + FTPUploader.configQuote("\(d.username):\(password ?? "")"))
|
||||
var args = ["--silent", "--show-error", "--fail", "--ftp-create-dirs", "--retry", "2",
|
||||
// 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)
|
||||
@@ -136,9 +139,16 @@ public struct FTPUploader: Sendable {
|
||||
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")
|
||||
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 {
|
||||
throw UploadError.failed("Upload \(name) → \(d.name) fehlgeschlagen: \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))")
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +166,69 @@ public struct FTPUploader: Sendable {
|
||||
|
||||
// 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 {
|
||||
|
||||
Reference in new issue
Block a user