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:
Lichtkasten DevandClaude Opus 5.5 committed 2026-11-04 01:00:35 +00:00
1 parent 2bf0d851aa
commit 5505fa1f37
5 files changed
+198 -12

No files matched your search

+79 -2
View File
@@ -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 {