diff --git a/README.md b/README.md index 30cdb79..e0a9be3 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ Schneller Foto-Browser und Metadaten-Editor für macOS (Apple Silicon), gedacht als Alternative zu Photo Mechanic für Agentur-Workflows. -> Stand **v0.1**. Der Code wurde ohne Mac geschrieben und noch nie kompiliert. Beim ersten Build in Xcode -> sind kleinere Compiler-Fehler wahrscheinlich. Bitte die Fehlermeldungen an Claude zurückgeben. +> Der Code entsteht ohne Mac. Neue Funktionen werden erst beim Build auf dem Mac kompiliert, +> kleinere Compiler-Fehler sind dann möglich. Fehlermeldungen bitte an Claude zurückgeben. ## Funktionen @@ -18,6 +18,10 @@ Schneller Foto-Browser und Metadaten-Editor für macOS (Apple Silicon), gedacht | **Lightroom Classic** | ⌘⇧L importiert die Auswahl in den offenen Katalog. ⌘⌥L importiert, wendet die Entwicklungsvorgabe an und exportiert JPEGs, auf Wunsch mit automatischem Upload | | **FTP** | FTP, FTPS (explizit/implizit), SFTP. Mehrere Profile, Passwort im Schlüsselbund, Upload als `.part` mit anschließendem Umbenennen, Umbenennungsmuster | | **Immich** | Upload per API-Key, optional in ein Album (wird bei Bedarf angelegt) | +| **Gesendet-Status** | Jedes Bild merkt sich, wann es an welches Ziel ging (grünes Papierflieger-Abzeichen, Filter „Gesendet / Nicht gesendet“). Schon gesendete Bilder werden beim nächsten Upload auf Wunsch übersprungen | +| **Agentur-Check** | Prüft vor dem FTP-Upload Pflichtfelder, offene Codes, alte Datumsangaben aus der Vorlage, IIM-Längen und offene Trikot-Vorschläge. Fehlerhafte Bilder lassen sich direkt bearbeiten oder auslassen | +| **Rückgängig** | ⌘Z / ⇧⌘Z für Sterne, Farben, Tags, IPTC-Änderungen und Vorlagen, auch für viele Bilder auf einmal | +| **Spieltag-Assistent** | Heim, Gast, Wettbewerb und Datum wählen. Daraus entstehen Vorlage (Überschrift, Ereignis, Beschreibung, Ort, Stichwörter im Aufbau der eigenen PM-Vorlage), Ingest-Ordner, Trikot-Teams und aktive Code-Teams | ## Voraussetzungen @@ -49,6 +53,8 @@ Zum Entwickeln `Package.swift` in Xcode öffnen und das Scheme **Lichtkasten** s | ⌘⌥L | Lightroom: Vorgabe + JPEG-Export nach SENT | | ⌘⌥S | INPUT ⇄ SENT | | ⌘T | Neuer Tab · ⌘G Ingest · ⌘⌥U Aufgaben · ⌘⇧K Code-Ersetzungen | +| ⌘⇧N | Neuer Spieltag (Assistent) | +| ⌘Z / ⇧⌘Z | Rückgängig / Wiederholen (in Textfeldern wie gewohnt für den Text) | | Leertaste | Vorschau · Z = Einpassen/100 % · +/− oder Trackpad = Zoom (max. einstellbar) | Unter Einstellungen → Allgemein lässt sich auf die Lightroom-Belegung umstellen (0–5 = Sterne, 6–9 = Farben). @@ -119,3 +125,66 @@ App-Icon: `scripts/make-icon.py` erzeugt `Resources/AppIcon.icns`. 3. Bilder mit Vorschlag tragen ein blaues `#10`-Abzeichen, der Filter „Vorschläge“ zeigt nur diese. 4. Mit **I** prüfen: Die Nummer ist im Bild markiert. **⌘J** (Annehmen) trägt den Spieler in die erste Zeile der Beschreibung und unter „Persons shown“ ein, ✕ verwirft den Vorschlag. Danach wie gewohnt ⌘B = Speichern & nächstes. + +## Spieltag-Assistent (⌘⇧N) + +Die IPTC-Daten sind bei jedem Spiel gleich aufgebaut, nur Teams, Wettbewerb, Runde, Datum und Stadion ändern sich. + +1. **Heim** und **Gast** wählen. Mit „+“ legst du ein Team an, am schnellsten „Aus Code-Team …“: Name, Code-Team + und Präfix (`w`, `h`) werden übernommen. Pro Team werden Kurzname (für den Ordner), Kürzel (Matchcode `VFLTSG`), + Stichwörter, Heimstadion und die Trikotfarben gespeichert. Farben, die in der Trikot-Erkennung per Lupe aus + einem Foto gepickt werden, landen automatisch wieder im Team. +2. **Wettbewerb** (Name für Überschrift/Ereignis, Langform für die Beschreibung, Sportart, Stichwörter, + Rechtehinweis wie „DFB REGULATIONS …“), **Runde** und **Datum** eintragen. +3. **Basis-Vorlage** wählen, also deine normale PM-Vorlage. Fotograf, Copyright, Credit und die PM-Häkchen + kommen von dort, der Rest wird erzeugt. Rechts siehst du die fertige Vorschau. +4. „Spieltag anlegen“ (⌘↩): Es entsteht die Vorlage „Spieltag 02.11.2026 · Heim – Gast“, der Ingest-Ordner + (`02.11.2026 - Wolfsburg (F) - Hoffenheim (F)`) und die Vorlage werden im Ingest eingetragen, die Trikot-Erkennung + bekommt beide Teams und nur die Code-Teams dieser zwei Mannschaften sind aktiv. + +Der Aufbau ist unter „Aufbau der IPTC-Felder (Muster)“ frei änderbar, Standard ist: + +```text +Überschrift {competition}: {home} vs. {away}, {matchdate} +Ereignis {competition}: {home} - {away} +Beschreibung (3 Leerzeilen für die Personen) + ; {sport}, {competitionLong}, {round}: {home} vs. {away} am {matchdate} im {venue}, {city} + (Leerzeile + Rechtehinweis) +Ordner {matchdate} - {homeShort} - {awayShort} +``` + +Das Datum der Bilder bleibt die Aufnahmezeit. Wird derselbe Spieltag (gleiche Teams, gleicher Tag) noch einmal +angelegt, aktualisiert Lichtkasten die vorhandene Vorlage, statt eine zweite anzulegen. Im SENT-Ordner mit mehreren +Spielen nimmt die Matchday-Ansicht die Teams aus dem Ereignis des jeweiligen Bildes. + +## Agentur-Check + +Vor jedem FTP-Upload (⌘U, ⌘⇧U, Upload nach dem Lightroom-Export) prüft Lichtkasten die Bilder: + +| Fehler (rot) | Hinweis (gelb) | +|---|---| +| Pflichtfeld leer (einstellbar: Beschreibung, Überschrift, Fotograf, Copyright, Stadt, Land, Datum …) | Erste Zeile der Beschreibung leer (Personen fehlen) | +| Offene Variable `{…}` | Code ohne Ersetzung (`w10` steht noch im Text) | +| Code-Ersetzung mit Trennzeichen nicht aufgelöst (`\w10\`) | Datum in Überschrift/Beschreibung passt nicht zum Aufnahmetag (alte Vorlage?) | +| Bild kleiner als die Mindestkantenlänge | IIM-Länge überschritten, offene Trikot-Vorschläge | + +Läuft alles durch, startet der Upload ohne Rückfrage. Sonst zeigt ein Fenster die Befunde pro Bild mit +„Bearbeiten“ (öffnet das IPTC-Fenster), „Erneut prüfen“, „Nur fehlerfreie senden“ oder „Alle senden“. +Einstellungen → Agentur-Check legt Pflichtfelder und Regeln fest, pro FTP-Server lässt sich der Check abschalten. +Immich-Uploads werden nicht geprüft. + +## Gesendet-Status + +Nach jedem erfolgreichen Upload (FTP und Immich) speichert Lichtkasten Ziel, Zeit und Dateinamen auf dem Server +(`~/Library/Application Support/Lichtkasten/sent-log.json`). Die Bilder zeigen ein grünes Papierflieger-Abzeichen +(mit „2ד, wenn öfter gesendet), der Tooltip, die Lupe und das IPTC-Fenster nennen Ziel und Uhrzeit. Im Filter +„Gesendet“ lässt sich auf gesendete oder noch nicht gesendete Bilder einschränken. Das Upload-Fenster und der +Agentur-Check überspringen bereits an dieses Ziel gesendete Bilder auf Wunsch. Rechtsklick → „Als nicht gesendet +markieren“ setzt den Status zurück. + +## Rückgängig + +⌘Z nimmt die letzte Änderung zurück, ⇧⌘Z stellt sie wieder her. Das gilt für Sterne, Farbklassen und Tags, für +IPTC-Änderungen aus dem Info-Fenster und dem Mass-Edit sowie für angewendete Vorlagen, jeweils für alle betroffenen +Bilder auf einmal. Die alten Werte werden wieder in die Dateien geschrieben. Steht der Cursor in einem Textfeld, +wirkt ⌘Z wie gewohnt auf den Text. Das Menü „Bearbeiten“ zeigt, was zurückgenommen wird. diff --git a/Sources/Lichtkasten/LichtkastenApp.swift b/Sources/Lichtkasten/LichtkastenApp.swift index 99f7ef4..02df387 100644 --- a/Sources/Lichtkasten/LichtkastenApp.swift +++ b/Sources/Lichtkasten/LichtkastenApp.swift @@ -52,6 +52,14 @@ struct LichtkastenApp: App { } .windowResizability(.contentSize) + // Agentur-Check before uploading + Window("Agentur-Check", id: "check") { + PreflightWindow() + .environmentObject(state) + .lkWindow() + } + .defaultSize(width: 880, height: 660) + // PM: Tasks window Window("Aufgaben", id: "tasks") { TasksWindow() @@ -83,6 +91,13 @@ struct AppCommands: Commands { @ObservedObject var state: AppState var body: some Commands { + // Undo/redo of ratings, labels, tags and IPTC – text fields keep their own undo while typing. + CommandGroup(replacing: .undoRedo) { + Button(state.undoTitle.map { "Rückgängig: \($0)" } ?? "Rückgängig") { state.performUndo() } + .keyboardShortcut("z") + Button(state.redoTitle.map { "Wiederholen: \($0)" } ?? "Wiederholen") { state.performRedo() } + .keyboardShortcut("z", modifiers: [.command, .shift]) + } // Replaces "New Window" (⌘N) – ⌘N is "Save & previous" in the IPTC window like in PM. CommandGroup(replacing: .newItem) { Button("Ordner öffnen …") { state.chooseFolder() }.keyboardShortcut("o") @@ -91,6 +106,8 @@ struct AppCommands: Commands { .disabled(state.ingestRunning) Button("Ordner neu laden") { state.reload() }.keyboardShortcut("r") Divider() + Button("Neuer Spieltag …") { state.showSpieltag = true }.keyboardShortcut("n", modifiers: [.command, .shift]) + Divider() Button("Im Finder zeigen") { NSWorkspace.shared.activateFileViewerSelecting(state.selectedItems.map(\.primary)) }.keyboardShortcut("r", modifiers: [.command, .shift]) diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift index 56c2388..48e1b90 100644 --- a/Sources/Lichtkasten/Services/AppState.swift +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -5,6 +5,9 @@ import LichtkastenCore /// PM toolbar filters: Tag popup, star toggles, color class toggles. 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" } + struct PMFilter: Equatable { var tag: TagFilter = .all var ratingOn = false @@ -18,10 +21,12 @@ struct PMFilter: Equatable { var team: UUID? var person: String? var withoutPlayer = false + /// upload status + var sent: SentFilter = .all var isActive: Bool { tag != .all || (ratingOn && !ratings.isEmpty) || (colorOn && !colors.isEmpty) || suggestionsOnly - || team != nil || person != nil || withoutPlayer + || team != nil || person != nil || withoutPlayer || sent != .all } func matches(_ item: PhotoItem) -> Bool { @@ -51,6 +56,31 @@ struct WindowRequest: Equatable { let token = UUID() } +/// One step on the undo stack: the affected photos before and after the change. +struct UndoEntry { + enum Kind { case flags, iptc([IPTCField]) } + let title: String + let kind: Kind + let before: [PhotoItem] + let after: [PhotoItem] +} + +/// Upload waiting for the Agentur-Check / double-send decision. +struct PendingUpload: Identifiable { + let id = UUID() + let target: String + let targetName: String + var items: [PhotoItem] + /// item id → issues + var issues: [String: [PreflightIssue]] + /// item ids already sent to this target + var alreadySent: Set + + func hasError(_ id: String) -> Bool { issues[id]?.contains { $0.severity == .error } ?? false } + var errorItems: Int { items.filter { hasError($0.id) }.count } + var warningItems: Int { items.filter { !hasError($0.id) && !(issues[$0.id] ?? []).isEmpty }.count } +} + struct AppAlert: Identifiable { let id = UUID() let title: String @@ -81,7 +111,15 @@ final class AppState: ObservableObject { @Published var statusText = "" @Published var alert: AppAlert? @Published var templates: [IPTCTemplate] = [] { didSet { Storage.save(templates, to: Storage.templatesURL) } } - @Published var settings: AppSettings { didSet { Storage.save(settings, to: Storage.settingsURL) } } + @Published var settings: AppSettings { + didSet { + Storage.save(settings, to: Storage.settingsURL) + if settings.jersey.teams != oldValue.jersey.teams { syncKitsToProfiles() } + } + } + /// Spieltag assistant: teams, competitions, patterns, created matches + @Published var spieltag: SpieltagLibrary { didSet { Storage.save(spieltag, to: Storage.spieltagURL) } } + @Published var showSpieltag = false /// Teams with player codes (PM: list of code replacement files). @Published var codeLibrary: CodeLibrary { didSet { @@ -96,7 +134,8 @@ final class AppState: ObservableObject { private func rebuildPersonIndex() { var idx: [String: String] = [:] - for set in codeLibrary.sets where set.enabled { + // enabled teams first, then the others (the SENT folder holds photos of many games) + for set in codeLibrary.sets.filter(\.enabled) + codeLibrary.sets.filter({ !$0.enabled }) { for e in set.entries { guard let rep = e.columns.first else { continue } let name = JerseyLogic.personName(replacement: rep, columns: e.columns) @@ -142,15 +181,31 @@ final class AppState: ObservableObject { private var pendingLRJobs: [String: LightroomJob] = [:] @Published var lrPendingCount = 0 + /// Upload history ("Gesendet"-Status) + @Published private(set) var sentLog = SentLog() + private var sentLogSaveTask: Task? + /// Agentur-Check / double-send question waiting for the user (window "check") + @Published var pendingUpload: PendingUpload? + /// Undo / redo of ratings, labels, tags and IPTC changes + @Published private(set) var undoStack: [UndoEntry] = [] + @Published private(set) var redoStack: [UndoEntry] = [] + /// metadata writes run one after another (fast key presses, undo right after a change) + private var writeTail: Task? + init() { settings = Storage.load(AppSettings.self, from: Storage.settingsURL) ?? AppSettings() + spieltag = Storage.load(SpieltagLibrary.self, from: Storage.spieltagURL) ?? SpieltagLibrary() templates = Storage.load([IPTCTemplate].self, from: Storage.templatesURL) ?? [] let library = Storage.load(CodeLibrary.self, from: Storage.codeLibraryURL) ?? CodeLibrary.migrate(Storage.load(CodeReplacements.self, from: Storage.codesURL) ?? CodeReplacements()) codeLibrary = library codes = library.replacements rebuildPersonIndex() + sentLog = Storage.load(SentLog.self, from: Storage.sentLogURL) ?? SentLog() uploads.state = self + _ = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { self?.flushSentLog() } + } seedDefaultsIfNeeded() startLightroomPolling() // PM "Automatically reload code replacement files when they change" @@ -486,7 +541,7 @@ final class AppState: ObservableObject { i.apply(fileMeta: meta[item.primary.path] ?? [:], sidecarMeta: nil) return i } - await self.applyTemplateAndWait(template, to: loaded) + await self.applyTemplateAndWait(template, to: loaded, recordUndo: false) } } var detail = "\(result.copied.count) Fotos kopiert" @@ -519,6 +574,7 @@ 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) } } if filter.team != nil || filter.person != nil || filter.withoutPlayer { list = list.filter { item in let p = playerInfo(for: item) @@ -691,7 +747,10 @@ final class AppState: ObservableObject { func setRating(_ n: Int, advance: Bool = true, only: PhotoItem? = nil) { let targets = only.map { [$0] } ?? actionTargets guard !targets.isEmpty, let w = writer else { return } + let before = current(targets) mutate(targets) { $0.rating = n } + pushUndo(UndoEntry(title: (n == 0 ? "Sterne entfernt" : "\(n) ★") + countSuffix(targets.count), + kind: .flags, before: before, after: current(targets))) writeState(targets, w) advanceIfSingle(targets.count, advance) } @@ -701,7 +760,10 @@ final class AppState: ObservableObject { guard !targets.isEmpty, let w = writer else { return } // Same label again toggles it off (LR behaviour). let newLabel: ColorLabel? = targets.allSatisfy({ $0.label == l }) ? nil : l + let before = current(targets) mutate(targets) { $0.label = newLabel } + pushUndo(UndoEntry(title: (newLabel.map { "Farbklasse \($0.germanName)" } ?? "Farbklasse entfernt") + countSuffix(targets.count), + kind: .flags, before: before, after: current(targets))) writeState(targets, w) advanceIfSingle(targets.count, advance) } @@ -710,7 +772,10 @@ final class AppState: ObservableObject { let targets = actionTargets guard !targets.isEmpty, let w = writer else { return } let newValue = !targets.allSatisfy(\.tagged) + let before = current(targets) mutate(targets) { $0.tagged = newValue } + pushUndo(UndoEntry(title: (newValue ? "Tag gesetzt" : "Tag entfernt") + countSuffix(targets.count), + kind: .flags, before: before, after: current(targets))) writeState(targets, w) advanceIfSingle(targets.count) } @@ -718,9 +783,25 @@ final class AppState: ObservableObject { /// Writes tag/color/stars of the (already updated) items to disk. private func writeState(_ targets: [PhotoItem], _ w: MetadataWriter) { let updated = targets.compactMap { item($0.id) } - Task { for t in updated { do { try await w.writeState(of: t) } catch { report(error) } } } + serialWrite { [weak self] in + for t in updated { do { try await w.writeState(of: t) } catch { self?.report(error) } } + } } + /// Runs metadata writes strictly one after another. + func serialWrite(_ op: @escaping @MainActor () async -> Void) { + let previous = writeTail + writeTail = Task { @MainActor in + await previous?.value + await op() + } + } + + /// Current in-memory state of these photos (falls back to the passed copy, e.g. other folder). + private func current(_ targets: [PhotoItem]) -> [PhotoItem] { targets.map { item($0.id) ?? $0 } } + + private func countSuffix(_ n: Int) -> String { n == 1 ? "" : " (\(n) Bilder)" } + func report(_ error: Error) { alert = AppAlert(title: "Fehler", message: error.localizedDescription) } @@ -745,11 +826,20 @@ final class AppState: ObservableObject { } @discardableResult - func applyIPTCAndWait(_ draft: IPTCValues, fields: [IPTCField], to targets: [PhotoItem]) async -> Bool { + func applyIPTCAndWait(_ draft: IPTCValues, fields: [IPTCField], to targets: [PhotoItem], recordUndo: Bool = true) async -> Bool { guard !targets.isEmpty, !fields.isEmpty, let w = writer else { return false } rememberFieldValues(draft, fields: fields) statusText = "Schreibe IPTC in \(targets.count) Bild(er) …" + await writeTail?.value // pending flag writes first var count = 0 + var before: [PhotoItem] = [] + var after: [PhotoItem] = [] + defer { + if recordUndo && !after.isEmpty { + let title = (fields.count == 1 ? "IPTC: \(fields[0].label)" : "IPTC: \(fields.count) Felder") + countSuffix(after.count) + pushUndo(UndoEntry(title: title, kind: .iptc(fields), before: before, after: after)) + } + } for t in targets { var merged = item(t.id)?.iptc ?? t.iptc for f in fields { @@ -758,8 +848,11 @@ final class AppState: ObservableObject { let ctx = VariableContext.make(fileURL: t.primary, exif: t.exif, iptc: merged, dateFormat: settings.dateFormat) let expanded = VariableExpander.expand(merged, context: ctx, codes: codes) do { + let old = item(t.id) ?? t try await w.write(values: expanded, fields: fields, to: t) mutate([t]) { $0.iptc = expanded } + before.append(old) + after.append(item(t.id) ?? { var n = t; n.iptc = expanded; return n }()) count += 1 } catch { report(error); return false } } @@ -779,14 +872,7 @@ final class AppState: ObservableObject { /// FTP/Immich upload of one item (IPTC window "Speichern, Hochladen & →"). func upload(item: PhotoItem, to target: String) { - let variant: UploadVariant = target == "immich" ? settings.immich.variant - : settings.ftpDestinations.first { $0.id.uuidString == target }?.variant ?? .jpeg - let files = uploadFiles(for: item, variant: variant) - guard !files.isEmpty else { - alert = AppAlert(title: "Kein JPEG", message: "\(item.filename) hat kein JPEG zum Hochladen.") - return - } - uploads.enqueue(files: files, target: target, sourceItems: [item]) + requestUpload([self.item(item.id) ?? item], to: target) } func applyTemplate(_ template: IPTCTemplate, to targets: [PhotoItem]? = nil) { @@ -794,13 +880,23 @@ final class AppState: ObservableObject { Task { await applyTemplateAndWait(template, to: targets) } } - func applyTemplateAndWait(_ template: IPTCTemplate, to targets: [PhotoItem]) async { + func applyTemplateAndWait(_ template: IPTCTemplate, to targets: [PhotoItem], recordUndo: Bool = true) async { guard !targets.isEmpty, let w = writer else { return } if templates.contains(where: { $0.id == template.id }) { settings.lastTemplateID = template.id } statusText = "Wende Vorlage „\(template.name)“ an …" + await writeTail?.value + let before = current(targets) do { let result = try await w.apply(template: template, to: targets, codes: codes, dateFormat: settings.dateFormat) for t in targets { if let v = result[t.id] { mutate([t]) { $0.iptc = v } } } + if recordUndo { + let after = targets.map { t -> PhotoItem in + if let cur = item(t.id) { return cur } + var n = t; n.iptc = result[t.id] ?? t.iptc; return n + } + pushUndo(UndoEntry(title: "Vorlage „\(template.name)“" + countSuffix(targets.count), + kind: .iptc(template.fieldsToWrite), before: before, after: after)) + } statusText = "Vorlage auf \(targets.count) Bild(er) angewendet" } catch { report(error) } } @@ -965,7 +1061,7 @@ final class AppState: ObservableObject { return it } for target in job.uploadTargets { - uploads.enqueue(files: files, target: target, sourceItems: exportedItems) + requestUpload(exportedItems, to: target, skipAlreadySent: true) } if !job.uploadTargets.isEmpty { openWindow("tasks") } // SENT workflow: show the exported JPEGs for captioning. @@ -1002,24 +1098,194 @@ final class AppState: ObservableObject { } func upload(to target: String) { - let targets = selectedItems - guard !targets.isEmpty else { return } - let variant: UploadVariant - if target == "immich" { variant = settings.immich.variant } - else if let d = settings.ftpDestinations.first(where: { $0.id.uuidString == target }) { variant = d.variant } - else { return } - var files: [URL] = [] - var missing = 0 - for t in targets { - let f = uploadFiles(for: t, variant: variant) - if f.isEmpty { missing += 1 } - files += f - } + requestUpload(selectedItems, to: target) + } + + func uploadVariant(_ target: String) -> UploadVariant? { + if target == "immich" { return settings.immich.variant } + return settings.ftpDestinations.first { $0.id.uuidString == target }?.variant + } + + func uploadTargetName(_ target: String) -> String? { + if target == "immich" { return "Immich" } + return settings.ftpDestinations.first { $0.id.uuidString == target }?.name + } + + /// Every upload goes through here: photos without a suitable file, double sending, Agentur-Check – + /// only then the queue. Problems open the "Agentur-Check" window. + /// `skipAlreadySent`: nil = ask if some were sent before, true/false = decided (e.g. ⌘U window). + func requestUpload(_ targets: [PhotoItem], to target: String, skipAlreadySent: Bool? = nil, force: Bool = false) { + guard !targets.isEmpty, let variant = uploadVariant(target), let name = uploadTargetName(target) else { return } + let withFiles = targets.filter { !uploadFiles(for: $0, variant: variant).isEmpty } + let missing = targets.count - withFiles.count if missing > 0 { alert = AppAlert(title: "\(missing) Bild(er) ohne JPEG", message: "Für reine RAW-Dateien zuerst „Lightroom → JPEG exportieren“ (⌘⌥L) nutzen; mit automatischem Upload in den Lightroom-Einstellungen geht das in einem Schritt.") } - uploads.enqueue(files: files, target: target, sourceItems: targets) + guard !withFiles.isEmpty else { return } + let sentBefore = Set(withFiles.filter { sentLog.wasSent($0, to: target) }.map(\.id)) + let destination = settings.ftpDestinations.first { $0.id.uuidString == target } + let runCheck = !force && target != "immich" && (destination?.preflight ?? true) + var issues: [String: [PreflightIssue]] = [:] + if runCheck { + for t in withFiles { + let i = preflightIssues(for: t) + if !i.isEmpty { issues[t.id] = i } + } + } + let decided = skipAlreadySent != nil || sentBefore.isEmpty || force + if issues.isEmpty && decided { + let send = skipAlreadySent == true ? withFiles.filter { !sentBefore.contains($0.id) } : withFiles + if send.isEmpty { statusText = "Alle ausgewählten Bilder wurden schon an \(name) gesendet"; return } + enqueueUpload(send, target: target, variant: variant) + return + } + pendingUpload = PendingUpload(target: target, targetName: name, items: withFiles, issues: issues, alreadySent: sentBefore) + openWindow("check") + } + + /// Agentur-Check of one photo (current metadata). + func preflightIssues(for item: PhotoItem) -> [PreflightIssue] { + let cur = self.item(item.id) ?? item + let open = openSuggestions(for: cur.id).map { s -> String in + let name = s.replacement.map { JerseyLogic.personName(replacement: $0, columns: []) } ?? "" + return [s.code ?? "#\(s.number)", name].filter { !$0.isEmpty }.joined(separator: " ") + } + return Preflight.check(iptc: cur.iptc, exif: cur.exif, captureDate: cur.captureDate, codes: codes, + options: settings.preflight, openSuggestions: open) + } + + /// Check window: run the check again (after fixing captions in the IPTC window). + func recheckPendingUpload() { + guard var p = pendingUpload else { return } + p.items = p.items.map { item($0.id) ?? $0 } + var issues: [String: [PreflightIssue]] = [:] + let destination = settings.ftpDestinations.first { $0.id.uuidString == p.target } + if p.target != "immich" && (destination?.preflight ?? true) { + for t in p.items { let i = preflightIssues(for: t); if !i.isEmpty { issues[t.id] = i } } + } + p.issues = issues + p.alreadySent = Set(p.items.filter { sentLog.wasSent($0, to: p.target) }.map(\.id)) + pendingUpload = p + } + + /// Check window: send these photos. + func confirmPendingUpload(_ send: [PhotoItem]) { + guard let p = pendingUpload, let variant = uploadVariant(p.target) else { pendingUpload = nil; return } + pendingUpload = nil + guard !send.isEmpty else { return } + enqueueUpload(send.map { item($0.id) ?? $0 }, target: p.target, variant: variant) + } + + private func enqueueUpload(_ items: [PhotoItem], target: String, variant: UploadVariant) { + let files = items.flatMap { uploadFiles(for: $0, variant: variant) } + uploads.enqueue(files: files, target: target, sourceItems: items) + } + + // MARK: - Gesendet-Status + + func recordSent(file: URL, destination: String, destinationName: String, remoteName: String, size: Int64) { + sentLog.record(file, SentRecord(destination: destination, destinationName: destinationName, remoteName: remoteName, size: size)) + scheduleSentLogSave() + if filter.sent != .all { rebuildVisible() } + } + + func sentSummary(for item: PhotoItem) -> SentSummary? { sentLog.summary(for: item) } + + var sentCountInFolder: Int { items.filter { sentLog.wasSent($0) }.count } + + /// "Als nicht gesendet markieren" + func markNotSent(_ targets: [PhotoItem]) { + sentLog.clear(targets.flatMap { [$0.primary] + $0.companions }) + scheduleSentLogSave() + rebuildVisible() + statusText = "\(targets.count) Bild(er) als nicht gesendet markiert" + } + + private func scheduleSentLogSave() { + sentLogSaveTask?.cancel() + sentLogSaveTask = Task { [weak self] in + try? await Task.sleep(nanoseconds: 1_000_000_000) + guard !Task.isCancelled else { return } + self?.flushSentLog() + } + } + + func flushSentLog() { + Storage.save(sentLog, to: Storage.sentLogURL) + } + + // MARK: - Rückgängig / Wiederholen + + var undoTitle: String? { undoStack.last?.title } + var redoTitle: String? { redoStack.last?.title } + + private func pushUndo(_ e: UndoEntry) { + undoStack.append(e) + if undoStack.count > 100 { undoStack.removeFirst(undoStack.count - 100) } + redoStack.removeAll() + } + + /// ⌘Z: while typing in a text field the text is undone, otherwise the last metadata change. + func performUndo() { + if NSApp.keyWindow?.firstResponder is NSText { + _ = NSApp.sendAction(Selector(("undo:")), to: nil, from: nil) + } else { + undo() + } + } + + func performRedo() { + if NSApp.keyWindow?.firstResponder is NSText { + _ = NSApp.sendAction(Selector(("redo:")), to: nil, from: nil) + } else { + redo() + } + } + + func undo() { + guard let e = undoStack.popLast() else { statusText = "Nichts zum Rückgängigmachen"; return } + restore(e.before, kind: e.kind) + redoStack.append(e) + statusText = "Rückgängig: \(e.title)" + } + + func redo() { + guard let e = redoStack.popLast() else { statusText = "Nichts zum Wiederholen"; return } + restore(e.after, kind: e.kind) + undoStack.append(e) + statusText = "Wiederholt: \(e.title)" + } + + /// Puts photos back into a recorded state – in memory and on disk. + private func restore(_ snapshots: [PhotoItem], kind: UndoEntry.Kind) { + guard let w = writer else { return } + switch kind { + case .flags: + for s in snapshots { + if let i = indexByID[s.id] { items[i].rating = s.rating; items[i].label = s.label; items[i].tagged = s.tagged } + } + rebuildVisible() + let toWrite = snapshots.map { s -> PhotoItem in + guard var cur = item(s.id) else { return s } + cur.rating = s.rating; cur.label = s.label; cur.tagged = s.tagged + return cur + } + serialWrite { [weak self] in + for t in toWrite { do { try await w.writeState(of: t) } catch { self?.report(error) } } + } + case .iptc(let fields): + for s in snapshots { + guard let i = indexByID[s.id] else { continue } + for f in fields { + if f.kind == .list { items[i].iptc.lists[f.id] = s.iptc.lists[f.id] } else { items[i].iptc.text[f.id] = s.iptc.text[f.id] } + } + } + rebuildVisible() + serialWrite { [weak self] in + for s in snapshots { do { try await w.write(values: s.iptc, fields: fields, to: s) } catch { self?.report(error) } } + } + } } // MARK: - Jersey number recognition @@ -1165,9 +1431,9 @@ final class AppState: ObservableObject { var matchdayActive: Bool { settings.jersey.matchday && settings.jersey.teams.count >= 2 } - func team(forCode code: String) -> JerseyTeam? { + func team(forCode code: String, in teams: [JerseyTeam]? = nil) -> JerseyTeam? { let c = code.lowercased() - return settings.jersey.teams.first { t in + return (teams ?? settings.jersey.teams).first { t in let p = t.prefix.lowercased() return !p.isEmpty && c.hasPrefix(p) && c.dropFirst(p.count).allSatisfy(\.isNumber) } @@ -1175,14 +1441,16 @@ final class AppState: ObservableObject { /// Main player of an image: accepted suggestion / "Persons shown" first, else the top open suggestion. func playerInfo(for item: PhotoItem) -> PlayerInfo? { + let teamsOfPhoto = teams(for: item) if let name = item.iptc.lists["personInImage"]?.first { let code = personIndex[name] let number = code.flatMap { c in Int(c.drop { !$0.isNumber }) } - return PlayerInfo(name: name, number: number, team: code.flatMap { team(forCode: $0) }, confirmed: true) + return PlayerInfo(name: name, number: number, team: code.flatMap { team(forCode: $0, in: teamsOfPhoto) }, confirmed: true) } if let s = openSuggestions(for: item.id).first, let rep = s.replacement { let name = JerseyLogic.personName(replacement: rep, columns: codes.table[(s.code ?? "").lowercased()] ?? []) - return PlayerInfo(name: name, number: s.number, team: settings.jersey.teams.first { $0.id == s.teamID }, confirmed: false) + let team = (teamsOfPhoto + settings.jersey.teams).first { $0.id == s.teamID } + return PlayerInfo(name: name, number: s.number, team: team, confirmed: false) } return nil } @@ -1217,4 +1485,110 @@ final class AppState: ObservableObject { filter.team = id; filter.person = nil; filter.withoutPlayer = false } + + // MARK: - Spieltag + + struct SpieltagOptions { + var setIngest = true + var setJersey = true + var onlyTheseCodes = true + var matchday = true + var applyToSelection = false + } + + /// Jersey recognition teams of a match (kit colors from the team profiles; id = profile id, so + /// suggestions stay valid when the teams are set up again later). + func jerseyTeams(for m: MatchPlan) -> [JerseyTeam] { + var out: [JerseyTeam] = [] + for (pid, home) in [(m.homeID, true), (m.awayID, false)] { + guard let p = spieltag.team(pid) else { continue } + let kit = home ? (p.homeKit ?? p.awayKit) : (p.awayKit ?? p.homeKit) + let fallback = home ? KitColor(r: 0.1, g: 0.45, b: 0.25) : KitColor(r: 0.95, g: 0.95, b: 0.95) + var t = JerseyTeam(id: p.id, name: p.name, codeSetID: p.codeSetID, prefix: p.codePrefix, + shirtColor: kit?.shirt ?? fallback, shortsColor: kit?.shorts) + t.profileID = p.id + t.isHome = home + out.append(t) + } + return out + } + + /// Teams of the match a photo belongs to (IPTC "Event" of a created Spieltag), else the current teams. + func teams(for item: PhotoItem?) -> [JerseyTeam] { + if let e = item?.iptc.text["event"], let m = spieltag.match(forEvent: e) { + let t = jerseyTeams(for: m) + if t.count == 2 { return t } + } + return settings.jersey.teams + } + + /// Kit colors picked in the jersey setup are remembered in the team profile (home or away kit). + private func syncKitsToProfiles() { + var lib = spieltag + var changed = false + for t in settings.jersey.teams { + guard let pid = t.profileID, let i = lib.teams.firstIndex(where: { $0.id == pid }) else { continue } + let kit = Kit(shirt: t.shirtColor, shorts: t.shortsColor) + if t.isHome == false { + if lib.teams[i].awayKit != kit { lib.teams[i].awayKit = kit; changed = true } + } else if lib.teams[i].homeKit != kit { + lib.teams[i].homeKit = kit; changed = true + } + } + if changed { spieltag = lib } + } + + /// Creates (or updates) the match: IPTC template from the base template + patterns, ingest folder name, + /// jersey teams, active code teams. + @discardableResult + func createSpieltag(_ plan: MatchPlan, options: SpieltagOptions) -> IPTCTemplate? { + guard let home = spieltag.team(plan.homeID), let away = spieltag.team(plan.awayID) else { return nil } + let comp = spieltag.competition(plan.competitionID) + let base = templates.first { $0.id == plan.baseTemplateID } + var m = plan + // same match again (same teams, same day) → update it instead of adding a second template + if let old = spieltag.matches.first(where: { $0.homeID == m.homeID && $0.awayID == m.awayID + && Calendar.current.isDate($0.date, inSameDayAs: m.date) }) { + m.id = old.id + m.templateID = old.templateID + m.created = old.created + } + let ctx = SpieltagGenerator.context(match: m, home: home, away: away, competition: comp, patterns: spieltag.patterns) + let template = SpieltagGenerator.makeTemplate(match: m, home: home, away: away, competition: comp, + patterns: spieltag.patterns, base: base) + m.templateID = template.id + m.event = template.values.text["event"] ?? "" + m.folderName = SpieltagGenerator.folderName(patterns: spieltag.patterns, ctx: ctx) + + if let i = templates.firstIndex(where: { $0.id == template.id }) { templates[i] = template } else { templates.append(template) } + settings.lastTemplateID = template.id + + var lib = spieltag + if let i = lib.matches.firstIndex(where: { $0.id == m.id }) { lib.matches[i] = m } else { lib.matches.append(m) } + lib.lastBaseTemplateID = plan.baseTemplateID + lib.lastCompetitionID = plan.competitionID + spieltag = lib + + if options.setIngest { + settings.ingest.folderPattern = m.folderName + settings.ingest.templateID = template.id + settings.ingest.applyTemplate = true + } + if options.setJersey { + settings.jersey.teams = jerseyTeams(for: m) + if options.matchday { settings.jersey.matchday = true } + } + if options.onlyTheseCodes { + let ids = Set([home.codeSetID, away.codeSetID].compactMap { $0 }) + if !ids.isEmpty { + var cl = codeLibrary + for i in cl.sets.indices { cl.sets[i].enabled = ids.contains(cl.sets[i].id) } + codeLibrary = cl + } + } + if options.applyToSelection, !selectedItems.isEmpty { applyTemplate(template, to: selectedItems) } + statusText = "Spieltag angelegt: \(home.name) – \(away.name) · Vorlage „\(template.name)“" + return template + } + } diff --git a/Sources/Lichtkasten/Services/Persistence.swift b/Sources/Lichtkasten/Services/Persistence.swift index 9d32809..208b62f 100644 --- a/Sources/Lichtkasten/Services/Persistence.swift +++ b/Sources/Lichtkasten/Services/Persistence.swift @@ -117,6 +117,8 @@ struct AppSettings: Codable { /// PM ▾ drop-down lists per IPTC field (imported from PM + recently used values) var fieldLists: [String: [String]] = [:] var jersey = JerseySettings() + /// Agentur-Check rules + var preflight = PreflightOptions() init() {} @@ -142,6 +144,7 @@ struct AppSettings: Codable { lastTemplateID = try? c.decode(UUID.self, forKey: .lastTemplateID) fieldLists = (try? c.decode([String: [String]].self, forKey: .fieldLists)) ?? [:] jersey = (try? c.decode(JerseySettings.self, forKey: .jersey)) ?? JerseySettings() + preflight = (try? c.decode(PreflightOptions.self, forKey: .preflight)) ?? PreflightOptions() } } @@ -156,6 +159,8 @@ enum Storage { static var templatesURL: URL { appSupport.appendingPathComponent("templates.json") } static var codesURL: URL { appSupport.appendingPathComponent("codes.json") } static var codeLibraryURL: URL { appSupport.appendingPathComponent("codelibrary.json") } + static var sentLogURL: URL { appSupport.appendingPathComponent("sent-log.json") } + static var spieltagURL: URL { appSupport.appendingPathComponent("spieltag.json") } static func load(_ type: T.Type, from url: URL) -> T? { guard let d = try? Data(contentsOf: url) else { return nil } diff --git a/Sources/Lichtkasten/Services/UploadQueue.swift b/Sources/Lichtkasten/Services/UploadQueue.swift index ac597ad..3265a93 100644 --- a/Sources/Lichtkasten/Services/UploadQueue.swift +++ b/Sources/Lichtkasten/Services/UploadQueue.swift @@ -198,6 +198,8 @@ final class UploadQueue: ObservableObject { 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 { @@ -205,6 +207,8 @@ final class UploadQueue: ObservableObject { } 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 { diff --git a/Sources/Lichtkasten/Views/ContactSheetView.swift b/Sources/Lichtkasten/Views/ContactSheetView.swift index 62f71c3..549d2c4 100644 --- a/Sources/Lichtkasten/Views/ContactSheetView.swift +++ b/Sources/Lichtkasten/Views/ContactSheetView.swift @@ -19,6 +19,7 @@ struct ContactSheetView: View { imageURL: state.previewURL(for: item), badge: state.suggestionBadge(for: item.id), player: state.matchdayActive ? state.playerInfo(for: item) : nil, + sent: state.sentSummary(for: item), onTagClick: { tagClick(item) }) .equatable() .id(item.id) @@ -89,6 +90,12 @@ struct ItemContextMenu: View { ensureSelected() state.recognizeJerseys(state.selectedItems, onlyNew: false) } + if state.sentSummary(for: item) != nil { + Button("Als nicht gesendet markieren") { + ensureSelected() + state.markNotSent(state.selectedItems) + } + } Button("Als Vorlage übernehmen") { state.templates.append(IPTCTemplate(name: item.baseName, values: item.iptc)) } @@ -111,11 +118,13 @@ struct ThumbnailCell: View, Equatable { let badge: String? /// Matchday: main player (team color edge + big number) let player: AppState.PlayerInfo? + /// upload history ("Gesendet") + let sent: SentSummary? let onTagClick: () -> Void @State private var image: NSImage? static func == (a: ThumbnailCell, b: ThumbnailCell) -> Bool { - a.item == b.item && a.size == b.size && a.selected == b.selected && a.isCursor == b.isCursor && a.imageURL == b.imageURL && a.badge == b.badge && a.player == b.player + a.item == b.item && a.size == b.size && a.selected == b.selected && a.isCursor == b.isCursor && a.imageURL == b.imageURL && a.badge == b.badge && a.player == b.player && a.sent == b.sent } private static let timeFormatter: DateFormatter = { @@ -168,6 +177,20 @@ struct ThumbnailCell: View, Equatable { .buttonStyle(.plain) .help("Tag (T)") } + // 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)) } + } + .foregroundStyle(LK.onAmber) + .padding(.horizontal, 6).frame(height: 18) + .background(Capsule().fill(LK.green)) + .padding(8) + .help(sent.tooltip) + } + } // open player suggestion .overlay(alignment: .bottomTrailing) { if let badge { diff --git a/Sources/Lichtkasten/Views/ContentView.swift b/Sources/Lichtkasten/Views/ContentView.swift index e0182cf..5931c92 100644 --- a/Sources/Lichtkasten/Views/ContentView.swift +++ b/Sources/Lichtkasten/Views/ContentView.swift @@ -47,6 +47,9 @@ struct ContentView: View { .sheet(isPresented: $state.showIngest) { IngestView() } .sheet(isPresented: $state.showPMImport) { PMImportSheet() } .sheet(isPresented: $state.showJerseySetup) { JerseySetupView() } + .sheet(isPresented: $state.showSpieltag) { + SpieltagView().environmentObject(state).groupBoxStyle(LKGroupBoxStyle()) + } .alert(item: $state.alert) { a in Alert(title: Text(a.title), message: Text(a.message), dismissButton: .default(Text("OK"))) } @@ -178,6 +181,23 @@ struct ContactSheetHeader: View { .buttonStyle(.plain) .help("Nur Bilder mit offenen Spieler-Vorschlägen") + Menu { + Picker("Gesendet", selection: $state.filter.sent) { + ForEach(SentFilter.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + .pickerStyle(.inline) + } label: { + Label(state.filter.sent == .all ? "Gesendet" : state.filter.sent.rawValue, systemImage: "paperplane") + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(state.filter.sent == .all ? LK.text2 : LK.onAmber) + .padding(.horizontal, 10).frame(height: 28) + .background(RoundedRectangle(cornerRadius: 8).fill(state.filter.sent == .all ? LK.raised : LK.amber)) + } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .fixedSize() + .help("Nach Upload-Status filtern") + Menu { Picker("Sortierung", selection: $state.sortOrder) { ForEach(SortOrder.allCases, id: \.self) { Text($0.rawValue).tag($0) } @@ -286,7 +306,8 @@ struct PMStatusBar: View { private var summary: String { let sel = state.selectedItems.count let size = ByteCountFormatter.string(fromByteCount: state.selectedBytes, countStyle: .file) - var parts = ["Ausgewählt \(sel) von \(state.visible.count) (\(size))", "\(state.items.count) gesamt"] + var parts = ["Ausgewählt \(sel) von \(state.visible.count) (\(size))", "\(state.items.count) gesamt", + "\(state.sentCountInFolder) gesendet"] if state.filter.isActive { parts.append("Filter aktiv") } if let c = state.cursorItem { parts.append(c.primary.path) } return parts.joined(separator: " | ") diff --git a/Sources/Lichtkasten/Views/IPTCInfoWindow.swift b/Sources/Lichtkasten/Views/IPTCInfoWindow.swift index 5b893fa..def3cea 100644 --- a/Sources/Lichtkasten/Views/IPTCInfoWindow.swift +++ b/Sources/Lichtkasten/Views/IPTCInfoWindow.swift @@ -200,6 +200,7 @@ struct IPTCInfoWindow: View { Text(positionText).foregroundStyle(.secondary).font(.caption) } .font(.callout) + SentStatusLine(summary: state.sentSummary(for: item)) } Grid(horizontalSpacing: 8, verticalSpacing: 8) { diff --git a/Sources/Lichtkasten/Views/IngestView.swift b/Sources/Lichtkasten/Views/IngestView.swift index dd9050c..1ffa796 100644 --- a/Sources/Lichtkasten/Views/IngestView.swift +++ b/Sources/Lichtkasten/Views/IngestView.swift @@ -20,6 +20,7 @@ struct IngestView: View { @State private var cards: [Card] = [] @State private var selectedCards: Set = [] @State private var folders: [URL] = [] + @State private var showSpieltag = false private var ingest: Binding { $state.settings.ingest } @@ -41,6 +42,9 @@ struct IngestView: View { pathPreview HStack { Button("Variablen …") { state.openWindow("codes") }.buttonStyle(LKButtonStyle()) + Button { showSpieltag = true } label: { Label("Spieltag …", systemImage: "sportscourt") } + .buttonStyle(LKButtonStyle()) + .help("Spieltag-Assistent: setzt Ordnername, Vorlage, Trikot-Teams und Codes für das nächste Spiel") Spacer() Button("Abbrechen") { state.pendingIngestSources = []; dismiss() } .buttonStyle(LKButtonStyle()) @@ -58,6 +62,9 @@ struct IngestView: View { .padding(18) .frame(width: 980) .background(LK.ground) + .sheet(isPresented: $showSpieltag) { + SpieltagView().environmentObject(state).groupBoxStyle(LKGroupBoxStyle()) + } .onAppear(perform: setup) } @@ -128,6 +135,11 @@ struct IngestView: View { TextField("{day0}.{month0}.{year4} - Ereignis", text: ingest.folderPattern) .textFieldStyle(.roundedBorder) } + if let m = state.spieltag.matches.last(where: { $0.folderName == state.settings.ingest.folderPattern }), + let h = state.spieltag.team(m.homeID), let a = state.spieltag.team(m.awayID) { + Label("Spieltag \(h.name) – \(a.name)", systemImage: "sportscourt") + .font(.caption).foregroundStyle(LK.amber) + } } .padding(6) } diff --git a/Sources/Lichtkasten/Views/LoupeInspector.swift b/Sources/Lichtkasten/Views/LoupeInspector.swift index fa5144b..6fa757e 100644 --- a/Sources/Lichtkasten/Views/LoupeInspector.swift +++ b/Sources/Lichtkasten/Views/LoupeInspector.swift @@ -101,6 +101,7 @@ struct LoupeInspector: View { .buttonStyle(.plain) .help("Tag (T)") } + SentStatusLine(summary: state.sentSummary(for: item)) } } .padding(18) diff --git a/Sources/Lichtkasten/Views/MatchdayViews.swift b/Sources/Lichtkasten/Views/MatchdayViews.swift index af58c17..d494acc 100644 --- a/Sources/Lichtkasten/Views/MatchdayViews.swift +++ b/Sources/Lichtkasten/Views/MatchdayViews.swift @@ -7,7 +7,8 @@ struct MatchdayHeader: View { @EnvironmentObject var state: AppState var body: some View { - let teams = state.settings.jersey.teams + // teams of the game the current photo belongs to (SENT holds several games) + let teams = state.teams(for: state.cursorItem) let info = state.matchdayEvent VStack(spacing: 0) { HStack(spacing: 24) { @@ -46,6 +47,8 @@ struct MatchdayHeader: View { chip("✕ " + p, on: true) { state.filter.person = nil } } Spacer() + Button("Spieltag …") { state.showSpieltag = true } + .buttonStyle(LKButtonStyle(compact: true)) Button("Trikot-Erkennung …") { state.showJerseySetup = true } .buttonStyle(LKButtonStyle(compact: true)) Button("Nummern erkennen ⌘⇧J") { state.recognizeJerseys() } @@ -85,6 +88,7 @@ struct MatchdayHeader: View { let open = state.items.filter { !state.openSuggestions(for: $0.id).isEmpty }.count return HStack(spacing: 18) { counter(tagged, "GETAGGT", highlight: true) + counter(state.sentCountInFolder, "GESENDET") counter(withPlayer, "MIT SPIELER:IN") counter(open, "OFFEN") } diff --git a/Sources/Lichtkasten/Views/PreflightWindow.swift b/Sources/Lichtkasten/Views/PreflightWindow.swift new file mode 100644 index 0000000..4bc0bd7 --- /dev/null +++ b/Sources/Lichtkasten/Views/PreflightWindow.swift @@ -0,0 +1,190 @@ +import SwiftUI +import LichtkastenCore + +/// Agentur-Check: shown before an upload when something is wrong or photos were sent before. +/// Errors (red) are excluded by "Nur fehlerfreie senden", warnings (amber) don't block. +struct PreflightWindow: View { + @EnvironmentObject var state: AppState + @Environment(\.dismissWindow) private var dismissWindow + @State private var skipSent = true + @State private var showOK = false + + var body: some View { + Group { + if let p = state.pendingUpload { + content(p) + } else { + VStack(spacing: 12) { + Image(systemName: "checkmark.shield").font(.system(size: 40)).foregroundStyle(LK.green) + Text("Kein Upload wartet auf eine Prüfung.").foregroundStyle(LK.text2) + Button("Schließen") { dismissWindow(id: "check") }.buttonStyle(LKButtonStyle()) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + .frame(minWidth: 760, minHeight: 520) + .background(LK.ground) + } + + // MARK: Content + + private func content(_ p: PendingUpload) -> some View { + let problem = p.items.filter { !(p.issues[$0.id] ?? []).isEmpty || p.alreadySent.contains($0.id) } + let ok = p.items.filter { (p.issues[$0.id] ?? []).isEmpty && !p.alreadySent.contains($0.id) } + let sendable = toSend(p, errorFree: true) + let all = toSend(p, errorFree: false) + + return VStack(spacing: 0) { + // header + HStack(spacing: 14) { + Image(systemName: p.errorItems > 0 ? "exclamationmark.shield.fill" : "checkmark.shield.fill") + .font(.system(size: 22)) + .foregroundStyle(p.errorItems > 0 ? LK.red : LK.amber) + .frame(width: 44, height: 44) + .background(RoundedRectangle(cornerRadius: 11).fill(LK.raised)) + VStack(alignment: .leading, spacing: 3) { + Text("Agentur-Check · \(p.targetName)").font(.system(size: 18, weight: .bold)).foregroundStyle(LK.text) + HStack(spacing: 12) { + chip("\(p.items.count) Bild(er)", LK.text2) + if p.errorItems > 0 { chip("\(p.errorItems) mit Fehlern", LK.red) } + if p.warningItems > 0 { chip("\(p.warningItems) mit Hinweisen", LK.amber) } + if !p.alreadySent.isEmpty { chip("\(p.alreadySent.count) schon gesendet", LK.green) } + } + } + Spacer() + Button("Erneut prüfen") { state.recheckPendingUpload() } + .buttonStyle(LKButtonStyle(compact: true)) + .help("Nach Korrekturen im IPTC-Fenster neu prüfen") + } + .padding(20) + + Rectangle().fill(LK.border).frame(height: 1) + + ScrollView { + VStack(alignment: .leading, spacing: 10) { + if !p.alreadySent.isEmpty { + Toggle(isOn: $skipSent) { + Text("Bereits an \(p.targetName) gesendete Bilder überspringen (\(p.alreadySent.count))") + .font(.system(size: 13, weight: .semibold)) + } + .toggleStyle(.checkbox) + .padding(.bottom, 4) + } + ForEach(problem) { item in row(item, p) } + if !ok.isEmpty { + DisclosureGroup(isExpanded: $showOK) { + VStack(alignment: .leading, spacing: 6) { + ForEach(ok) { item in + Text(item.filename).font(LK.mono(12)).foregroundStyle(LK.text2) + } + } + .padding(.top, 6) + } label: { + Label("\(ok.count) Bild(er) ohne Befund", systemImage: "checkmark.circle.fill") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(LK.green) + } + .padding(12) + .background(RoundedRectangle(cornerRadius: 10).fill(LK.card)) + } + } + .padding(20) + } + + Rectangle().fill(LK.border).frame(height: 1) + HStack(spacing: 10) { + Button("Abbrechen") { + state.pendingUpload = nil + dismissWindow(id: "check") + } + .buttonStyle(LKButtonStyle()) + .keyboardShortcut(.cancelAction) + Spacer() + if all.count != sendable.count { + Button("Alle senden (\(all.count))") { send(all) } + .buttonStyle(LKButtonStyle()) + .disabled(all.isEmpty) + .help("Auch Bilder mit Fehlern senden") + } + Button(p.errorItems > 0 ? "Nur fehlerfreie senden (\(sendable.count))" : "Senden (\(sendable.count))") { send(sendable) } + .buttonStyle(LKButtonStyle(primary: true)) + .keyboardShortcut(.defaultAction) + .disabled(sendable.isEmpty) + } + .padding(16) + } + } + + private func toSend(_ p: PendingUpload, errorFree: Bool) -> [PhotoItem] { + p.items.filter { item in + if skipSent && p.alreadySent.contains(item.id) { return false } + if errorFree && p.hasError(item.id) { return false } + return true + } + } + + private func send(_ items: [PhotoItem]) { + state.confirmPendingUpload(items) + state.openWindow("tasks") + dismissWindow(id: "check") + } + + // MARK: Row per photo + + private func row(_ item: PhotoItem, _ p: PendingUpload) -> some View { + let issues = p.issues[item.id] ?? [] + return HStack(alignment: .top, spacing: 12) { + PreflightThumb(url: state.previewURL(for: item)) + VStack(alignment: .leading, spacing: 5) { + HStack { + Text(item.filename).font(LK.mono(12, .semibold)).foregroundStyle(LK.text) + if p.alreadySent.contains(item.id), let s = state.sentSummary(for: item) { + Label(s.tooltip, systemImage: "paperplane.fill") + .font(.system(size: 11)).foregroundStyle(LK.green).lineLimit(1) + } + } + ForEach(issues) { i in + HStack(alignment: .top, spacing: 6) { + Image(systemName: i.severity == .error ? "xmark.octagon.fill" : "exclamationmark.triangle.fill") + .font(.system(size: 11)) + .foregroundStyle(i.severity == .error ? LK.red : LK.amber) + Text(i.message).font(.system(size: 12)).foregroundStyle(LK.text) + } + } + } + Spacer() + Button("Bearbeiten") { + state.cursorID = item.id + state.selection = [item.id] + state.openWindow("iptc") + } + .buttonStyle(LKButtonStyle(compact: true)) + .help("Im IPTC-Fenster öffnen – danach „Erneut prüfen“") + } + .padding(12) + .background(RoundedRectangle(cornerRadius: 10).fill(LK.card)) + .overlay(RoundedRectangle(cornerRadius: 10).stroke(p.hasError(item.id) ? LK.red.opacity(0.5) : LK.border)) + } + + private func chip(_ text: String, _ color: Color) -> some View { + Text(text).font(.system(size: 11, weight: .bold)).foregroundStyle(color) + } +} + +struct PreflightThumb: View { + let url: URL + @State private var image: NSImage? + + var body: some View { + ZStack { + RoundedRectangle(cornerRadius: 6).fill(LK.deep) + if let image { Image(nsImage: image).resizable().scaledToFill() } + } + .frame(width: 84, height: 56) + .clipShape(RoundedRectangle(cornerRadius: 6)) + .task(id: url) { + image = ImageLoader.shared.cachedThumbnail(url) + if image == nil { image = await ImageLoader.shared.thumbnail(for: url) } + } + } +} diff --git a/Sources/Lichtkasten/Views/SettingsView.swift b/Sources/Lichtkasten/Views/SettingsView.swift index 00c7fb2..2d28292 100644 --- a/Sources/Lichtkasten/Views/SettingsView.swift +++ b/Sources/Lichtkasten/Views/SettingsView.swift @@ -4,12 +4,13 @@ import LichtkastenCore /// Own settings navigation (Apple's settings tab bar always uses the system accent color). struct SettingsView: View { enum Page: String, CaseIterable, Identifiable { - case general = "Allgemein", ftp = "FTP", immich = "Immich", lightroom = "Lightroom", codes = "Codes" + case general = "Allgemein", ftp = "FTP", check = "Agentur-Check", immich = "Immich", lightroom = "Lightroom", codes = "Codes" var id: String { rawValue } var icon: String { switch self { case .general: return "gearshape" case .ftp: return "server.rack" + case .check: return "checkmark.shield" case .immich: return "photo.stack" case .lightroom: return "camera.aperture" case .codes: return "character.textbox" @@ -49,6 +50,7 @@ struct SettingsView: View { switch page { case .general: GeneralSettings() case .ftp: FTPSettings() + case .check: PreflightSettings() case .immich: ImmichSettingsView() case .lightroom: LightroomSettingsView() case .codes: CodesSettings() @@ -349,3 +351,53 @@ struct CodesSettings: View { .lkForm() } } + +/// Agentur-Check rules (applied before uploads to FTP servers with the check switched on). +struct PreflightSettings: View { + @EnvironmentObject var state: AppState + + /// fields offered as "Pflichtfeld" + private static let candidates = ["caption", "headline", "creator", "copyright", "credit", "source", "event", + "city", "sublocation", "state", "country", "countryCode", "dateCreated", + "keywords", "objectName", "captionWriter"] + + private var opts: Binding { $state.settings.preflight } + + var body: some View { + Form { + Section("Pflichtfelder (Fehler, wenn leer)") { + LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())], alignment: .leading, spacing: 8) { + ForEach(Self.candidates, id: \.self) { id in + if let f = IPTCField.byID[id] { + Toggle(f.label, isOn: Binding( + get: { state.settings.preflight.requiredFields.contains(id) }, + set: { on in + state.settings.preflight.requiredFields.removeAll { $0 == id } + if on { state.settings.preflight.requiredFields.append(id) } + })) + .toggleStyle(.checkbox) + } + } + } + }.lkRow() + Section("Weitere Prüfungen (Hinweise)") { + Toggle("Erste Zeile der Beschreibung leer (Person vergessen?)", isOn: opts.warnEmptyFirstLine) + Toggle("Datum in Überschrift/Beschreibung passt nicht zum Aufnahmedatum (alte Vorlage?)", isOn: opts.checkDates) + Toggle("Felder länger als das IPTC-Limit (Agentur kürzt)", isOn: opts.checkLengths) + Toggle("Offene Spieler-Vorschläge (Trikotnummern)", isOn: opts.checkOpenSuggestions) + Text("Immer geprüft: nicht ersetzte Variablen wie {city} und Codes wie .w10. – das sind Fehler.") + .font(.caption).foregroundStyle(.secondary) + }.lkRow() + Section("Bildgröße") { + TextField("Mindestens lange Kante in px (0 = aus)", value: opts.minLongEdge, format: .number.grouping(.never)) + }.lkRow() + Section("Pro Server") { + ForEach(state.settings.ftpDestinations.indices, id: \.self) { i in + Toggle("Agentur-Check für „\(state.settings.ftpDestinations[i].name)“", isOn: $state.settings.ftpDestinations[i].preflight) + } + Text("Immich wird nicht geprüft (persönliches Archiv).").font(.caption).foregroundStyle(.secondary) + }.lkRow() + } + .lkForm() + } +} diff --git a/Sources/Lichtkasten/Views/SpieltagView.swift b/Sources/Lichtkasten/Views/SpieltagView.swift new file mode 100644 index 0000000..0d2a140 --- /dev/null +++ b/Sources/Lichtkasten/Views/SpieltagView.swift @@ -0,0 +1,544 @@ +import SwiftUI +import LichtkastenCore + +/// Spieltag-Assistent: pick home, away, competition and date – Lichtkasten builds the IPTC template in the +/// structure of the base template (headline, event, caption, place, keywords), sets the ingest folder name, +/// the jersey teams and the active code teams. Teams and competitions are remembered. +struct SpieltagView: View { + @EnvironmentObject var state: AppState + @Environment(\.dismiss) private var dismiss + + @State private var homeID: UUID? + @State private var awayID: UUID? + @State private var competitionID: UUID? + @State private var round = "" + @State private var date = Date() + @State private var venue = Venue() + @State private var venueFollowsHome = true + @State private var baseTemplateID: UUID? + @State private var extraKeywords = "" + @State private var options = AppState.SpieltagOptions() + @State private var showPatterns = false + @State private var editHome = false + @State private var editAway = false + @State private var editCompetition = false + + private var home: TeamProfile? { state.spieltag.team(homeID) } + private var away: TeamProfile? { state.spieltag.team(awayID) } + private var competition: Competition? { state.spieltag.competition(competitionID) } + private var baseTemplate: IPTCTemplate? { state.templates.first { $0.id == baseTemplateID } } + + /// Home stadium (always the current version of the home profile) or the venue typed for this match. + private var effectiveVenue: Venue { venueFollowsHome ? (home?.venue ?? venue) : venue } + + private var plan: MatchPlan { + MatchPlan(homeID: homeID ?? UUID(), awayID: awayID ?? UUID(), competitionID: competitionID, round: round, + date: date, venue: effectiveVenue, extraKeywords: extraKeywords, baseTemplateID: baseTemplateID) + } + + private var preview: IPTCTemplate? { + guard let home, let away else { return nil } + return SpieltagGenerator.makeTemplate(match: plan, home: home, away: away, competition: competition, + patterns: state.spieltag.patterns, base: baseTemplate) + } + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 14) { + Image(systemName: "sportscourt") + .font(.system(size: 20, weight: .semibold)) + .foregroundStyle(LK.onAmber) + .frame(width: 42, height: 42) + .background(RoundedRectangle(cornerRadius: 11).fill(LK.amber)) + VStack(alignment: .leading, spacing: 2) { + Text("Neuer Spieltag").font(.system(size: 18, weight: .bold)).foregroundStyle(LK.text) + Text("Vorlage, Ingest-Ordner, Trikot-Erkennung und Codes in einem Schritt") + .font(.system(size: 12)).foregroundStyle(LK.text2) + } + Spacer() + } + .padding(20) + Rectangle().fill(LK.border).frame(height: 1) + + HStack(alignment: .top, spacing: 0) { + ScrollView { form.padding(20) } + .frame(width: 600) + Rectangle().fill(LK.border).frame(width: 1) + ScrollView { previewColumn.padding(20) } + .frame(maxWidth: .infinity) + .background(LK.panel) + } + + Rectangle().fill(LK.border).frame(height: 1) + HStack { + VStack(alignment: .leading, spacing: 3) { + ForEach(warnings, id: \.self) { w in + Label(w, systemImage: "exclamationmark.triangle.fill").font(.system(size: 12)).foregroundStyle(LK.amber) + } + } + Spacer() + Button("Abbrechen") { dismiss() } + .buttonStyle(LKButtonStyle()) + .keyboardShortcut(.cancelAction) + // ⌘↩ instead of plain Return: Return in one of the many text fields must not create the match + Button("Spieltag anlegen") { + state.createSpieltag(plan, options: options) + dismiss() + } + .buttonStyle(LKButtonStyle(primary: true)) + .keyboardShortcut(.return, modifiers: .command) + .help("⌘↩") + .disabled(home == nil || away == nil || homeID == awayID) + } + .padding(16) + } + .frame(width: 1100, height: 740) + .background(LK.ground) + .onAppear(perform: setup) + } + + private var warnings: [String] { + var w: [String] = [] + if let h = home, let a = away { + if h.id == a.id { w.append("Heim und Gast sind dasselbe Team") } + if !h.codePrefix.isEmpty && h.codePrefix.lowercased() == a.codePrefix.lowercased() { + w.append("Beide Teams haben das Code-Präfix „\(h.codePrefix)“") + } + if h.codePrefix.isEmpty || a.codePrefix.isEmpty { w.append("Ohne Code-Präfix keine Trikot-Erkennung") } + } + if competition == nil { w.append("Kein Wettbewerb gewählt") } + return w + } + + // MARK: Form + + private var form: some View { + VStack(alignment: .leading, spacing: 16) { + GroupBox("Spiel") { + VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 10) { + teamPicker("Heim", $homeID, edit: $editHome) + Text("vs.").font(.system(size: 13, weight: .bold)).foregroundStyle(LK.muted) + teamPicker("Gast", $awayID, edit: $editAway) + } + HStack(spacing: 6) { + Picker("Wettbewerb", selection: $competitionID) { + Text("– wählen –").tag(UUID?.none) + ForEach(state.spieltag.competitions) { c in Text(c.name).tag(UUID?.some(c.id)) } + } + Button { newCompetition() } label: { Image(systemName: "plus") } + .buttonStyle(.borderless) + .help("Neuen Wettbewerb anlegen") + } + HStack(spacing: 12) { + TextField("Runde / Spieltag (z. B. Achtelfinale, 8. Spieltag)", text: $round) + .textFieldStyle(.roundedBorder) + DatePicker("Datum", selection: $date, displayedComponents: .date) + .fixedSize() + } + Picker("Basis-Vorlage", selection: $baseTemplateID) { + Text("– keine –").tag(UUID?.none) + ForEach(state.templates.filter { !$0.name.hasPrefix("Spieltag ") }) { t in + Text(t.name).tag(UUID?.some(t.id)) + } + } + Text("Aus der Basis-Vorlage kommen Fotograf, Copyright, Datum-Einstellung und welche Felder angewendet werden. Überschrift, Ereignis, Beschreibung, Ort und Stichwörter baut der Assistent.") + .font(.caption).foregroundStyle(LK.muted) + } + } + + if let b = teamBinding(homeID) { + DisclosureGroup(isExpanded: $editHome) { teamEditor(b) } label: { editorLabel("Heim", b.wrappedValue.name) } + .padding(12).background(RoundedRectangle(cornerRadius: 12).fill(LK.card)) + } + if let b = teamBinding(awayID) { + DisclosureGroup(isExpanded: $editAway) { teamEditor(b) } label: { editorLabel("Gast", b.wrappedValue.name) } + .padding(12).background(RoundedRectangle(cornerRadius: 12).fill(LK.card)) + } + if let b = competitionBinding(competitionID) { + DisclosureGroup(isExpanded: $editCompetition) { competitionEditor(b) } label: { editorLabel("Wettbewerb", b.wrappedValue.name) } + .padding(12).background(RoundedRectangle(cornerRadius: 12).fill(LK.card)) + } + + GroupBox("Spielort") { + VStack(alignment: .leading, spacing: 8) { + Toggle("Heimstadion des Heimteams", isOn: $venueFollowsHome) + .toggleStyle(.checkbox) + .onChange(of: venueFollowsHome) { _, on in + // switching to a different venue starts from the home stadium + if !on, let h = home, venue.isEmpty { venue = h.venue } + } + if venueFollowsHome { + Text(venueSummary(effectiveVenue)) + .font(.system(size: 12)).foregroundStyle(LK.text2) + } else { + venueFields($venue) + } + } + } + + GroupBox("Nur für dieses Spiel") { + TextField("Zusätzliche Stichwörter, komma-getrennt (z. B. Heimspiel, ZDF)", text: $extraKeywords) + .textFieldStyle(.roundedBorder) + } + + GroupBox("Danach") { + VStack(alignment: .leading, spacing: 6) { + Toggle("Ingest: Ordnername und Vorlage setzen", isOn: $options.setIngest) + Toggle("Trikot-Erkennung mit beiden Teams einrichten", isOn: $options.setJersey) + Toggle("Matchday-Ansicht einschalten", isOn: $options.matchday).disabled(!options.setJersey) + Toggle("Nur die Code-Teams dieser beiden Mannschaften aktivieren", isOn: $options.onlyTheseCodes) + if !state.selectedItems.isEmpty { + Toggle("Vorlage gleich auf \(state.selectedItems.count) ausgewählte(s) Bild(er) anwenden", isOn: $options.applyToSelection) + } + } + .toggleStyle(.checkbox) + } + + DisclosureGroup(isExpanded: $showPatterns) { patternEditor } label: { + Text("Aufbau der IPTC-Felder (Muster)").font(.system(size: 13, weight: .semibold)).foregroundStyle(LK.text) + } + .padding(12).background(RoundedRectangle(cornerRadius: 12).fill(LK.card)) + } + } + + private func editorLabel(_ role: String, _ name: String) -> some View { + HStack(spacing: 8) { + Text(role.uppercased()).font(.system(size: 11, weight: .bold)).tracking(1.2).foregroundStyle(LK.amber) + Text(name).font(.system(size: 13, weight: .semibold)).foregroundStyle(LK.text) + Text("bearbeiten").font(.system(size: 11)).foregroundStyle(LK.muted) + } + } + + private func teamPicker(_ title: String, _ sel: Binding, edit: Binding) -> some View { + HStack(spacing: 4) { + Picker(title, selection: sel) { + Text("– wählen –").tag(UUID?.none) + ForEach(state.spieltag.teams) { t in Text(t.name).tag(UUID?.some(t.id)) } + } + Menu { + Button("Leeres Team") { sel.wrappedValue = newTeam(from: nil); edit.wrappedValue = true } + if !state.codeLibrary.sets.isEmpty { + Divider() + ForEach(state.codeLibrary.sets) { set in + Button("Aus Code-Team „\(set.name)“") { sel.wrappedValue = newTeam(from: set); edit.wrappedValue = true } + } + } + } label: { Image(systemName: "plus") } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .fixedSize() + .help("Neues Team anlegen") + } + } + + // MARK: Team / competition editors + + private func teamEditor(_ b: Binding) -> some View { + VStack(alignment: .leading, spacing: 8) { + row("Name") { TextField("VfL Wolfsburg", text: b.name).textFieldStyle(.roundedBorder) } + HStack(spacing: 10) { + row("Kurzname") { TextField("Wolfsburg (F)", text: b.shortName).textFieldStyle(.roundedBorder) } + row("Kürzel") { TextField("VFL", text: b.abbreviation).textFieldStyle(.roundedBorder).frame(width: 70) } + } + row("Stichwörter") { + TextField("VfL Wolfsburg, VfL, Wölfe, Wölfinnen …", text: b.keywords, axis: .vertical) + .lineLimit(1...4).textFieldStyle(.roundedBorder) + } + HStack(spacing: 10) { + row("Spieler-Codes") { + Picker("", selection: b.codeSetID) { + Text("– keine –").tag(UUID?.none) + ForEach(state.codeLibrary.sets) { set in Text(set.name).tag(UUID?.some(set.id)) } + } + .labelsHidden() + } + row("Präfix") { TextField("w", text: b.codePrefix).textFieldStyle(.roundedBorder).frame(width: 50) } + } + row("Heimstadion") { venueFields(b.venue) } + HStack(spacing: 14) { + kitPicker("Heimtrikot", b.homeKit, fallback: KitColor(r: 0.1, g: 0.45, b: 0.25)) + kitPicker("Auswärtstrikot", b.awayKit, fallback: KitColor(r: 0.95, g: 0.95, b: 0.95)) + Text("Genauer per Klick ins Foto: Bild → Trikot-Erkennung – wird hier gemerkt.") + .font(.caption).foregroundStyle(LK.muted) + } + } + .padding(.top, 8) + } + + private func competitionEditor(_ b: Binding) -> some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 10) { + row("Name (Überschrift)") { TextField("DFB-Pokal Frauen", text: b.name).textFieldStyle(.roundedBorder) } + row("Sportart") { TextField("Fußball", text: b.sport).textFieldStyle(.roundedBorder).frame(width: 120) } + } + row("Langform (Beschreibung)") { TextField("DFB-Pokal der Frauen", text: b.longName).textFieldStyle(.roundedBorder) } + row("Stichwörter") { + TextField("DFB Pokal, DFB Pokal Frauen …", text: b.keywords, axis: .vertical).lineLimit(1...3).textFieldStyle(.roundedBorder) + } + row("Rechtehinweis (ans Ende der Beschreibung)") { + TextField("DFB REGULATIONS PROHIBIT ANY USE OF PHOTOGRAPHS AS IMAGE SEQUENCES AND/OR QUASI-VIDEO.", + text: b.notice, axis: .vertical).lineLimit(1...4).textFieldStyle(.roundedBorder) + } + if let base = baseTemplate, b.wrappedValue.notice.isEmpty, let n = Self.noticeFromCaption(base.values.text["caption"]) { + Button("Hinweis aus der Basis-Vorlage übernehmen: „\(String(n.prefix(40)))…“") { b.wrappedValue.notice = n } + .buttonStyle(LKButtonStyle(compact: true)) + } + } + .padding(.top, 8) + } + + /// Last paragraph of the base caption if it looks like a notice (mostly upper case). + static func noticeFromCaption(_ caption: String?) -> String? { + guard let c = caption, let last = c.components(separatedBy: "\n\n").last?.trimmingCharacters(in: .whitespacesAndNewlines), + last.count > 20 else { return nil } + let letters = last.filter(\.isLetter) + guard !letters.isEmpty else { return nil } + let upper = letters.filter(\.isUppercase).count + return Double(upper) / Double(letters.count) > 0.7 ? last : nil + } + + private func venueFields(_ v: Binding) -> some View { + VStack(alignment: .leading, spacing: 6) { + TextField("Stadion (z. B. AOK Stadion)", text: v.name).textFieldStyle(.roundedBorder) + HStack(spacing: 6) { + TextField("Stadt", text: v.city).textFieldStyle(.roundedBorder) + TextField("Bundesland", text: v.state).textFieldStyle(.roundedBorder) + TextField("Land", text: v.country).textFieldStyle(.roundedBorder) + TextField("DEU", text: v.countryCode).textFieldStyle(.roundedBorder).frame(width: 56) + } + } + } + + private func kitPicker(_ title: String, _ kit: Binding, fallback: KitColor) -> some View { + HStack(spacing: 6) { + ColorPicker(title, selection: Binding( + get: { cg(kit.wrappedValue?.shirt ?? fallback) }, + set: { c in + var k = kit.wrappedValue ?? Kit(shirt: fallback) + k.shirt = rgb(c) + kit.wrappedValue = k + }), supportsOpacity: false) + .font(.system(size: 12)) + } + } + + private func row(_ label: String, @ViewBuilder _ content: () -> C) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(label).font(.system(size: 11, weight: .semibold)).foregroundStyle(LK.text2) + content() + } + } + + // MARK: Patterns + + private var patternEditor: some View { + let p = $state.spieltag.patterns + return VStack(alignment: .leading, spacing: 10) { + row("Überschrift") { TextField("", text: p.headline).textFieldStyle(.roundedBorder).font(LK.mono(12)) } + row("Ereignis") { TextField("", text: p.event).textFieldStyle(.roundedBorder).font(LK.mono(12)) } + row("Beschreibung (Leerzeilen oben = Platz für die Personen)") { + TextEditor(text: p.caption) + .font(LK.mono(12)) + .scrollContentBackground(.hidden) + .padding(6) + .frame(height: 110) + .background(RoundedRectangle(cornerRadius: 8).fill(LK.deep)) + .overlay(RoundedRectangle(cornerRadius: 8).stroke(LK.borderStrong)) + } + HStack(spacing: 10) { + row("Ingest-Ordner") { TextField("", text: p.folder).textFieldStyle(.roundedBorder).font(LK.mono(12)) } + row("Matchcode") { TextField("", text: p.matchCode).textFieldStyle(.roundedBorder).font(LK.mono(12)).frame(width: 160) } + } + HStack(spacing: 10) { + row("Stichwörter für jedes Spiel") { + TextField("Fußball, Fußballspiel, BLD …", text: p.generalKeywords).textFieldStyle(.roundedBorder) + } + row("Saison-Stichwort") { TextField("", text: p.seasonKeyword).textFieldStyle(.roundedBorder).frame(width: 160) } + } + LazyVGrid(columns: [GridItem(.adaptive(minimum: 190), alignment: .leading)], alignment: .leading, spacing: 4) { + ForEach(SpieltagPatterns.variables.indices, id: \.self) { i in + HStack(spacing: 6) { + Text(SpieltagPatterns.variables[i].0).font(LK.mono(11)).foregroundStyle(LK.amber).textSelection(.enabled) + Text(SpieltagPatterns.variables[i].1).font(.system(size: 11)).foregroundStyle(LK.muted) + } + } + } + Button("Muster zurücksetzen") { state.spieltag.patterns = SpieltagPatterns() } + .buttonStyle(LKButtonStyle(compact: true)) + } + .padding(.top, 8) + } + + // MARK: Preview + + private var previewColumn: some View { + VStack(alignment: .leading, spacing: 16) { + LKSectionLabel(title: "Vorschau") + if let t = preview { + previewRow("Überschrift", t.values.text["headline"] ?? "") + previewRow("Ereignis", t.values.text["event"] ?? "") + VStack(alignment: .leading, spacing: 5) { + Text("Beschreibung").font(.system(size: 11, weight: .semibold)).foregroundStyle(LK.text2) + Text(visibleLineBreaks(t.values.text["caption"] ?? "")) + .font(LK.mono(12)) + .foregroundStyle(LK.text) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(10) + .background(RoundedRectangle(cornerRadius: 8).fill(LK.deep)) + Text("⏎ = Zeilenumbruch · die leeren Zeilen oben füllst du pro Bild mit den Personen (Codes / Trikot-Erkennung)") + .font(.system(size: 10)).foregroundStyle(LK.muted) + } + previewRow("Ort", placeText(t)) + VStack(alignment: .leading, spacing: 6) { + Text("Stichwörter (\(t.values.lists["keywords"]?.count ?? 0))") + .font(.system(size: 11, weight: .semibold)).foregroundStyle(LK.text2) + LazyVGrid(columns: [GridItem(.adaptive(minimum: 110), spacing: 6, alignment: .leading)], alignment: .leading, spacing: 6) { + ForEach(t.values.lists["keywords"] ?? [], id: \.self) { k in + Text(k).font(.system(size: 11)).foregroundStyle(LK.text).lineLimit(1) + .padding(.horizontal, 8).padding(.vertical, 3) + .background(Capsule().fill(LK.raised)) + } + } + } + if let home, let away { + let ctx = SpieltagGenerator.context(match: plan, home: home, away: away, competition: competition, + patterns: state.spieltag.patterns) + previewRow("Ingest-Ordner", SpieltagGenerator.folderName(patterns: state.spieltag.patterns, ctx: ctx), mono: true) + previewRow("Datum", "Aufnahmezeit jedes Bildes (Capture Time)") + } + if let base = baseTemplate { + previewRow("Aus „\(base.name)“", baseText(base)) + } + } else { + VStack(spacing: 10) { + Image(systemName: "sportscourt").font(.system(size: 34)).foregroundStyle(LK.faint) + Text("Heim- und Gastteam wählen – mit „+“ legst du ein Team an, z. B. direkt aus einem Code-Team deiner Kader-TXT.") + .font(.system(size: 12)).foregroundStyle(LK.muted).multilineTextAlignment(.center) + } + .frame(maxWidth: .infinity, minHeight: 240) + } + } + } + + private func previewRow(_ label: String, _ value: String, mono: Bool = false) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(label).font(.system(size: 11, weight: .semibold)).foregroundStyle(LK.text2) + Text(value.isEmpty ? "–" : value) + .font(mono ? LK.mono(12) : .system(size: 13)) + .foregroundStyle(LK.text) + .textSelection(.enabled) + } + } + + private func visibleLineBreaks(_ s: String) -> String { + s.components(separatedBy: "\n").map { $0.isEmpty ? "⏎" : $0 }.joined(separator: "\n") + } + + private func placeText(_ t: IPTCTemplate) -> String { + let text: [String: String] = t.values.text + var parts: [String] = [] + for id in ["sublocation", "city", "state"] { + if let v = text[id], !v.isEmpty { parts.append(v) } + } + if let country = text["country"], !country.isEmpty { + let code: String = text["countryCode"] ?? "" + parts.append(code.isEmpty ? country : "\(country) (\(code))") + } + return parts.joined(separator: " · ") + } + + /// What the base template contributes (creator, copyright …). + private func baseText(_ base: IPTCTemplate) -> String { + var parts: [String] = [] + for id in ["creator", "copyright", "credit", "source", "captionWriter"] { + guard let v = base.values.text[id], !v.isEmpty else { continue } + let label: String = IPTCField.byID[id]?.label ?? id + parts.append("\(label): \(v)") + } + return parts.joined(separator: " · ") + } + + private func venueSummary(_ v: Venue) -> String { + if v.isEmpty { return "Kein Heimstadion im Heimteam eingetragen – „Heim bearbeiten“ oder Haken entfernen." } + let place = [v.city, v.state, v.country].filter { !$0.isEmpty }.joined(separator: ", ") + return v.name.isEmpty ? place : "\(v.name) · \(place)" + } + + // MARK: Data helpers + + private func setup() { + let lib = state.spieltag + if competitionID == nil { competitionID = lib.lastCompetitionID ?? lib.competitions.first?.id } + if baseTemplateID == nil { + let candidates = state.templates.filter { !$0.name.hasPrefix("Spieltag ") } + baseTemplateID = lib.lastBaseTemplateID.flatMap { id in candidates.first { $0.id == id }?.id } ?? candidates.first?.id + } + guard homeID == nil, let last = lib.matches.last else { return } + if last.date >= Calendar.current.startOfDay(for: Date()) { + // today's / an upcoming match: reopen it for corrections (same teams + day updates it) + homeID = last.homeID + awayID = last.awayID + competitionID = last.competitionID ?? competitionID + round = last.round + date = last.date + extraKeywords = last.extraKeywords + if let b = last.baseTemplateID, state.templates.contains(where: { $0.id == b }) { baseTemplateID = b } + let homeVenue = lib.team(last.homeID)?.venue ?? Venue() + venueFollowsHome = last.venue == homeVenue + venue = last.venue + } else { + homeID = last.homeID // club photographers: usually the same home team + } + } + + private func newTeam(from set: CodeSet?) -> UUID { + var t = TeamProfile(name: set.map { prettyName($0.name) } ?? "Neues Team") + if let set { + t.codeSetID = set.id + t.codePrefix = JerseyLogic.detectPrefix(codes: set.entries.map(\.code)) + } + state.spieltag.teams.append(t) + return t.id + } + + /// Code teams are often named after their TXT file ("vfl wolfsburg frauen kader 26-27") – + /// take the first words, capitalized; the name stays editable. + private func prettyName(_ s: String) -> String { + let words: [String] = s.split(separator: " ").prefix(3).map { w in + String(w.prefix(1)).uppercased() + String(w.dropFirst()) + } + return words.joined(separator: " ") + } + + private func newCompetition() { + let c = Competition(name: "Neuer Wettbewerb") + state.spieltag.competitions.append(c) + competitionID = c.id + editCompetition = true + } + + private func teamBinding(_ id: UUID?) -> Binding? { + guard let id, state.spieltag.teams.contains(where: { $0.id == id }) else { return nil } + return Binding( + get: { state.spieltag.teams.first { $0.id == id } ?? TeamProfile(name: "") }, + set: { new in if let i = state.spieltag.teams.firstIndex(where: { $0.id == id }) { state.spieltag.teams[i] = new } }) + } + + private func competitionBinding(_ id: UUID?) -> Binding? { + guard let id, state.spieltag.competitions.contains(where: { $0.id == id }) else { return nil } + return Binding( + get: { state.spieltag.competitions.first { $0.id == id } ?? Competition(name: "") }, + set: { new in if let i = state.spieltag.competitions.firstIndex(where: { $0.id == id }) { state.spieltag.competitions[i] = new } }) + } + + private func cg(_ c: KitColor) -> CGColor { CGColor(srgbRed: c.r, green: c.g, blue: c.b, alpha: 1) } + + private func rgb(_ c: CGColor) -> KitColor { + let conv = c.converted(to: CGColorSpace(name: CGColorSpace.sRGB)!, intent: .defaultIntent, options: nil) ?? c + let comps = conv.components ?? [0, 0, 0] + if comps.count >= 3 { return KitColor(r: Double(comps[0]), g: Double(comps[1]), b: Double(comps[2])) } + return KitColor(r: Double(comps[0]), g: Double(comps[0]), b: Double(comps[0])) + } +} diff --git a/Sources/Lichtkasten/Views/Theme.swift b/Sources/Lichtkasten/Views/Theme.swift index 8a468c7..2a76fbc 100644 --- a/Sources/Lichtkasten/Views/Theme.swift +++ b/Sources/Lichtkasten/Views/Theme.swift @@ -189,3 +189,18 @@ struct LKWindowStyler: NSViewRepresentable { w.appearance = NSAppearance(named: .darkAqua) } } + +/// "Gesendet an … am …" / "Noch nicht gesendet" (loupe panel, IPTC window). +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) + } + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(summary == nil ? LK.muted : LK.green) + .frame(maxWidth: .infinity, alignment: .leading) + } +} diff --git a/Sources/Lichtkasten/Views/UploadWindow.swift b/Sources/Lichtkasten/Views/UploadWindow.swift index 59818fe..9b269b1 100644 --- a/Sources/Lichtkasten/Views/UploadWindow.swift +++ b/Sources/Lichtkasten/Views/UploadWindow.swift @@ -6,6 +6,7 @@ struct UploadWindow: View { @EnvironmentObject var state: AppState @Environment(\.dismissWindow) private var dismissWindow @AppStorage("lastUploadTarget") private var target = "" + @AppStorage("uploadSkipSent") private var skipSent = true private var destination: FTPDestination? { state.settings.ftpDestinations.first { $0.id.uuidString == target } } private var destIndex: Int? { state.settings.ftpDestinations.firstIndex { $0.id.uuidString == target } } @@ -14,7 +15,16 @@ struct UploadWindow: View { target == "immich" ? state.settings.immich.variant : destination?.variant ?? .jpeg } - private var files: [URL] { state.selectedItems.flatMap { state.uploadFiles(for: $0, variant: variant) } } + private var files: [URL] { sendItems.flatMap { state.uploadFiles(for: $0, variant: variant) } } + + /// selected photos already sent to this destination + private var alreadySent: [PhotoItem] { state.selectedItems.filter { state.sentLog.wasSent($0, to: target) } } + + private var sendItems: [PhotoItem] { + guard skipSent else { return state.selectedItems } + let sent = Set(alreadySent.map(\.id)) + return state.selectedItems.filter { !sent.contains($0.id) } + } private var totalBytes: Int64 { files.reduce(0) { sum, f in sum + (((try? FileManager.default.attributesOfItem(atPath: f.path)[.size]) as? NSNumber)?.int64Value ?? 0) } } @@ -70,6 +80,11 @@ struct UploadWindow: View { LKSegmented(options: UploadVariant.allCases.map { ($0, $0.rawValue) }, selection: $state.settings.ftpDestinations[i].variant) } + divider + optionRow("Agentur-Check") { + Toggle("Vor dem Senden prüfen (Pflichtfelder, Codes, Datum …)", isOn: $state.settings.ftpDestinations[i].preflight) + .toggleStyle(.checkbox) + } } .background(RoundedRectangle(cornerRadius: 12).fill(LK.card)) .overlay(RoundedRectangle(cornerRadius: 12).stroke(LK.border)) @@ -88,8 +103,16 @@ struct UploadWindow: View { .overlay(RoundedRectangle(cornerRadius: 12).stroke(LK.border)) } - if files.count < state.selectedItems.count { - Label("\(state.selectedItems.count - files.count) Bild(er) ohne JPEG – zuerst in Lightroom exportieren (⌘⌥L).", + if !alreadySent.isEmpty { + Toggle(isOn: $skipSent) { + Label("\(alreadySent.count) Bild(er) wurden schon an dieses Ziel gesendet – überspringen", systemImage: "paperplane.fill") + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(LK.green) + } + .toggleStyle(.checkbox) + } + if files.count < sendItems.count { + Label("\(max(0, sendItems.count - files.count)) Bild(er) ohne JPEG – zuerst in Lightroom exportieren (⌘⌥L).", systemImage: "exclamationmark.triangle.fill") .font(.system(size: 12)).foregroundStyle(LK.amber) } @@ -109,8 +132,8 @@ struct UploadWindow: View { .buttonStyle(LKButtonStyle()) .keyboardShortcut(.cancelAction) Button("\(files.count) Datei(en) hochladen") { - state.upload(to: target) - state.openWindow("tasks") + state.requestUpload(state.selectedItems, to: target, skipAlreadySent: skipSent) + if state.pendingUpload == nil { state.openWindow("tasks") } dismissWindow(id: "upload") } .buttonStyle(LKButtonStyle(primary: true)) diff --git a/Sources/LichtkastenCore/Matchday/Spieltag.swift b/Sources/LichtkastenCore/Matchday/Spieltag.swift new file mode 100644 index 0000000..fcf5915 --- /dev/null +++ b/Sources/LichtkastenCore/Matchday/Spieltag.swift @@ -0,0 +1,325 @@ +import Foundation + +/// Stadium / place of a match. +public struct Venue: Codable, Hashable, Sendable { + public var name: String = "" // "AOK Stadion" + public var city: String = "" // "Wolfsburg" + public var state: String = "" // "Niedersachsen" + public var country: String = "Deutschland" + public var countryCode: String = "DEU" + + public init(name: String = "", city: String = "", state: String = "", country: String = "Deutschland", countryCode: String = "DEU") { + self.name = name; self.city = city; self.state = state; self.country = country; self.countryCode = countryCode + } + + public var isEmpty: Bool { name.isEmpty && city.isEmpty } +} + +/// Kit colors of a team (home / away). +public struct Kit: Codable, Hashable, Sendable { + public var shirt: KitColor + public var shorts: KitColor? + public init(shirt: KitColor, shorts: KitColor? = nil) { self.shirt = shirt; self.shorts = shorts } +} + +/// A club/team as it appears in captions, keywords, folder names, jersey recognition. +public struct TeamProfile: Codable, Hashable, Identifiable, Sendable { + public var id = UUID() + public var name: String // "VfL Wolfsburg" + public var shortName: String // "Wolfsburg (F)" – folder names + public var abbreviation: String // "VFL" – match code VFLTSG + /// comma separated, e.g. "VfL Wolfsburg, VfL, Wölfe, Wölfinnen, Grün Weiß" + public var keywords: String + public var venue: Venue // home stadium + public var codeSetID: UUID? // players in the code library + public var codePrefix: String // "w" → w10 + public var homeKit: Kit? + public var awayKit: Kit? + + public init(name: String, shortName: String = "", abbreviation: String = "", keywords: String = "", + venue: Venue = Venue(), codeSetID: UUID? = nil, codePrefix: String = "") { + self.name = name; self.shortName = shortName; self.abbreviation = abbreviation; self.keywords = keywords + self.venue = venue; self.codeSetID = codeSetID; self.codePrefix = codePrefix + } + + enum CodingKeys: String, CodingKey { + case id, name, shortName, abbreviation, keywords, venue, codeSetID, codePrefix, homeKit, awayKit + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = (try? c.decode(UUID.self, forKey: .id)) ?? UUID() + name = (try? c.decode(String.self, forKey: .name)) ?? "" + shortName = (try? c.decode(String.self, forKey: .shortName)) ?? "" + abbreviation = (try? c.decode(String.self, forKey: .abbreviation)) ?? "" + keywords = (try? c.decode(String.self, forKey: .keywords)) ?? "" + venue = (try? c.decode(Venue.self, forKey: .venue)) ?? Venue() + codeSetID = try? c.decode(UUID.self, forKey: .codeSetID) + codePrefix = (try? c.decode(String.self, forKey: .codePrefix)) ?? "" + homeKit = try? c.decode(Kit.self, forKey: .homeKit) + awayKit = try? c.decode(Kit.self, forKey: .awayKit) + } + + /// "VfL Wolfsburg" → "VFL" when no abbreviation is set + public var effectiveAbbreviation: String { + if !abbreviation.isEmpty { return abbreviation.uppercased() } + let words = name.split(separator: " ").map(String.init) + let main = words.first { $0.count > 3 && $0.first?.isLetter == true } ?? words.first ?? name + return String(main.prefix(3)).uppercased() + } + + public var effectiveShortName: String { shortName.isEmpty ? name : shortName } +} + +/// Competition: "DFB-Pokal Frauen", "Frauen-Bundesliga", "FIBA Women's World Cup" … +public struct Competition: Codable, Hashable, Identifiable, Sendable { + public var id = UUID() + public var name: String // headline / event: "DFB-Pokal Frauen" + public var longName: String // caption: "DFB-Pokal der Frauen" + public var sport: String // "Fußball" + public var keywords: String // comma separated + /// rights notice appended to the caption ("DFB REGULATIONS PROHIBIT …") + public var notice: String + + public init(name: String, longName: String = "", sport: String = "Fußball", keywords: String = "", notice: String = "") { + self.name = name; self.longName = longName; self.sport = sport; self.keywords = keywords; self.notice = notice + } + + enum CodingKeys: String, CodingKey { case id, name, longName, sport, keywords, notice } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = (try? c.decode(UUID.self, forKey: .id)) ?? UUID() + name = (try? c.decode(String.self, forKey: .name)) ?? "" + longName = (try? c.decode(String.self, forKey: .longName)) ?? "" + sport = (try? c.decode(String.self, forKey: .sport)) ?? "Fußball" + keywords = (try? c.decode(String.self, forKey: .keywords)) ?? "" + notice = (try? c.decode(String.self, forKey: .notice)) ?? "" + } +} + +/// How the IPTC of every match is built – defaults follow Leon's Photo Mechanic template. +public struct SpieltagPatterns: Codable, Hashable, Sendable { + public var headline = "{competition}: {home} vs. {away}, {matchdate}" + public var event = "{competition}: {home} - {away}" + public var caption = "\n\n\n; {sport}, {competitionLong}, {round}: {home} vs. {away} am {matchdate} im {venue}, {city}{noticeBlock}" + public var folder = "{matchdate} - {homeShort} - {awayShort}" + public var matchCode = "{homeAbbr}{awayAbbr}" + public var seasonKeyword = "Saison {season}" + /// keywords for every match, comma separated ("Fußball, Fußballspiel, BLD") + public var generalKeywords = "" + + public init() {} + + enum CodingKeys: String, CodingKey { case headline, event, caption, folder, matchCode, seasonKeyword, generalKeywords } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = SpieltagPatterns() + headline = (try? c.decode(String.self, forKey: .headline)) ?? d.headline + event = (try? c.decode(String.self, forKey: .event)) ?? d.event + caption = (try? c.decode(String.self, forKey: .caption)) ?? d.caption + folder = (try? c.decode(String.self, forKey: .folder)) ?? d.folder + matchCode = (try? c.decode(String.self, forKey: .matchCode)) ?? d.matchCode + seasonKeyword = (try? c.decode(String.self, forKey: .seasonKeyword)) ?? d.seasonKeyword + generalKeywords = (try? c.decode(String.self, forKey: .generalKeywords)) ?? d.generalKeywords + } + + /// Variables available in all patterns (shown in the assistant). + public static let variables: [(String, String)] = [ + ("{home}", "Heimteam"), ("{away}", "Gastteam"), ("{homeShort}", "Heim kurz (Ordner)"), ("{awayShort}", "Gast kurz"), + ("{homeAbbr}", "Heim-Kürzel"), ("{awayAbbr}", "Gast-Kürzel"), ("{competition}", "Wettbewerb"), + ("{competitionLong}", "Wettbewerb lang"), ("{round}", "Runde / Spieltag"), ("{sport}", "Sportart"), + ("{venue}", "Stadion"), ("{city}", "Stadt"), ("{state}", "Bundesland"), ("{country}", "Land"), + ("{matchdate}", "Datum 02.11.2026"), ("{isomatchdate}", "Datum 2026-11-02"), ("{season}", "Saison 26/27"), + ("{matchcode}", "Matchcode"), ("{notice}", "Rechtehinweis"), ("{noticeBlock}", "Leerzeile + Rechtehinweis"), + ] +} + +/// One planned/created match. +public struct MatchPlan: Codable, Hashable, Identifiable, Sendable { + public var id = UUID() + public var homeID: UUID + public var awayID: UUID + public var competitionID: UUID? + public var round: String + public var date: Date + public var venue: Venue + /// comma separated, only for this match + public var extraKeywords: String + public var baseTemplateID: UUID? + public var templateID: UUID? + /// event text written into the photos – finds the match of a photo later (e.g. in SENT) + public var event: String + public var folderName: String + public var created: Date + + public init(homeID: UUID, awayID: UUID, competitionID: UUID?, round: String, date: Date, venue: Venue, + extraKeywords: String = "", baseTemplateID: UUID? = nil) { + self.homeID = homeID; self.awayID = awayID; self.competitionID = competitionID; self.round = round + self.date = date; self.venue = venue; self.extraKeywords = extraKeywords; self.baseTemplateID = baseTemplateID + self.event = ""; self.folderName = ""; self.created = Date() + } +} + +/// Everything the Spieltag assistant remembers. +public struct SpieltagLibrary: Codable, Sendable { + public var teams: [TeamProfile] = [] + public var competitions: [Competition] = [] + public var patterns = SpieltagPatterns() + public var matches: [MatchPlan] = [] + public var lastBaseTemplateID: UUID? + public var lastCompetitionID: UUID? + + public init() {} + + enum CodingKeys: String, CodingKey { case teams, competitions, patterns, matches, lastBaseTemplateID, lastCompetitionID } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + teams = (try? c.decode([TeamProfile].self, forKey: .teams)) ?? [] + competitions = (try? c.decode([Competition].self, forKey: .competitions)) ?? [] + patterns = (try? c.decode(SpieltagPatterns.self, forKey: .patterns)) ?? SpieltagPatterns() + matches = (try? c.decode([MatchPlan].self, forKey: .matches)) ?? [] + lastBaseTemplateID = try? c.decode(UUID.self, forKey: .lastBaseTemplateID) + lastCompetitionID = try? c.decode(UUID.self, forKey: .lastCompetitionID) + } + + public func team(_ id: UUID?) -> TeamProfile? { id.flatMap { i in teams.first { $0.id == i } } } + public func competition(_ id: UUID?) -> Competition? { id.flatMap { i in competitions.first { $0.id == i } } } + + /// Newest match whose event text is exactly this (IPTC "Event" of a photo). + public func match(forEvent event: String) -> MatchPlan? { + guard !event.isEmpty else { return nil } + return matches.last { $0.event == event } + } +} + +/// Builds headline, event, caption, keywords, folder name and the IPTC template of a match. +public enum SpieltagGenerator { + /// Season of a date: July–June, "26/27" for November 2026. + public static func season(for date: Date) -> String { + let c = Calendar(identifier: .gregorian).dateComponents([.year, .month], from: date) + let y = (c.year ?? 2000) % 100, m = c.month ?? 1 + let start = m >= 7 ? y : (y + 99) % 100 + return String(format: "%02d/%02d", start, (start + 1) % 100) + } + + public static func context(match: MatchPlan, home: TeamProfile, away: TeamProfile, competition: Competition?, + patterns: SpieltagPatterns) -> [String: String] { + let f = DateFormatter() + f.locale = Locale(identifier: "de_DE") + f.dateFormat = "dd.MM.yyyy" + let iso = DateFormatter() + iso.locale = Locale(identifier: "en_US_POSIX") + iso.dateFormat = "yyyy-MM-dd" + var ctx: [String: String] = [ + "home": home.name, "away": away.name, + "homeshort": home.effectiveShortName, "awayshort": away.effectiveShortName, + "homeabbr": home.effectiveAbbreviation, "awayabbr": away.effectiveAbbreviation, + "competition": competition?.name ?? "", + "competitionlong": (competition?.longName.isEmpty == false ? competition?.longName : competition?.name) ?? "", + "round": match.round, "sport": competition?.sport ?? "", + "venue": match.venue.name, "city": match.venue.city, "state": match.venue.state, + "country": match.venue.country, "countrycode": match.venue.countryCode, + "matchdate": f.string(from: match.date), "isomatchdate": iso.string(from: match.date), + "season": season(for: match.date), + "notice": competition?.notice ?? "", + "noticeblock": (competition?.notice ?? "").isEmpty ? "" : "\n\n" + (competition?.notice ?? ""), + ] + ctx["matchcode"] = fill(patterns.matchCode, ctx).replacingOccurrences(of: " ", with: "") + return ctx + } + + /// Replaces {variables} (case-insensitive) and tidies separators left by empty values + /// (", :" → ":", ", ," → ","). Line breaks are kept exactly. + public static func fill(_ pattern: String, _ ctx: [String: String]) -> String { + var out = "" + var rest = pattern[...] + while let open = rest.firstIndex(of: "{") { + out += rest[.. String { + var s = line + let rules: [(String, String)] = [(#",\s*:"#, ":"), (#",\s*,"#, ","), (#"\s+,"#, ","), (#"\(\s*\)"#, ""), (#" {2,}"#, " ")] + for (p, r) in rules { + s = s.replacingOccurrences(of: p, with: r, options: .regularExpression) + } + // trailing separators from empty values at the end ("…, 02.11.2026, " → "…, 02.11.2026") + s = s.replacingOccurrences(of: #"[\s,;:–-]+$"#, with: "", options: .regularExpression) + return s + } + + public static func splitKeywords(_ s: String) -> [String] { IPTCValues.splitList(s) } + + public static func keywords(match: MatchPlan, home: TeamProfile, away: TeamProfile, competition: Competition?, + patterns: SpieltagPatterns, ctx: [String: String]) -> [String] { + var all: [String] = [] + all += splitKeywords(patterns.generalKeywords) + all += splitKeywords(competition?.keywords ?? "") + if !match.round.isEmpty { all.append(match.round) } + all += splitKeywords(home.keywords) + all += splitKeywords(away.keywords) + if !match.venue.name.isEmpty { all.append(match.venue.name) } + if let code = ctx["matchcode"], !code.isEmpty { all.append(code) } + let season = fill(patterns.seasonKeyword, ctx) + if !season.isEmpty { all.append(season) } + all += splitKeywords(match.extraKeywords) + var seen = Set() + return all.filter { seen.insert($0.lowercased()).inserted } + } + + /// Folder name for the ingest (no path separators). + public static func folderName(patterns: SpieltagPatterns, ctx: [String: String]) -> String { + fill(patterns.folder, ctx).replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: "-") + } + + public static let generatedFields = ["headline", "event", "caption", "city", "sublocation", "state", "country", + "countryCode", "keywords", "dateCreated"] + + /// The IPTC template of the match: base template (creator, copyright, …) + everything generated. + public static func makeTemplate(match: MatchPlan, home: TeamProfile, away: TeamProfile, competition: Competition?, + patterns: SpieltagPatterns, base: IPTCTemplate?) -> IPTCTemplate { + let ctx = context(match: match, home: home, away: away, competition: competition, patterns: patterns) + var t = base ?? IPTCTemplate(name: "", listMergeMode: .replace) + t.id = match.templateID ?? UUID() + t.name = "Spieltag \(ctx["matchdate"] ?? "") · \(home.name) – \(away.name)" + var v = t.values + v.text["headline"] = fill(patterns.headline, ctx) + v.text["event"] = fill(patterns.event, ctx) + v.text["caption"] = fill(patterns.caption, ctx) + v.text["city"] = match.venue.city.isEmpty ? nil : match.venue.city + v.text["sublocation"] = match.venue.name.isEmpty ? nil : match.venue.name + v.text["state"] = match.venue.state.isEmpty ? nil : match.venue.state + v.text["country"] = match.venue.country.isEmpty ? nil : match.venue.country + v.text["countryCode"] = match.venue.countryCode.isEmpty ? nil : match.venue.countryCode + v.lists["keywords"] = keywords(match: match, home: home, away: away, competition: competition, patterns: patterns, ctx: ctx) + v.text["dateCreated"] = "{capturetime}" + // "Location created" only if the base template uses it – then it must not keep the old stadium + if t.values.text["lcCity"] != nil || t.values.text["lcSublocation"] != nil { + v.text["lcCity"] = match.venue.city + v.text["lcSublocation"] = match.venue.name + v.text["lcState"] = match.venue.state + v.text["lcCountry"] = match.venue.country + v.text["lcCountryCode"] = match.venue.countryCode + } + t.values = v + t.dateFromCapture = true + if var applied = t.appliedFields { + applied.formUnion(generatedFields) + t.appliedFields = applied + } + if base == nil { t.listMergeMode = .replace } + t.unmappedPMCodes = [] + t.modified = Date() + return t + } +} diff --git a/Sources/LichtkastenCore/Metadata/JerseyLogic.swift b/Sources/LichtkastenCore/Metadata/JerseyLogic.swift index b0454b9..a7f71d0 100644 --- a/Sources/LichtkastenCore/Metadata/JerseyLogic.swift +++ b/Sources/LichtkastenCore/Metadata/JerseyLogic.swift @@ -22,9 +22,13 @@ public struct JerseyTeam: Codable, Hashable, Identifiable, Sendable { public var prefix: String public var shirtColor: KitColor public var shortsColor: KitColor? + /// team profile of the Spieltag assistant this team comes from (kit colors are written back to it) + public var profileID: UUID? + /// home or away kit of that profile + public var isHome: Bool? - public init(name: String, codeSetID: UUID? = nil, prefix: String, shirtColor: KitColor, shortsColor: KitColor? = nil) { - self.name = name; self.codeSetID = codeSetID; self.prefix = prefix + public init(id: UUID = UUID(), name: String, codeSetID: UUID? = nil, prefix: String, shirtColor: KitColor, shortsColor: KitColor? = nil) { + self.id = id; self.name = name; self.codeSetID = codeSetID; self.prefix = prefix self.shirtColor = shirtColor; self.shortsColor = shortsColor } } diff --git a/Sources/LichtkastenCore/Upload/FTPUploader.swift b/Sources/LichtkastenCore/Upload/FTPUploader.swift index 914d475..187a279 100644 --- a/Sources/LichtkastenCore/Upload/FTPUploader.swift +++ b/Sources/LichtkastenCore/Upload/FTPUploader.swift @@ -39,15 +39,43 @@ public struct FTPDestination: Codable, Identifiable, Hashable, Sendable { /// Path to an SSH private key for SFTP (optional; otherwise ssh-agent / password via curl). public var sshKeyPath: String public var allowInsecureTLS: Bool + /// Agentur-Check before uploading to this server + public var preflight: Bool public init(id: UUID = UUID(), name: String = "Neuer Server", proto: FTPProtocol = .ftp, host: String = "", port: Int = 21, username: String = "", remoteDirectory: String = "/", passive: Bool = true, uploadWithTempName: Bool = true, renamePattern: String = "", variant: UploadVariant = .jpeg, - sshKeyPath: String = "", allowInsecureTLS: Bool = false) { + sshKeyPath: String = "", allowInsecureTLS: Bool = false, preflight: Bool = true) { self.id = id; self.name = name; self.proto = proto; self.host = host; self.port = port self.username = username; self.remoteDirectory = remoteDirectory; self.passive = passive self.uploadWithTempName = uploadWithTempName; self.renamePattern = renamePattern; self.variant = variant - self.sshKeyPath = sshKeyPath; self.allowInsecureTLS = allowInsecureTLS + self.sshKeyPath = sshKeyPath; self.allowInsecureTLS = allowInsecureTLS; self.preflight = preflight + } + + enum CodingKeys: String, CodingKey { + case id, name, proto, host, port, username, remoteDirectory, passive, uploadWithTempName, renamePattern, + variant, sshKeyPath, allowInsecureTLS, preflight + } + + /// Tolerant decoding – new options must never wipe the saved server profiles. + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = FTPDestination() + func v(_ k: CodingKeys, _ def: T) -> T { (try? c.decode(T.self, forKey: k)) ?? def } + id = v(.id, UUID()) + name = v(.name, d.name) + proto = v(.proto, d.proto) + host = v(.host, d.host) + port = v(.port, d.port) + username = v(.username, d.username) + remoteDirectory = v(.remoteDirectory, d.remoteDirectory) + passive = v(.passive, d.passive) + uploadWithTempName = v(.uploadWithTempName, d.uploadWithTempName) + renamePattern = v(.renamePattern, d.renamePattern) + variant = v(.variant, d.variant) + sshKeyPath = v(.sshKeyPath, d.sshKeyPath) + allowInsecureTLS = v(.allowInsecureTLS, d.allowInsecureTLS) + preflight = v(.preflight, d.preflight) } public var keychainAccount: String { "ftp-\(id.uuidString)" } diff --git a/Sources/LichtkastenCore/Upload/Preflight.swift b/Sources/LichtkastenCore/Upload/Preflight.swift new file mode 100644 index 0000000..b9d95f8 --- /dev/null +++ b/Sources/LichtkastenCore/Upload/Preflight.swift @@ -0,0 +1,175 @@ +import Foundation + +/// Agentur-Check: what is checked before photos go to an agency server. +public struct PreflightOptions: Codable, Hashable, Sendable { + /// Field ids that must not be empty (error) + public var requiredFields: [String] = ["caption", "headline", "creator", "copyright", "city", "country", "dateCreated"] + /// First caption line empty (the line for the people in the PM template) → warning + public var warnEmptyFirstLine = true + /// Dates like 02.11.2026 in headline/caption must match the capture date (old template reused?) + public var checkDates = true + /// IIM byte limits (agencies truncate) + public var checkLengths = true + /// Jersey suggestions not yet accepted/dismissed + public var checkOpenSuggestions = true + /// Minimum long edge in pixels (0 = off) + public var minLongEdge = 0 + + public init() {} + + enum CodingKeys: String, CodingKey { + case requiredFields, warnEmptyFirstLine, checkDates, checkLengths, checkOpenSuggestions, minLongEdge + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = PreflightOptions() + requiredFields = (try? c.decode([String].self, forKey: .requiredFields)) ?? d.requiredFields + warnEmptyFirstLine = (try? c.decode(Bool.self, forKey: .warnEmptyFirstLine)) ?? d.warnEmptyFirstLine + checkDates = (try? c.decode(Bool.self, forKey: .checkDates)) ?? d.checkDates + checkLengths = (try? c.decode(Bool.self, forKey: .checkLengths)) ?? d.checkLengths + checkOpenSuggestions = (try? c.decode(Bool.self, forKey: .checkOpenSuggestions)) ?? d.checkOpenSuggestions + minLongEdge = (try? c.decode(Int.self, forKey: .minLongEdge)) ?? d.minLongEdge + } +} + +public enum PreflightSeverity: String, Codable, Sendable, Comparable { + case warning, error + + public static func < (a: PreflightSeverity, b: PreflightSeverity) -> Bool { a == .warning && b == .error } +} + +public struct PreflightIssue: Hashable, Identifiable, Sendable { + public var id: String { severity.rawValue + "|" + message } + public var severity: PreflightSeverity + public var message: String + /// field the issue belongs to (to jump to it), nil = whole image + public var fieldID: String? + + public init(_ severity: PreflightSeverity, _ message: String, field: String? = nil) { + self.severity = severity; self.message = message; self.fieldID = field + } +} + +public enum Preflight { + /// Checks one photo. `openSuggestions` = codes/names of jersey suggestions still open. + public static func check(iptc: IPTCValues, exif: [String: String], captureDate: Date?, codes: CodeReplacements, + options: PreflightOptions, openSuggestions: [String] = []) -> [PreflightIssue] { + var issues: [PreflightIssue] = [] + + // 1. required fields + for id in options.requiredFields { + guard let f = IPTCField.byID[id] else { continue } + let value = f.kind == .list ? iptc.list(f).joined() : (iptc.text[id] ?? "") + if value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + issues.append(PreflightIssue(.error, "Pflichtfeld leer: \(f.label)", field: id)) + } + } + + let caption = iptc.text["caption"] ?? "" + + // 2. first caption line (people line of the template) still empty + if options.warnEmptyFirstLine, !caption.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + let first = caption.components(separatedBy: .newlines).first ?? "" + if first.trimmingCharacters(in: .whitespaces).isEmpty { + issues.append(PreflightIssue(.warning, "Erste Zeile der Beschreibung ist leer – Person vergessen?", field: "caption")) + } + } + + // 3. unresolved variables / codes in any text + var allTexts: [(IPTCField, String)] = [] + for f in IPTCField.all { + if f.kind == .list { for v in iptc.list(f) { allTexts.append((f, v)) } } + else if let v = iptc.text[f.id], !v.isEmpty { allTexts.append((f, v)) } + } + var reported = Set() + for (f, text) in allTexts { + for v in unresolvedVariables(in: text) where reported.insert("var" + v).inserted { + issues.append(PreflightIssue(.error, "Variable nicht ersetzt: \(v) (\(f.label))", field: f.id)) + } + for c in unresolvedDelimiterCodes(in: text, delimiter: codes.delimiter) where reported.insert("code" + c).inserted { + issues.append(PreflightIssue(.error, "Code nicht ersetzt: \(c) (\(f.label))", field: f.id)) + } + } + for (f, text) in allTexts where ["caption", "headline", "personInImage", "objectName"].contains(f.id) { + for token in bareCodes(in: text, codes: codes) where reported.insert("bare" + token).inserted { + issues.append(PreflightIssue(.warning, "„\(token)“ ist ein Code und steht noch im Text (\(f.label))", field: f.id)) + } + } + + // 4. dates in headline / caption vs. capture date + if options.checkDates, let captureDate { + let cal = Calendar(identifier: .gregorian) + for id in ["headline", "caption", "event"] { + guard let text = iptc.text[id] else { continue } + for d in dates(in: text) { + let days = abs(cal.dateComponents([.day], from: cal.startOfDay(for: d), to: cal.startOfDay(for: captureDate)).day ?? 0) + // ±1 day: late kick-off after midnight + if days > 1 { + let f = DateFormatter(); f.dateFormat = "dd.MM.yyyy" + let label = IPTCField.byID[id]?.label ?? id + issues.append(PreflightIssue(.warning, "Datum \(f.string(from: d)) in „\(label)“ passt nicht zur Aufnahme (\(f.string(from: captureDate))) – alte Vorlage?", field: id)) + } + } + } + } + + // 5. IIM lengths + if options.checkLengths { + for f in IPTCField.all { + guard let max = f.iimMaxBytes, f.iimTag != nil, f.id != "dateCreated" else { continue } + if f.kind == .list { + for v in iptc.list(f) where v.utf8.count > max { + issues.append(PreflightIssue(.warning, "\(f.label) „\(v.prefix(30))…“ länger als \(max) Bytes – wird gekürzt", field: f.id)) + } + } else if let v = iptc.text[f.id], v.utf8.count > max { + issues.append(PreflightIssue(.warning, "\(f.label) zu lang (\(v.utf8.count)/\(max) Bytes) – wird gekürzt", field: f.id)) + } + } + } + + // 6. open jersey suggestions + if options.checkOpenSuggestions, !openSuggestions.isEmpty { + issues.append(PreflightIssue(.warning, "Spieler-Vorschlag noch offen: \(openSuggestions.joined(separator: ", "))")) + } + + // 7. image size + if options.minLongEdge > 0, + let w = exif["ImageWidth"].flatMap({ Int($0) }), let h = exif["ImageHeight"].flatMap({ Int($0) }), + max(w, h) < options.minLongEdge { + issues.append(PreflightIssue(.error, "Bild zu klein: \(max(w, h)) px lange Kante (mindestens \(options.minLongEdge) px)")) + } + + return issues.sorted { ($0.severity, $1.message) > ($1.severity, $0.message) } + } + + /// "{city}", "{date}" … left in a text + static func unresolvedVariables(in text: String) -> [String] { + matches(#"\{[A-Za-z][A-Za-z0-9_]*\}"#, in: text) + } + + /// ".w10." / "\h7\" – a code shape (letters + digits) between two delimiters + static func unresolvedDelimiterCodes(in text: String, delimiter: Character) -> [String] { + let d = NSRegularExpression.escapedPattern(for: String(delimiter)) + return matches(d + #"[A-Za-z]{1,5}\d{1,3}(#\d+)?"# + d, in: text) + } + + /// Words like "w10" that are codes of the enabled teams and were not expanded (typed without a space at the end). + static func bareCodes(in text: String, codes: CodeReplacements) -> [String] { + matches(#"(? [Date] { + let f = DateFormatter() + f.locale = Locale(identifier: "de_DE") + f.dateFormat = "dd.MM.yyyy" + return matches(#"\b\d{2}\.\d{2}\.\d{4}\b"#, in: text).compactMap { f.date(from: $0) } + } + + static func matches(_ pattern: String, in text: String) -> [String] { + guard let re = try? NSRegularExpression(pattern: pattern) else { return [] } + let ns = text as NSString + return re.matches(in: text, range: NSRange(location: 0, length: ns.length)).map { ns.substring(with: $0.range) } + } +} diff --git a/Sources/LichtkastenCore/Upload/SentLog.swift b/Sources/LichtkastenCore/Upload/SentLog.swift new file mode 100644 index 0000000..1cb1eb9 --- /dev/null +++ b/Sources/LichtkastenCore/Upload/SentLog.swift @@ -0,0 +1,73 @@ +import Foundation + +/// One successful upload of a file. +public struct SentRecord: Codable, Hashable, Sendable { + /// FTP destination id (uuid string) or "immich" + public var destination: String + /// Destination name at the time of sending ("Beautiful Sports – Sport") + public var destinationName: String + /// File name on the server (after renaming) + public var remoteName: String + public var date: Date + public var size: Int64 + + public init(destination: String, destinationName: String, remoteName: String, date: Date = Date(), size: Int64 = 0) { + self.destination = destination; self.destinationName = destinationName + self.remoteName = remoteName; self.date = date; self.size = size + } +} + +/// Upload history per file ("Gesendet"-Status). Keyed by the standardized file path; a photo counts as sent +/// when any of its files (RAW, JPEG companion) was sent. +public struct SentLog: Codable, Sendable { + public private(set) var records: [String: [SentRecord]] = [:] + + public init() {} + + public static func key(_ url: URL) -> String { url.standardizedFileURL.path } + + public mutating func record(_ url: URL, _ r: SentRecord) { + records[SentLog.key(url), default: []].append(r) + } + + /// Forget the history of these files ("Als nicht gesendet markieren"). + public mutating func clear(_ urls: [URL]) { + for u in urls { records[SentLog.key(u)] = nil } + } + + public func records(for urls: [URL]) -> [SentRecord] { + urls.flatMap { records[SentLog.key($0)] ?? [] }.sorted { $0.date < $1.date } + } + + public func records(for item: PhotoItem) -> [SentRecord] { + records(for: [item.primary] + item.companions) + } + + public func wasSent(_ item: PhotoItem, to destination: String? = nil) -> Bool { + let r = records(for: item) + guard let destination else { return !r.isEmpty } + return r.contains { $0.destination == destination } + } + + /// Short summary for the thumbnail / panels, newest first. + public func summary(for item: PhotoItem) -> SentSummary? { + 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) + } +} + +public struct SentSummary: Hashable, Sendable { + public var count: Int + public var destinations: [String] + public var last: Date + public var lastDestination: 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)" + } +} diff --git a/Tests/LichtkastenCoreTests/CoreTests.swift b/Tests/LichtkastenCoreTests/CoreTests.swift index f30ead7..959ac32 100644 --- a/Tests/LichtkastenCoreTests/CoreTests.swift +++ b/Tests/LichtkastenCoreTests/CoreTests.swift @@ -267,3 +267,113 @@ final class JerseyLogicTests: XCTestCase { XCTAssertEqual(Set(m[0].regions), [.shirt, .shorts]) } } + +final class SpieltagTests: XCTestCase { + func sample() -> (MatchPlan, TeamProfile, TeamProfile, Competition, SpieltagPatterns) { + var home = TeamProfile(name: "VfL Wolfsburg", shortName: "Wolfsburg (F)", abbreviation: "VFL", + keywords: "VfL Wolfsburg, VfL, Wölfe, Wölfinnen", + venue: Venue(name: "AOK Stadion", city: "Wolfsburg", state: "Niedersachsen")) + home.codePrefix = "w" + let away = TeamProfile(name: "TSG 1899 Hoffenheim", shortName: "Hoffenheim (F)", abbreviation: "TSG", keywords: "TSG 1899 Hoffenheim, TSG") + let comp = Competition(name: "DFB-Pokal Frauen", longName: "DFB-Pokal der Frauen", sport: "Fußball", + keywords: "DFB Pokal, DFB Pokal Frauen", + notice: "DFB REGULATIONS PROHIBIT ANY USE OF PHOTOGRAPHS AS IMAGE SEQUENCES AND/OR QUASI-VIDEO.") + var f = DateComponents(); f.year = 2026; f.month = 11; f.day = 2; f.hour = 18 + let date = Calendar(identifier: .gregorian).date(from: f)! + let match = MatchPlan(homeID: home.id, awayID: away.id, competitionID: comp.id, round: "Achtelfinale", + date: date, venue: home.venue) + var p = SpieltagPatterns() + p.generalKeywords = "Fußball, Frauenfußball" + return (match, home, away, comp, p) + } + + func testGeneratesLeonsStructure() { + let (m, h, a, c, p) = sample() + let t = SpieltagGenerator.makeTemplate(match: m, home: h, away: a, competition: c, patterns: p, base: nil) + XCTAssertEqual(t.values.text["headline"], "DFB-Pokal Frauen: VfL Wolfsburg vs. TSG 1899 Hoffenheim, 02.11.2026") + XCTAssertEqual(t.values.text["event"], "DFB-Pokal Frauen: VfL Wolfsburg - TSG 1899 Hoffenheim") + XCTAssertEqual(t.values.text["caption"], + "\n\n\n; Fußball, DFB-Pokal der Frauen, Achtelfinale: VfL Wolfsburg vs. TSG 1899 Hoffenheim am 02.11.2026 im AOK Stadion, Wolfsburg\n\nDFB REGULATIONS PROHIBIT ANY USE OF PHOTOGRAPHS AS IMAGE SEQUENCES AND/OR QUASI-VIDEO.") + XCTAssertEqual(t.values.text["sublocation"], "AOK Stadion") + XCTAssertEqual(t.values.text["dateCreated"], "{capturetime}") + let kw = t.values.lists["keywords"] ?? [] + XCTAssertTrue(kw.contains("VFLTSG")) + XCTAssertTrue(kw.contains("Saison 26/27")) + XCTAssertTrue(kw.contains("Achtelfinale")) + XCTAssertEqual(kw.filter { $0 == "VfL Wolfsburg" }.count, 1) + } + + func testEmptyRoundIsTidied() { + var (m, h, a, c, p) = sample() + m.round = "" + let ctx = SpieltagGenerator.context(match: m, home: h, away: a, competition: c, patterns: p) + XCTAssertTrue(SpieltagGenerator.fill(p.caption, ctx).contains("; Fußball, DFB-Pokal der Frauen: VfL Wolfsburg")) + XCTAssertEqual(SpieltagGenerator.folderName(patterns: p, ctx: ctx), "02.11.2026 - Wolfsburg (F) - Hoffenheim (F)") + } + + func testSeason() { + var c = DateComponents(); c.year = 2027; c.month = 3; c.day = 1 + XCTAssertEqual(SpieltagGenerator.season(for: Calendar(identifier: .gregorian).date(from: c)!), "26/27") + } + + func testBaseTemplateKeepsAppliedFieldsAndCreator() { + let (m, h, a, c, p) = sample() + let base = IPTCTemplate(name: "Basis", values: IPTCValues(text: ["creator": "Leon Tonhäuser", "copyright": "© Beautiful Sports/Tonhäuser"]), + listMergeMode: .replace, appliedFields: ["creator", "copyright"]) + let t = SpieltagGenerator.makeTemplate(match: m, home: h, away: a, competition: c, patterns: p, base: base) + XCTAssertEqual(t.values.text["creator"], "Leon Tonhäuser") + XCTAssertTrue(t.appliedFields?.contains("headline") == true) + XCTAssertTrue(t.appliedFields?.contains("creator") == true) + XCTAssertNotEqual(t.id, base.id) + } +} + +final class PreflightTests: XCTestCase { + func testFindsTypicalAgencyMistakes() { + var v = IPTCValues() + v.text["caption"] = "\n\n; Fußball am 02.11.2026 {city} .w10." + v.text["headline"] = "DFB-Pokal, 02.11.2026" + v.text["creator"] = "Leon" + var codes = CodeReplacements(table: ["w10": ["Svenja Huth (VfL Wolfsburg, 10)"]]) + codes.delimiter = "." + var opts = PreflightOptions() + opts.requiredFields = ["caption", "headline", "creator", "copyright"] + var c = DateComponents(); c.year = 2026; c.month = 11; c.day = 9; c.hour = 15 + let capture = Calendar(identifier: .gregorian).date(from: c)! + let issues = Preflight.check(iptc: v, exif: [:], captureDate: capture, codes: codes, options: opts) + let messages = issues.map(\.message).joined(separator: "\n") + XCTAssertTrue(messages.contains("Pflichtfeld leer: Copyright")) + XCTAssertTrue(messages.contains("Erste Zeile")) + XCTAssertTrue(messages.contains("{city}")) + XCTAssertTrue(messages.contains(".w10.")) + XCTAssertTrue(messages.contains("alte Vorlage")) + XCTAssertEqual(issues.first?.severity, .error) + } + + func testCleanCaptionPasses() { + var v = IPTCValues() + v.text["caption"] = "Svenja Huth (VfL Wolfsburg, 10)\n\n; Fußball am 02.11.2026" + v.text["headline"] = "DFB-Pokal, 02.11.2026" + var opts = PreflightOptions() + opts.requiredFields = ["caption", "headline"] + var c = DateComponents(); c.year = 2026; c.month = 11; c.day = 2; c.hour = 20 + let issues = Preflight.check(iptc: v, exif: [:], captureDate: Calendar(identifier: .gregorian).date(from: c), + codes: CodeReplacements(), options: opts) + XCTAssertTrue(issues.isEmpty, issues.map(\.message).joined(separator: ", ")) + } +} + +final class SentLogTests: XCTestCase { + func testItemCountsAsSentViaCompanion() { + var log = SentLog() + let item = PhotoItem(primary: URL(fileURLWithPath: "/x/a.NEF"), companions: [URL(fileURLWithPath: "/x/a.JPG")]) + XCTAssertFalse(log.wasSent(item)) + log.record(URL(fileURLWithPath: "/x/a.JPG"), SentRecord(destination: "d1", destinationName: "Sport", remoteName: "a.jpg")) + XCTAssertTrue(log.wasSent(item)) + XCTAssertTrue(log.wasSent(item, to: "d1")) + XCTAssertFalse(log.wasSent(item, to: "immich")) + XCTAssertEqual(log.summary(for: item)?.destinations, ["Sport"]) + log.clear([URL(fileURLWithPath: "/x/a.JPG")]) + XCTAssertFalse(log.wasSent(item)) + } +}