From 5505fa1f37c5b3953c044a81d70d3ffff84f139e Mon Sep 17 00:00:00 2001 From: Lichtkasten Dev Date: Wed, 4 Nov 2026 01:00:35 +0000 Subject: [PATCH] =?UTF-8?q?Live-Upload-Rate=20(MB/s,=20Mbit/s,=20Restzeit)?= =?UTF-8?q?=20f=C3=BCr=20FTP=20(curl-Fortschritt)=20und=20Immich,=20Fortsc?= =?UTF-8?q?hritt=20pro=20Datei?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D --- .../Lichtkasten/Services/UploadQueue.swift | 81 ++++++++++++++++++- Sources/Lichtkasten/Views/ContentView.swift | 14 +++- Sources/Lichtkasten/Views/TasksWindow.swift | 13 +++ .../LichtkastenCore/Upload/FTPUploader.swift | 81 ++++++++++++++++++- .../LichtkastenCore/Upload/ImmichClient.swift | 21 +++-- 5 files changed, 198 insertions(+), 12 deletions(-) diff --git a/Sources/Lichtkasten/Services/UploadQueue.swift b/Sources/Lichtkasten/Services/UploadQueue.swift index 74a1db5..ac597ad 100644 --- a/Sources/Lichtkasten/Services/UploadQueue.swift +++ b/Sources/Lichtkasten/Services/UploadQueue.swift @@ -15,6 +15,9 @@ struct UploadJob: Identifiable { var status: Status = .waiting var attempts = 0 var batch: UUID? + var fileSize: Int64 = 0 + var sent: Int64 = 0 + var progress: Double { fileSize > 0 ? min(1, Double(sent) / Double(fileSize)) : 0 } var isFinished: Bool { switch status { @@ -36,6 +39,67 @@ final class UploadQueue: ObservableObject { /// album name → new asset ids private var immichNewAssets: [String: [String]] = [:] + // MARK: Live rate + /// Smoothed upload rate in bytes/s while transfers are running (0 when idle). + @Published private(set) var rate: Double = 0 + /// Bytes sent / total of all unfinished jobs (for ETA). + @Published private(set) var remainingBytes: Int64 = 0 + private var sentCounter: Int64 = 0 // cumulative bytes of this session + private var lastSample: (time: Date, bytes: Int64)? + private var rateTimer: Timer? + + var rateText: String { + guard rate > 0 else { return "" } + let r = ByteCountFormatter.string(fromByteCount: Int64(rate), countStyle: .file) + "/s" + let mbit = String(format: "%.1f Mbit/s", rate * 8 / 1_000_000) + guard remainingBytes > 0 else { return "\(r) (\(mbit))" } + let secs = Int(Double(remainingBytes) / rate) + let eta = secs >= 3600 ? String(format: "%d:%02d:%02d", secs / 3600, secs % 3600 / 60, secs % 60) + : String(format: "%d:%02d", secs / 60, secs % 60) + return "\(r) (\(mbit)) · noch \(eta)" + } + + private func reportSent(_ jobID: UUID, _ bytes: Int64) { + guard let i = jobs.firstIndex(where: { $0.id == jobID }) else { return } + let delta = bytes - jobs[i].sent + guard delta > 0 else { return } + jobs[i].sent = bytes + sentCounter += delta + } + + private func startRateTimer() { + guard rateTimer == nil else { return } + lastSample = (Date(), sentCounter) + rateTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in + Task { @MainActor in self?.sampleRate() } + } + } + + private func sampleRate() { + let now = Date() + if let last = lastSample { + let dt = now.timeIntervalSince(last.time) + if dt > 0 { + let instant = Double(sentCounter - last.bytes) / dt + rate = rate == 0 ? instant : rate * 0.6 + instant * 0.4 // smoothing + } + } + lastSample = (now, sentCounter) + remainingBytes = jobs.filter { !$0.isFinished }.reduce(0) { $0 + max(0, $1.fileSize - $1.sent) } + // live detail in the task rows + if let state { + for batch in Set(jobs.filter { $0.status == .running }.compactMap(\.batch)) { + let inBatch = jobs.filter { $0.batch == batch } + let done = inBatch.filter(\.isFinished).count + state.tasks.update(batch, done: done, detail: "\(rateText) · \(done)/\(inBatch.count)") + } + } + if running == 0 && jobs.allSatisfy({ $0.status != .waiting }) { + rateTimer?.invalidate(); rateTimer = nil + rate = 0; remainingBytes = 0; lastSample = nil + } + } + /// Removes waiting jobs of a batch (running transfers finish). func cancelBatch(_ id: UUID?) { jobs.removeAll { $0.status == .waiting && (id == nil || $0.batch == id) } @@ -70,6 +134,7 @@ final class UploadQueue: ObservableObject { } var job = UploadJob(file: f, target: target, targetName: name, remoteName: remote, captureDate: src?.captureDate) job.batch = batch + job.fileSize = ((try? FileManager.default.attributesOfItem(atPath: f.path)[.size]) as? NSNumber)?.int64Value ?? 0 if target == "immich" { job.album = state.immichAlbum(for: src ?? state.item(f.path) ?? PhotoItem(primary: f)) } @@ -115,10 +180,22 @@ final class UploadQueue: ObservableObject { private func run(_ job: UploadJob) async { defer { running -= 1; pump() } guard let state else { return } + startRateTimer() + let jobID = job.id + // progress callbacks arrive on background threads → hop to the main actor + let onSent: @Sendable (Int64) -> Void = { [weak self] bytes in + Task { @MainActor in self?.reportSent(jobID, bytes) } + } + if let i = jobs.firstIndex(where: { $0.id == jobID }) { // retry: restart counting this file + let previous = jobs[i].sent + sentCounter -= previous + if let l = lastSample { lastSample = (l.time, l.bytes - previous) } + jobs[i].sent = 0 + } do { if job.target == "immich" { let client = try immich(state) - let r = try await client.upload(file: job.file, captureDate: job.captureDate) + let r = try await client.upload(file: job.file, captureDate: job.captureDate, progress: onSent) // Duplicates are added to the album too (e.g. re-upload after captioning). if !job.album.isEmpty { immichNewAssets[job.album, default: []].append(r.assetId) } setStatus(job.id, r.duplicate ? .duplicate : .done) @@ -127,7 +204,7 @@ final class UploadQueue: ObservableObject { setStatus(job.id, .failed("Server-Profil gelöscht")); return } try await FTPUploader().upload(file: job.file, remoteName: job.remoteName, to: d, - password: Keychain.get(d.keychainAccount)) + password: Keychain.get(d.keychainAccount), progress: onSent) setStatus(job.id, .done) } } catch { diff --git a/Sources/Lichtkasten/Views/ContentView.swift b/Sources/Lichtkasten/Views/ContentView.swift index e292cc1..d82a5b8 100644 --- a/Sources/Lichtkasten/Views/ContentView.swift +++ b/Sources/Lichtkasten/Views/ContentView.swift @@ -98,7 +98,9 @@ struct MainToolbar: ToolbarContent { } .help("In Lightroom Classic bearbeiten (⌘E)") Button { state.openWindow("upload") } label: { - Label(uploads.activeCount > 0 ? "Upload (\(uploads.activeCount))" : "Upload", systemImage: "icloud.and.arrow.up") + Label(uploads.activeCount > 0 + ? (uploads.rate > 0 ? "\(ByteCountFormatter.string(fromByteCount: Int64(uploads.rate), countStyle: .file))/s" : "Upload (\(uploads.activeCount))") + : "Upload", systemImage: "icloud.and.arrow.up") } .help("Upload-Fenster (⌘U)") Button { state.openWindow("tasks") } label: { @@ -247,6 +249,13 @@ struct PMStatusBar: View { Text(summary).lineLimit(1).truncationMode(.middle) Spacer() if state.lrPendingCount > 0 { Label("LR: \(state.lrPendingCount)", systemImage: "hourglass") } + if uploads.activeCount > 0 { + Label(uploads.rate > 0 ? "\(uploads.activeCount) Upload(s) · \(uploads.rateText)" : "\(uploads.activeCount) Upload(s) …", + systemImage: "arrow.up.circle.fill") + .foregroundStyle(Color.accentColor) + .monospacedDigit() + .onTapGesture { state.openWindow("tasks") } + } if uploads.failedCount > 0 { Label("\(uploads.failedCount) Upload(s) fehlgeschlagen", systemImage: "exclamationmark.triangle.fill") .foregroundStyle(.red) @@ -377,6 +386,9 @@ struct MiniTaskRow: View { } if task.isRunning { if task.total > 0 { ProgressView(value: task.progress).controlSize(.small) } else { ProgressView().controlSize(.small) } + if !task.detail.isEmpty { + Text(task.detail).font(.caption2.monospacedDigit()).foregroundStyle(.secondary).lineLimit(1) + } } else { Text(task.detail).font(.caption2).foregroundStyle(.secondary).lineLimit(1) } diff --git a/Sources/Lichtkasten/Views/TasksWindow.swift b/Sources/Lichtkasten/Views/TasksWindow.swift index d36c449..17deecf 100644 --- a/Sources/Lichtkasten/Views/TasksWindow.swift +++ b/Sources/Lichtkasten/Views/TasksWindow.swift @@ -22,12 +22,25 @@ struct TasksWindow: View { TableColumn("Als") { j in Text(j.remoteName).foregroundStyle(.secondary) } TableColumn("Ziel") { j in Text(j.targetName) } TableColumn("Status") { j in UploadStatusView(status: j.status) } + TableColumn("Fortschritt") { j in + if j.status == .running { + HStack { + ProgressView(value: j.progress).frame(width: 90) + Text("\(Int(j.progress * 100)) %").monospacedDigit().font(.caption) + } + } else { + Text(ByteCountFormatter.string(fromByteCount: j.fileSize, countStyle: .file)).foregroundStyle(.secondary) + } + } } .frame(minHeight: 180) } Divider() HStack { Toggle("Einzelne Upload-Dateien", isOn: $showFiles).toggleStyle(.checkbox) + if uploads.rate > 0 { + Label(uploads.rateText, systemImage: "speedometer").monospacedDigit().foregroundStyle(Color.accentColor) + } Spacer() Button("Fehlgeschlagene Uploads wiederholen") { uploads.retryFailed() }.disabled(uploads.failedCount == 0) Button("Erledigte entfernen") { tasks.clearFinished(); uploads.clearFinished() } diff --git a/Sources/LichtkastenCore/Upload/FTPUploader.swift b/Sources/LichtkastenCore/Upload/FTPUploader.swift index 73c142e..914d475 100644 --- a/Sources/LichtkastenCore/Upload/FTPUploader.swift +++ b/Sources/LichtkastenCore/Upload/FTPUploader.swift @@ -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 { diff --git a/Sources/LichtkastenCore/Upload/ImmichClient.swift b/Sources/LichtkastenCore/Upload/ImmichClient.swift index d267971..c4fc33f 100644 --- a/Sources/LichtkastenCore/Upload/ImmichClient.swift +++ b/Sources/LichtkastenCore/Upload/ImmichClient.swift @@ -94,15 +94,26 @@ public final class ImmichClient: @unchecked Sendable { /// Uploads one file as multipart/form-data (streamed from a temp file, RAWs can be large). /// Newer Immich (3.x) dropped deviceAssetId/deviceId; older servers require them → automatic retry. - public func upload(file: URL, captureDate: Date?) async throws -> UploadResult { + public func upload(file: URL, captureDate: Date?, progress: (@Sendable (Int64) -> Void)? = nil) async throws -> UploadResult { do { - return try await upload(file: file, captureDate: captureDate, legacyFields: false) + return try await upload(file: file, captureDate: captureDate, legacyFields: false, progress: progress) } catch ImmichError.http(400, let body) where body.contains("deviceAssetId") || body.contains("deviceId") { - return try await upload(file: file, captureDate: captureDate, legacyFields: true) + return try await upload(file: file, captureDate: captureDate, legacyFields: true, progress: progress) } } - private func upload(file: URL, captureDate: Date?, legacyFields: Bool) async throws -> UploadResult { + /// Reports bytes sent for the live upload rate. + final class ProgressDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable { + let onSent: (@Sendable (Int64) -> Void)? + init(_ f: (@Sendable (Int64) -> Void)?) { onSent = f } + func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + onSent?(totalBytesSent) + } + } + + private func upload(file: URL, captureDate: Date?, legacyFields: Bool, + progress: (@Sendable (Int64) -> Void)?) async throws -> UploadResult { let attrs = try FileManager.default.attributesOfItem(atPath: file.path) let modified = (attrs[.modificationDate] as? Date) ?? Date() let size = (attrs[.size] as? NSNumber)?.int64Value ?? 0 @@ -139,7 +150,7 @@ public final class ImmichClient: @unchecked Sendable { var r = try request("assets", method: "POST") r.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") - let (data, resp) = try await session.upload(for: r, fromFile: body) + let (data, resp) = try await session.upload(for: r, fromFile: body, delegate: ProgressDelegate(progress)) let code = (resp as? HTTPURLResponse)?.statusCode ?? 0 guard (200..<300).contains(code) else { throw ImmichError.http(code, String(decoding: data, as: UTF8.self)) } guard let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any], let id = obj["id"] as? String else {