From b2210757dd5cb2ada46669c7c0584fc7d3d3296a Mon Sep 17 00:00:00 2001 From: Lichtkasten Dev Date: Fri, 6 Nov 2026 23:51:05 +0000 Subject: [PATCH] Fixes aus dem Bundesliga-Einsatz MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D --- Sources/Lichtkasten/LichtkastenApp.swift | 9 +- Sources/Lichtkasten/Services/AppState.swift | 122 ++++++++++++++++-- .../Services/KeyboardMonitor.swift | 7 + .../Lichtkasten/Services/UploadQueue.swift | 67 +++++++++- Sources/Lichtkasten/Views/CodeTextViews.swift | 9 ++ .../Lichtkasten/Views/ContactSheetView.swift | 30 ++++- Sources/Lichtkasten/Views/Theme.swift | 16 ++- .../LichtkastenCore/Upload/FTPUploader.swift | 26 +++- Sources/LichtkastenCore/Upload/SentLog.swift | 33 ++++- Tests/LichtkastenCoreTests/CoreTests.swift | 12 ++ 10 files changed, 298 insertions(+), 33 deletions(-) diff --git a/Sources/Lichtkasten/LichtkastenApp.swift b/Sources/Lichtkasten/LichtkastenApp.swift index 17d03e0..68326ac 100644 --- a/Sources/Lichtkasten/LichtkastenApp.swift +++ b/Sources/Lichtkasten/LichtkastenApp.swift @@ -3,6 +3,11 @@ import SwiftUI import LichtkastenCore final class AppDelegate: NSObject, NSApplicationDelegate { + func applicationWillFinishLaunching(_ notification: Notification) { + // A helper process (curl, exiftool) that dies while we write to it must not kill the app (SIGPIPE). + signal(SIGPIPE, SIG_IGN) + } + func applicationDidFinishLaunching(_ notification: Notification) { // Needed when started via `swift run` (no app bundle). NSApp.setActivationPolicy(.regular) @@ -113,9 +118,11 @@ struct AppCommands: Commands { }.keyboardShortcut("r", modifiers: [.command, .shift]) } CommandMenu("Bild") { - Button("Alle auswählen") { state.selectAll() }.keyboardShortcut("a", modifiers: [.command, .option]) + Button("Alle auswählen (⌘A)") { state.selectAll() }.keyboardShortcut("a", modifiers: [.command, .option]) Button("Getaggte auswählen") { state.selectTagged() }.keyboardShortcut("t", modifiers: [.command, .option]) Button("Auswahl aufheben") { state.deselectAll() }.keyboardShortcut("d") + Button("In den Papierkorb … (⌘⌫)") { state.trashSelected() } + .disabled(state.selectedItems.isEmpty) Divider() Button("Tag umschalten (T)") { state.toggleTag() } Menu("Farbklasse (1–8)") { diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift index 5d8577e..4b59f0b 100644 --- a/Sources/Lichtkasten/Services/AppState.swift +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -6,7 +6,11 @@ import LichtkastenCore enum TagFilter: String, CaseIterable { case all = "Alle", tagged = "Getaggt", untagged = "Nicht getaggt" } /// "Gesendet"-Filter -enum SentFilter: String, CaseIterable { case all = "Alle", sent = "Gesendet", notSent = "Nicht gesendet" } +enum SentFilter: String, CaseIterable { + case all = "Alle", sent = "Gesendet", notSent = "Nicht gesendet" + case ftp = "Per FTP gesendet", notFTP = "Nicht per FTP gesendet" + case immich = "An Immich gesendet", notImmich = "Nicht an Immich gesendet" +} struct PMFilter: Equatable { var tag: TagFilter = .all @@ -315,6 +319,17 @@ final class AppState: ObservableObject { if panel.runModal() == .OK, let url = panel.url { open(folder: url) } } + /// Photos to select when a folder is opened next (the last ingest into it) + private var pendingSelection: [URL: Set] = [:] + + private func selectIngested(_ ids: Set) { + let present = visible.filter { ids.contains($0.primary.standardizedFileURL.path) }.map(\.id) + guard !present.isEmpty else { return } + selection = Set(present) + cursorID = present.first + statusText = "\(present.count) neu importierte Bilder ausgewählt" + } + private struct TabSnapshot { var items: [PhotoItem]; var selection: Set; var cursor: String? } private var tabSnapshots: [URL: TabSnapshot] = [:] @@ -337,6 +352,7 @@ final class AppState: ObservableObject { loadJerseyCache() refreshFolder() statusText = "\(items.count) Bilder" + if let ids = pendingSelection.removeValue(forKey: url) { selectIngested(ids) } return } folder = url @@ -349,6 +365,7 @@ final class AppState: ObservableObject { selection = [] cursorID = visible.first?.id if let c = cursorID { selection = [c] } + if let ids = pendingSelection.removeValue(forKey: url) { selectIngested(ids) } statusText = "\(scanned.count) Bilder" folderWatcher.watch(url) loadJerseyCache() @@ -401,22 +418,39 @@ final class AppState: ObservableObject { for i in items { existing[i.id] = i } var merged: [PhotoItem] = [] var newOnes: [PhotoItem] = [] + var changed: [PhotoItem] = [] + let now = Date() for var item in scanned { if let old = existing[item.id] { - let companions = item.companions + // File changed on disk by someone else (Lightroom still writing the JPEG, our IPTC rewrite after + // the export, PM …) → read its metadata again; otherwise the first, incomplete read stays forever. + let fileChanged = old.fileSize != item.fileSize || old.modified != item.modified + let ours = ownWrites[item.id].map { now.timeIntervalSince($0) < 5 } ?? false + if fileChanged && !ours { changed.append(item) } + let companions = item.companions, size = item.fileSize, modified = item.modified item = old item.companions = companions + item.fileSize = size + item.modified = modified } else { newOnes.append(item) } merged.append(item) } let sameIDs = merged.map(\.id) == items.map(\.id) - if sameIDs && newOnes.isEmpty && merged.map(\.companions) == items.map(\.companions) { return } + if sameIDs && newOnes.isEmpty && changed.isEmpty && merged.map(\.companions) == items.map(\.companions) { return } setItems(merged) selection = selection.filter { indexByID[$0] != nil } if let c = cursorID, indexByID[c] == nil { cursorID = visible.first?.id } - if !newOnes.isEmpty { Task { await loadMetadata(for: newOnes) } } + if !newOnes.isEmpty || !changed.isEmpty { Task { await loadMetadata(for: newOnes + changed) } } + } + + /// Files Lichtkasten itself just wrote (stars, IPTC …) – not re-read when the folder watcher fires. + private var ownWrites: [String: Date] = [:] + private func noteOwnWrite(_ targets: [PhotoItem]) { + let now = Date() + for t in targets { ownWrites[t.id] = now } + if ownWrites.count > 5000 { ownWrites = ownWrites.filter { now.timeIntervalSince($0.value) < 60 } } } // MARK: RAW ⇄ SENT @@ -578,9 +612,13 @@ final class AppState: ObservableObject { if result.skipped > 0 { detail += ", \(result.skipped) bereits importiert übersprungen" } if !result.lockedCopies.isEmpty { detail += ", \(result.lockedCopies.count) gesperrt" + (settings.tagLockedPhotos ? " → getaggt" : "") } self.tasks.finish(taskID, detail: detail + ejectNote) + // the photos of this ingest are selected (e.g. straight into Lightroom with ⌘E / ⌘⇧L) + let newIDs = Set(result.copied.map(\.standardizedFileURL.path)) + for f in result.folders where f != self.folder { self.pendingSelection[f] = newIDs } if let current = self.folder, result.folders.contains(current) { self.metadataCache = nil self.refreshFolder() + self.selectIngested(newIDs) await self.loadMetadata(for: self.items) // after the refresh, so the new photos are part of it if self.settings.jersey.autoAfterIngest, !self.settings.jersey.teams.isEmpty { @@ -604,7 +642,15 @@ final class AppState: ObservableObject { private func rebuildVisible() { var list = items.filter { filter.matches($0) } if filter.suggestionsOnly { list = list.filter { !(openSuggestions(for: $0.id).isEmpty) } } - if filter.sent != .all { list = list.filter { sentLog.wasSent($0) == (filter.sent == .sent) } } + switch filter.sent { + case .all: break + case .sent: list = list.filter { sentLog.wasSent($0) } + case .notSent: list = list.filter { !sentLog.wasSent($0) } + case .ftp: list = list.filter { sentLog.wasSentByFTP($0) } + case .notFTP: list = list.filter { !sentLog.wasSentByFTP($0) } + case .immich: list = list.filter { sentLog.wasSentToImmich($0) } + case .notImmich: list = list.filter { !sentLog.wasSentToImmich($0) } + } if filter.team != nil || filter.person != nil || filter.withoutPlayer { list = list.filter { item in let p = playerInfo(for: item) @@ -757,6 +803,39 @@ final class AppState: ObservableObject { } func selectAll() { selection = Set(visible.map(\.id)) } + + /// ⌘⌫ – moves the selected photos (RAW, JPEG, XMP sidecar) to the Trash (Finder: "Put Back" restores them). + func trashSelected() { + let targets = selectedItems + guard !targets.isEmpty else { return } + let alert = NSAlert() + alert.messageText = targets.count == 1 ? "„\(targets[0].filename)“ in den Papierkorb legen?" + : "\(targets.count) Bilder in den Papierkorb legen?" + alert.informativeText = "RAW, JPEG und XMP-Datei werden zusammen verschoben. Im Finder lassen sie sich mit „Zurücklegen“ wiederherstellen." + alert.addButton(withTitle: "In den Papierkorb") + alert.addButton(withTitle: "Abbrechen") + alert.alertStyle = .warning + guard alert.runModal() == .alertFirstButtonReturn else { return } + let fm = FileManager.default + var trashed = Set() + var failed: [String] = [] + for item in targets { + var files = [item.primary] + item.companions + if item.kind.usesSidecar, fm.fileExists(atPath: item.sidecarURL.path) { files.append(item.sidecarURL) } + do { + for f in files where fm.fileExists(atPath: f.path) { try fm.trashItem(at: f, resultingItemURL: nil) } + trashed.insert(item.id) + } catch { failed.append("\(item.filename): \(error.localizedDescription)") } + } + // cursor to the photo after the deleted ones (like PM) + let after = visible.drop { !trashed.contains($0.id) }.first { !trashed.contains($0.id) }?.id + ?? visible.last { !trashed.contains($0.id) }?.id + setItems(items.filter { !trashed.contains($0.id) }) + cursorID = after + selection = after.map { [$0] } ?? [] + statusText = "\(trashed.count) Bild(er) in den Papierkorb gelegt" + if !failed.isEmpty { self.alert = AppAlert(title: "Nicht alles gelöscht", message: failed.joined(separator: "\n")) } + } func deselectAll() { selection = cursorID.map { [$0] } ?? [] } func selectTagged() { selection = Set(visible.filter(\.tagged).map(\.id)) } @@ -818,7 +897,9 @@ final class AppState: ObservableObject { private func writeState(_ targets: [PhotoItem], _ w: MetadataWriter) { let updated = targets.compactMap { item($0.id) } serialWrite { [weak self] in + self?.noteOwnWrite(updated) for t in updated { do { try await w.writeState(of: t) } catch { self?.report(error) } } + self?.noteOwnWrite(updated) } } @@ -884,7 +965,9 @@ final class AppState: ObservableObject { let expanded = VariableExpander.expand(merged, context: ctx, codes: codes) do { let old = item(t.id) ?? t + noteOwnWrite([t]) try await w.write(values: expanded, fields: fields, to: t) + noteOwnWrite([t]) mutate([t], rebuild: false) { $0.iptc = expanded } if count % 50 == 49 { rebuildVisible() } // visible progress on big selections before.append(old) @@ -923,7 +1006,9 @@ final class AppState: ObservableObject { await writeTail?.value let before = current(targets) do { + noteOwnWrite(targets) let result = try await w.apply(template: template, to: targets, codes: codes, dateFormat: settings.dateFormat) + noteOwnWrite(targets) for t in targets { if let v = result[t.id] { mutate([t], rebuild: false) { $0.iptc = v } } } rebuildVisible() if recordUndo { @@ -1115,12 +1200,21 @@ final class AppState: ObservableObject { var exportedItems: [PhotoItem] = [] var missingSources = 0 for file in result.exported { - guard let src = result.exportSources[file], let source = sources[Self.exportKey(src)] else { + // plugin ≥ 0.2 reports the source path; older plugins (not reinstalled in LR) only the JPEG → + // fall back to the file name (LR keeps it, may append "-2") + let base = file.deletingPathExtension().lastPathComponent + let byPath = result.exportSources[file].flatMap { sources[Self.exportKey($0)] } + guard let source = byPath ?? sources.values.first(where: { + base == $0.baseName || base.hasPrefix($0.baseName + "-") + }) else { missingSources += 1 continue } var exported = PhotoItem(primary: file) - if job.rewriteIPTCAfterExport { + // Never write an empty block over the JPEG: if the source's metadata was not read (yet), the + // IPTC Lightroom wrote stays – otherwise the photo would lose everything. + let sourceHasIPTC = source.metadataLoaded && !source.iptc.isCompletelyEmpty + if job.rewriteIPTCAfterExport && sourceHasIPTC { guard let writer else { continue } do { try await writer.write(values: source.iptc, fields: IPTCField.all, to: exported) @@ -1129,9 +1223,13 @@ final class AppState: ObservableObject { continue } } - exported.iptc = source.iptc - exported.exif = source.exif - exported.captureDate = source.captureDate + if sourceHasIPTC { + exported.iptc = source.iptc + exported.exif = source.exif + exported.captureDate = source.captureDate + } else if let et = exiftool, let meta = try? await et.readMetadata(files: [file]) { + exported.apply(fileMeta: meta[file.path] ?? [:], sidecarMeta: nil) // what Lightroom wrote + } exportedItems.append(exported) } if missingSources > 0 && (job.rewriteIPTCAfterExport || !job.uploadTargets.isEmpty) { @@ -1368,7 +1466,9 @@ final class AppState: ObservableObject { return cur } serialWrite { [weak self] in + self?.noteOwnWrite(toWrite) for t in toWrite { do { try await w.writeState(of: t) } catch { self?.report(error) } } + self?.noteOwnWrite(toWrite) } case .iptc(let fields): for s in snapshots { @@ -1379,7 +1479,9 @@ final class AppState: ObservableObject { } rebuildVisible() serialWrite { [weak self] in + self?.noteOwnWrite(snapshots) for s in snapshots { do { try await w.write(values: s.iptc, fields: fields, to: s) } catch { self?.report(error) } } + self?.noteOwnWrite(snapshots) } } } diff --git a/Sources/Lichtkasten/Services/KeyboardMonitor.swift b/Sources/Lichtkasten/Services/KeyboardMonitor.swift index 35293bc..447a163 100644 --- a/Sources/Lichtkasten/Services/KeyboardMonitor.swift +++ b/Sources/Lichtkasten/Services/KeyboardMonitor.swift @@ -27,6 +27,13 @@ final class KeyboardMonitor { if isTyping(event, state: state) { return false } let mods = event.modifierFlags.intersection(.deviceIndependentFlagsMask) let shift = mods.contains(.shift) + // ⌘A / ⌘⌫ only here (browser window, not typing) – as menu shortcuts they would break + // "select all" and "delete line" in every text field + if mods.subtracting([.function, .numericPad, .capsLock]) == [.command] { + if event.keyCode == 51 || event.keyCode == 117 { state.trashSelected(); return true } // ⌫ / ⌦ + if event.charactersIgnoringModifiers?.lowercased() == "a" { state.selectAll(); return true } + return false + } if mods.contains(.command) || mods.contains(.control) { return false } switch event.keyCode { diff --git a/Sources/Lichtkasten/Services/UploadQueue.swift b/Sources/Lichtkasten/Services/UploadQueue.swift index 175d663..9e00486 100644 --- a/Sources/Lichtkasten/Services/UploadQueue.swift +++ b/Sources/Lichtkasten/Services/UploadQueue.swift @@ -1,4 +1,5 @@ import Foundation +import Network import SwiftUI import LichtkastenCore @@ -47,12 +48,58 @@ final class UploadQueue: ObservableObject { 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] = [:] + /// jobs stopped because of a network change – they start again by themselves, the attempt does not count + private var interruptedByNetwork = Set() + private var resumeTask: Task? + + 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 { - guard rate > 0 else { return "" } + 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(Double(remainingBytes) / rate) + 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)" @@ -79,8 +126,9 @@ final class UploadQueue: ObservableObject { if let last = lastSample { let dt = now.timeIntervalSince(last.time) if dt > 0 { - let instant = Double(sentCounter - last.bytes) / dt + 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) @@ -178,12 +226,12 @@ final class UploadQueue: ObservableObject { } private func pump() { - while running < maxParallel, let idx = jobs.firstIndex(where: { $0.status == .waiting }) { + 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] - Task { await self.run(job) } + runningTasks[job.id] = Task { await self.run(job) } } if running == 0 { finishImmichBatch() } } @@ -203,7 +251,7 @@ final class UploadQueue: ObservableObject { } private func run(_ job: UploadJob) async { - defer { running -= 1; pump() } + 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 @@ -238,6 +286,13 @@ final class UploadQueue: ObservableObject { } } 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 diff --git a/Sources/Lichtkasten/Views/CodeTextViews.swift b/Sources/Lichtkasten/Views/CodeTextViews.swift index 06e7a3a..9b3170c 100644 --- a/Sources/Lichtkasten/Views/CodeTextViews.swift +++ b/Sources/Lichtkasten/Views/CodeTextViews.swift @@ -39,6 +39,7 @@ struct CodeTextView: NSViewRepresentable { tv.isContinuousSpellCheckingEnabled = true tv.textContainerInset = NSSize(width: 3, height: 4) tv.string = text + CodeTextView.cursorToStart(tv) return sv } @@ -46,6 +47,14 @@ struct CodeTextView: NSViewRepresentable { context.coordinator.parent = self guard let tv = sv.documentView as? NSTextView, tv.string != text, !context.coordinator.editing else { return } tv.string = text + CodeTextView.cursorToStart(tv) + } + + /// Like PM: a newly loaded caption starts with the cursor at the very top – on the empty placeholder + /// line for the people (setting `string` would leave it at the end). + static func cursorToStart(_ tv: NSTextView) { + tv.setSelectedRange(NSRange(location: 0, length: 0)) + tv.scrollRangeToVisible(NSRange(location: 0, length: 0)) } final class Coordinator: NSObject, NSTextViewDelegate { diff --git a/Sources/Lichtkasten/Views/ContactSheetView.swift b/Sources/Lichtkasten/Views/ContactSheetView.swift index 31b01ac..eb4aa1f 100644 --- a/Sources/Lichtkasten/Views/ContactSheetView.swift +++ b/Sources/Lichtkasten/Views/ContactSheetView.swift @@ -184,15 +184,31 @@ struct ThumbnailCell: View, Equatable { // sent to agency / Immich .overlay(alignment: .bottomLeading) { if let sent { - HStack(spacing: 3) { - Image(systemName: "paperplane.fill").font(.system(size: 9, weight: .bold)) - if sent.count > 1 { Text("\(sent.count)×").font(LK.mono(10, .semibold)) } + // FTP (agency) and Immich separately + HStack(spacing: 4) { + if let ftp = sent.ftp { + HStack(spacing: 3) { + Image(systemName: "paperplane.fill").font(.system(size: 9, weight: .bold)) + Text("FTP").font(.system(size: 9, weight: .bold)) + if ftp.count > 1 { Text("\(ftp.count)×").font(LK.mono(10, .semibold)) } + } + .foregroundStyle(LK.onAmber) + .padding(.horizontal, 6).frame(height: 18) + .background(Capsule().fill(LK.green)) + .help(ftp.tooltip) + } + if let immich = sent.immich { + HStack(spacing: 3) { + Image(systemName: "photo.stack.fill").font(.system(size: 9, weight: .bold)) + if immich.count > 1 { Text("\(immich.count)×").font(LK.mono(10, .semibold)) } + } + .foregroundStyle(.white) + .padding(.horizontal, 6).frame(height: 18) + .background(Capsule().fill(Color(red: 0.26, green: 0.52, blue: 0.96))) + .help(immich.tooltip.replacingOccurrences(of: "Gesendet an", with: "Hochgeladen zu")) + } } - .foregroundStyle(LK.onAmber) - .padding(.horizontal, 6).frame(height: 18) - .background(Capsule().fill(LK.green)) .padding(8) - .help(sent.tooltip) } } // open player suggestion diff --git a/Sources/Lichtkasten/Views/Theme.swift b/Sources/Lichtkasten/Views/Theme.swift index 2a76fbc..5567609 100644 --- a/Sources/Lichtkasten/Views/Theme.swift +++ b/Sources/Lichtkasten/Views/Theme.swift @@ -195,12 +195,20 @@ struct SentStatusLine: View { let summary: SentSummary? var body: some View { - HStack(alignment: .top, spacing: 6) { - Image(systemName: summary == nil ? "paperplane" : "paperplane.fill").font(.system(size: 11)) - Text(summary?.tooltip ?? "Noch nicht gesendet").lineLimit(2) + VStack(alignment: .leading, spacing: 3) { + line("paperplane", "FTP", summary?.ftp?.tooltip, LK.green) + line("photo.stack", "Immich", summary?.immich?.tooltip.replacingOccurrences(of: "Gesendet an Immich", with: "Hochgeladen"), + Color(red: 0.36, green: 0.6, blue: 1.0)) } .font(.system(size: 11, weight: .medium)) - .foregroundStyle(summary == nil ? LK.muted : LK.green) .frame(maxWidth: .infinity, alignment: .leading) } + + private func line(_ icon: String, _ what: String, _ text: String?, _ color: Color) -> some View { + HStack(alignment: .top, spacing: 6) { + Image(systemName: text == nil ? icon : icon + ".fill").font(.system(size: 11)) + Text(text ?? "\(what): noch nicht gesendet").lineLimit(2) + } + .foregroundStyle(text == nil ? LK.muted : color) + } } diff --git a/Sources/LichtkastenCore/Upload/FTPUploader.swift b/Sources/LichtkastenCore/Upload/FTPUploader.swift index 1b25c9e..84fbaaf 100644 --- a/Sources/LichtkastenCore/Upload/FTPUploader.swift +++ b/Sources/LichtkastenCore/Upload/FTPUploader.swift @@ -178,8 +178,10 @@ public struct FTPUploader: Sendable { let tempName = d.uploadWithTempName ? "lichtkasten-\(UUID().uuidString).part" : name let url = baseURL(d) + Self.encodePath(tempName) // No --silent: the progress meter on stderr gives the live upload rate. + // --speed-limit/-time: a dead connection (Wi-Fi without internet) ends after 45 s instead of hanging var args = connectionOptions(d) + ["--show-error", "--fail", "--ftp-create-dirs", "-o", "/dev/null", - "--connect-timeout", "20", "-K", "-", "-T", file.path, url] + "--connect-timeout", "20", "--speed-limit", "512", "--speed-time", "45", + "-K", "-", "-T", file.path, url] if d.uploadWithTempName { args.insert(contentsOf: ["--retry", "2"], at: 0) } if d.uploadWithTempName { if d.proto == .sftp { @@ -294,7 +296,15 @@ public struct FTPUploader: Sendable { /// 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 + // Cancelling the task (network change, cancel button) ends curl instead of letting it hang. + final class Running: @unchecked Sendable { + let lock = NSLock(); var process: Process?; var cancelled = false + func set(_ p: Process) -> Bool { lock.lock(); defer { lock.unlock() }; process = p; return !cancelled } + func cancel() { lock.lock(); cancelled = true; let p = process; lock.unlock(); if p?.isRunning == true { p?.terminate() } } + } + let running = Running() + let result: ProcResult = try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { cont in DispatchQueue.global(qos: .utility).async { do { let p = Process() @@ -318,7 +328,10 @@ public struct FTPUploader: Sendable { for line in parts where !line.isEmpty { onLine(line) } } try p.run() - if let stdin { inp.fileHandleForWriting.write(Data(stdin.utf8)) } + let alive = running.set(p) + if !alive { p.terminate() } + // throwing write: a curl that already exited must not take the app down (EPIPE) + if alive, let stdin { try? inp.fileHandleForWriting.write(contentsOf: Data(stdin.utf8)) } try? inp.fileHandleForWriting.close() _ = out.fileHandleForReading.readDataToEndOfFile() p.waitUntilExit() @@ -329,7 +342,12 @@ public struct FTPUploader: Sendable { stderr: String(decoding: all, as: UTF8.self))) } catch { cont.resume(throwing: error) } } + } + } onCancel: { + running.cancel() } + if Task.isCancelled { throw CancellationError() } + return result } struct ProcResult { var status: Int32; var stdout: String; var stderr: String } @@ -351,7 +369,7 @@ public struct FTPUploader: Sendable { p.standardError = err p.standardInput = inp try p.run() - if let stdin { inp.fileHandleForWriting.write(Data(stdin.utf8)) } + if let stdin { try? inp.fileHandleForWriting.write(contentsOf: Data(stdin.utf8)) } try? inp.fileHandleForWriting.close() // Read both pipes concurrently to avoid dead-locks on large output. final class Box: @unchecked Sendable { var data = Data() } diff --git a/Sources/LichtkastenCore/Upload/SentLog.swift b/Sources/LichtkastenCore/Upload/SentLog.swift index 1cb1eb9..992aadd 100644 --- a/Sources/LichtkastenCore/Upload/SentLog.swift +++ b/Sources/LichtkastenCore/Upload/SentLog.swift @@ -54,8 +54,19 @@ public struct SentLog: Codable, Sendable { let r = records(for: item) guard let last = r.last else { return nil } let names = r.reduce(into: [String]()) { acc, rec in if !acc.contains(rec.destinationName) { acc.append(rec.destinationName) } } - return SentSummary(count: r.count, destinations: names, last: last.date, lastDestination: last.destinationName) + var s = SentSummary(count: r.count, destinations: names, last: last.date, lastDestination: last.destinationName) + let ftp = r.filter { $0.destination != SentLog.immich }, immich = r.filter { $0.destination == SentLog.immich } + s.ftp = ftp.last.map { SentSummary.Part(count: ftp.count, last: $0.date, + destinations: Array(Set(ftp.map(\.destinationName))).sorted()) } + s.immich = immich.last.map { SentSummary.Part(count: immich.count, last: $0.date, destinations: ["Immich"]) } + return s } + + public static let immich = "immich" + + /// Sent to an FTP server (any) / to Immich. + public func wasSentByFTP(_ item: PhotoItem) -> Bool { records(for: item).contains { $0.destination != SentLog.immich } } + public func wasSentToImmich(_ item: PhotoItem) -> Bool { records(for: item).contains { $0.destination == SentLog.immich } } } public struct SentSummary: Hashable, Sendable { @@ -63,6 +74,26 @@ public struct SentSummary: Hashable, Sendable { public var destinations: [String] public var last: Date public var lastDestination: String + /// FTP and Immich separately – two badges on the thumbnail + public var ftp: Part? + public var immich: Part? + + public struct Part: Hashable, Sendable { + public var count: Int + public var last: Date + public var destinations: [String] + + public var tooltip: String { + let f = DateFormatter() + f.dateFormat = "dd.MM.yyyy HH:mm" + let times = count == 1 ? "" : " (\(count)× gesendet)" + return "Gesendet an \(destinations.joined(separator: ", ")) – zuletzt \(f.string(from: last))\(times)" + } + } + + public init(count: Int, destinations: [String], last: Date, lastDestination: String) { + self.count = count; self.destinations = destinations; self.last = last; self.lastDestination = lastDestination + } public var tooltip: String { let f = DateFormatter() diff --git a/Tests/LichtkastenCoreTests/CoreTests.swift b/Tests/LichtkastenCoreTests/CoreTests.swift index 03102bf..42596d5 100644 --- a/Tests/LichtkastenCoreTests/CoreTests.swift +++ b/Tests/LichtkastenCoreTests/CoreTests.swift @@ -383,6 +383,18 @@ final class SentLogTests: XCTestCase { log.clear([URL(fileURLWithPath: "/x/a.JPG")]) XCTAssertFalse(log.wasSent(item)) } + + func testFTPAndImmichAreShownSeparately() { + var log = SentLog() + let item = PhotoItem(primary: URL(fileURLWithPath: "/x/b.JPG")) + log.record(item.primary, SentRecord(destination: "immich", destinationName: "Immich", remoteName: "b.jpg")) + XCTAssertTrue(log.wasSentToImmich(item)) + XCTAssertFalse(log.wasSentByFTP(item)) + XCTAssertNil(log.summary(for: item)?.ftp) + log.record(item.primary, SentRecord(destination: "d1", destinationName: "Sport", remoteName: "b.jpg")) + XCTAssertEqual(log.summary(for: item)?.ftp?.destinations, ["Sport"]) + XCTAssertEqual(log.summary(for: item)?.immich?.count, 1) + } } final class BugfixTests: XCTestCase {