Files
lichtkasten/Sources/Lichtkasten/Services/UploadQueue.swift
T
Lichtkasten DevandClaude Opus 5.5 b2210757dd Fixes aus dem Bundesliga-Einsatz
- Upload: kein Absturz mehr bei abreißender Verbindung (Restzeit-Berechnung lief über), SIGPIPE ignoriert;
  bei Netzwechsel werden laufende Übertragungen abgebrochen und auf dem neuen Netz automatisch neu
  gestartet (Versuch zählt nicht), ohne Netz warten sie; tote Verbindungen enden nach 45 s
- LR-Export: Bilder, die sich auf der Platte ändern, werden neu eingelesen (vorher blieb der erste,
  unvollständige Stand stehen); nie leeres IPTC über das JPEG schreiben; Zuordnung auch mit altem Plugin
- I-Fenster: Cursor in der Beschreibung steht oben (wie PM), nicht am Ende
- ⌘A wählt alle Bilder, ⌘⌫ legt die Auswahl (RAW + JPEG + XMP) nach Rückfrage in den Papierkorb
- Gesendet-Status getrennt: grünes FTP- und blaues Immich-Abzeichen, Filter je Ziel, Info in Lupe/I-Fenster
- nach dem Ingest sind die neu importierten Bilder ausgewählt (direkt weiter nach Lightroom)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
2026-11-06 23:51:05 +00:00

333 lines
15 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
import Network
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?
// MARK: Network changes (Wi-Fi ↔ hotspot ↔ LAN in the stadium)
/// No network: new transfers wait until it is back.
@Published private(set) var networkPaused = false
private let pathMonitor = NWPathMonitor()
private var lastPathSignature: String?
/// running transfers, so they can be stopped when the network changes
private var runningTasks: [UUID: Task<Void, Never>] = [:]
/// jobs stopped because of a network change – they start again by themselves, the attempt does not count
private var interruptedByNetwork = Set<UUID>()
private var resumeTask: Task<Void, Never>?
init() {
pathMonitor.pathUpdateHandler = { [weak self] path in
let signature = "\(path.status)|" + path.availableInterfaces.map(\.name).joined(separator: ",")
let online = path.status == .satisfied
Task { @MainActor [weak self] in self?.networkChanged(signature: signature, online: online) }
}
pathMonitor.start(queue: DispatchQueue(label: "lichtkasten.network"))
}
/// The network changed: running transfers on the old connection would hang or die – stop them cleanly
/// and start them again on the new connection (when there is one).
private func networkChanged(signature: String, online: Bool) {
defer { lastPathSignature = signature }
guard let last = lastPathSignature, last != signature else { return }
networkPaused = !online
if !runningTasks.isEmpty {
interruptedByNetwork.formUnion(runningTasks.keys)
for t in runningTasks.values { t.cancel() }
state?.statusText = online ? "Netzwerk gewechselt – laufende Uploads werden neu gestartet"
: "Netzwerk weg – Uploads werden fortgesetzt, sobald es wieder da ist"
}
resumeTask?.cancel()
guard online else { return }
resumeTask = Task { [weak self] in
try? await Task.sleep(nanoseconds: 2_000_000_000) // let the new connection settle (DHCP, DNS)
guard !Task.isCancelled else { return }
self?.immichClient = nil // fresh URLSession on the new network
self?.pump()
}
}
var rateText: String {
if networkPaused { return "Kein Netz – Uploads warten" }
guard rate.isFinite, rate > 0 else { return "" }
// a stalled connection lets the smoothed rate fall towards 0 → the ETA would be astronomically large
// (Int(Double) overflow = crash). Below 1 KB/s it is shown as stalled instead.
guard rate >= 1024 else { return "Verbindung stockt …" }
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(min(Double(remainingBytes) / rate, 359_999))
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 = max(0, Double(sentCounter - last.bytes) / dt) // a restarted file must not go negative
rate = rate == 0 ? instant : rate * 0.6 + instant * 0.4 // smoothing
if rate < 1 { rate = 0 }
}
}
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 {
var ctx = VariableContext.make(fileURL: f, exif: src?.exif ?? [:], iptc: src?.iptc ?? IPTCValues(),
dateFormat: state.settings.dateFormat)
if let src { ctx.values.merge(state.matchVariables(for: src)) { iptc, _ in iptc } }
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 !networkPaused, running < maxParallel, let idx = jobs.firstIndex(where: { $0.status == .waiting }) {
jobs[idx].status = .running
jobs[idx].attempts += 1
running += 1
let job = jobs[idx]
runningTasks[job.id] = 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; runningTasks[job.id] = nil; 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 where interruptedByNetwork.contains(job.id) {
// stopped by a network change: wait for the new connection, this attempt does not count
interruptedByNetwork.remove(job.id)
if let i = jobs.firstIndex(where: { $0.id == job.id }) {
jobs[i].status = .waiting
jobs[i].attempts = max(0, jobs[i].attempts - 1)
}
} 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)
}
}
}
}
}