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? var status: Status = .waiting var attempts = 0 var batch: UUID? 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? private var immichAlbumId: String? private var immichNewAssets: [String] = [] /// 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 = "" if target == "immich" { name = "Immich" } else if let d = state.settings.ftpDestinations.first(where: { $0.id.uuidString == target }) { name = d.name pattern = d.renamePattern } 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() } var job = UploadJob(file: f, target: target, targetName: name, remoteName: remote, captureDate: src?.captureDate) job.batch = batch jobs.append(job) } pump() } func retryFailed() { for i in jobs.indices { if case .failed = jobs[i].status { jobs[i].status = .waiting; jobs[i].attempts = 0 } } 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 { return } do { if job.target == "immich" { let client = try immich(state) let r = try await client.upload(file: job.file, captureDate: job.captureDate) if !r.duplicate { immichNewAssets.append(r.assetId) } 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)) setStatus(job.id, .done) } } 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; immichAlbumId = nil } private func finishImmichBatch() { guard !immichNewAssets.isEmpty, let state, let client = immichClient else { return } let album = state.settings.immich.albumName.trimmingCharacters(in: .whitespaces) let ids = immichNewAssets immichNewAssets = [] guard !album.isEmpty else { return } Task { do { let albumId = try await client.albumId(named: album) try await client.add(assetIds: ids, toAlbum: albumId) } catch { state.report(error) } } } }