277 lines
12 KiB
Swift
277 lines
12 KiB
Swift
import Foundation
|
||
import SwiftUI
|
||
import LichtkastenCore
|
||
|
||
struct UploadJob: Identifiable {
|
||
enum Status: Equatable { case waiting, running, done, duplicate, failed(String) }
|
||
let id = UUID()
|
||
let file: URL
|
||
let target: String // FTP destination id or "immich"
|
||
let targetName: String
|
||
let remoteName: String
|
||
let captureDate: Date?
|
||
/// Immich album for this file (pattern already expanded with the image's IPTC, e.g. "{event}").
|
||
var album = ""
|
||
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 {
|
||
case .done, .duplicate, .failed: return true
|
||
default: return false
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Upload queue for FTP destinations and Immich (2 parallel transfers, 2 retries).
|
||
@MainActor
|
||
final class UploadQueue: ObservableObject {
|
||
@Published var jobs: [UploadJob] = []
|
||
weak var state: AppState?
|
||
private var running = 0
|
||
private let maxParallel = 2
|
||
private var immichClient: ImmichClient?
|
||
/// 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) }
|
||
}
|
||
|
||
var activeCount: Int { jobs.filter { $0.status == .waiting || $0.status == .running }.count }
|
||
var failedCount: Int { jobs.filter { if case .failed = $0.status { return true } else { return false } }.count }
|
||
|
||
func enqueue(files: [URL], target: String, sourceItems: [PhotoItem] = []) {
|
||
guard let state, !files.isEmpty else { return }
|
||
let name: String
|
||
var pattern = ""
|
||
var usedNames = Set<String>()
|
||
if target == "immich" {
|
||
name = "Immich"
|
||
} else if let d = state.settings.ftpDestinations.first(where: { $0.id.uuidString == target }) {
|
||
name = d.name
|
||
pattern = d.renamePattern
|
||
let uploader = FTPUploader()
|
||
let directory = uploader.baseURL(d).lowercased()
|
||
let matchingProfiles = Set(state.settings.ftpDestinations.filter {
|
||
uploader.baseURL($0).lowercased() == directory
|
||
}.map { $0.id.uuidString })
|
||
usedNames = Set(jobs.filter { !$0.isFinished && matchingProfiles.contains($0.target) }
|
||
.map { $0.remoteName.lowercased() })
|
||
} else { return }
|
||
var batchRef: UUID?
|
||
let batch = state.tasks.start(.upload, title: "Upload → \(name)", total: files.count) { [weak self] in
|
||
if let b = batchRef { self?.cancelBatch(b) }
|
||
}
|
||
batchRef = batch
|
||
for f in files {
|
||
let src = sourceItems.first { $0.primary == f || $0.companions.contains(f) }
|
||
var remote = f.lastPathComponent
|
||
if !pattern.isEmpty {
|
||
let ctx = VariableContext.make(fileURL: f, exif: src?.exif ?? [:], iptc: src?.iptc ?? IPTCValues(),
|
||
dateFormat: state.settings.dateFormat)
|
||
remote = VariableExpander.expand(pattern, context: ctx)
|
||
.replacingOccurrences(of: "/", with: "-") + "." + f.pathExtension.lowercased()
|
||
}
|
||
// a pattern without {filenamebase}/{seqn} gives many images the same name → they would overwrite
|
||
// each other on the server: number the duplicates
|
||
if usedNames.contains(remote.lowercased()) {
|
||
let ext = (remote as NSString).pathExtension, stem = (remote as NSString).deletingPathExtension
|
||
var n = 2
|
||
while usedNames.contains("\(stem)-\(n).\(ext)".lowercased()) { n += 1 }
|
||
remote = "\(stem)-\(n).\(ext)"
|
||
}
|
||
usedNames.insert(remote.lowercased())
|
||
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))
|
||
}
|
||
jobs.append(job)
|
||
}
|
||
pump()
|
||
}
|
||
|
||
func retryFailed() {
|
||
var batches = Set<UUID>()
|
||
for i in jobs.indices {
|
||
if case .failed = jobs[i].status {
|
||
jobs[i].status = .waiting; jobs[i].attempts = 0
|
||
if let b = jobs[i].batch { batches.insert(b) }
|
||
}
|
||
}
|
||
// the task rows were already "failed" – make them run again so the result is shown
|
||
for b in batches { state?.tasks.reopen(b) { [weak self] in self?.cancelBatch(b) } }
|
||
pump()
|
||
}
|
||
|
||
func clearFinished() {
|
||
jobs.removeAll { $0.status == .done || $0.status == .duplicate }
|
||
}
|
||
|
||
private func pump() {
|
||
while running < maxParallel, let idx = jobs.firstIndex(where: { $0.status == .waiting }) {
|
||
jobs[idx].status = .running
|
||
jobs[idx].attempts += 1
|
||
running += 1
|
||
let job = jobs[idx]
|
||
Task { await self.run(job) }
|
||
}
|
||
if running == 0 { finishImmichBatch() }
|
||
}
|
||
|
||
private func setStatus(_ id: UUID, _ s: UploadJob.Status) {
|
||
guard let i = jobs.firstIndex(where: { $0.id == id }) else { return }
|
||
jobs[i].status = s
|
||
guard let batch = jobs[i].batch, let state else { return }
|
||
let inBatch = jobs.filter { $0.batch == batch }
|
||
let finished = inBatch.filter(\.isFinished)
|
||
let failed = finished.filter { if case .failed = $0.status { return true } else { return false } }
|
||
state.tasks.update(batch, done: finished.count, detail: jobs[i].remoteName)
|
||
if finished.count == inBatch.count {
|
||
state.tasks.finish(batch, error: failed.isEmpty ? nil : "\(failed.count) fehlgeschlagen",
|
||
detail: "\(finished.count - failed.count) von \(inBatch.count) übertragen")
|
||
}
|
||
}
|
||
|
||
private func run(_ job: UploadJob) async {
|
||
defer { running -= 1; pump() }
|
||
guard let state else { setStatus(job.id, .failed("App-Zustand nicht verfügbar")); 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, 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) }
|
||
state.recordSent(file: job.file, destination: job.target, destinationName: job.targetName,
|
||
remoteName: job.remoteName, size: job.fileSize)
|
||
setStatus(job.id, r.duplicate ? .duplicate : .done)
|
||
} else {
|
||
guard let d = state.settings.ftpDestinations.first(where: { $0.id.uuidString == job.target }) else {
|
||
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), progress: onSent)
|
||
state.recordSent(file: job.file, destination: job.target, destinationName: job.targetName,
|
||
remoteName: job.remoteName, size: job.fileSize)
|
||
setStatus(job.id, .done)
|
||
}
|
||
} catch UploadError.remoteNameConflict(let name) {
|
||
setStatus(job.id, .failed(UploadError.remoteNameConflict(name).localizedDescription))
|
||
} catch {
|
||
if let i = jobs.firstIndex(where: { $0.id == job.id }), jobs[i].attempts < 3 {
|
||
jobs[i].status = .waiting
|
||
} else {
|
||
setStatus(job.id, .failed(error.localizedDescription))
|
||
}
|
||
}
|
||
}
|
||
|
||
private func immich(_ state: AppState) throws -> ImmichClient {
|
||
if let c = immichClient { return c }
|
||
let key = Keychain.get(ImmichSettings.keychainAccount) ?? ""
|
||
let c = try ImmichClient(settings: state.settings.immich, apiKey: key)
|
||
immichClient = c
|
||
return c
|
||
}
|
||
|
||
/// Settings changed → rebuild client next time.
|
||
func resetImmich() { immichClient = nil }
|
||
|
||
private func finishImmichBatch() {
|
||
guard !immichNewAssets.isEmpty, let state, let client = immichClient else { return }
|
||
let batches = immichNewAssets
|
||
immichNewAssets = [:]
|
||
Task {
|
||
for (album, ids) in batches {
|
||
do {
|
||
let albumId = try await client.albumId(named: album)
|
||
try await client.add(assetIds: ids, toAlbum: albumId)
|
||
state.statusText = "Immich: \(ids.count) Bild(er) im Album „\(album)“"
|
||
} catch {
|
||
state.report(error)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|