Files
lichtkasten/Sources/LichtkastenCore/Metadata/CodeLibrary.swift
T
Lichtkasten DevandClaude Opus 5.5 1f63714b73 Bugfixes aus dem Projekt-Review (27 Punkte)
Datenverlust:
- Ingest löscht keine vorhandenen Fotos mehr: gleiche Namen (zweiter Body/zweite Karte) bekommen -1, -2 …
- Ingest-Vorlage nur auf die neu kopierten Fotos, nicht auf den ganzen Ordner
- Neue Dateien brechen das Laden der Metadaten nicht mehr ab
- Code-Dateien in Windows-1252/Mac Roman werden nicht mehr als UTF-16-Zeichensalat gelesen
- Code-Bibliothek und Teams werden tolerant gelesen (fehlende Felder löschen nichts mehr)
- IPTC-Fenster speichert offene Änderungen, wenn das Bild von außen gewechselt wird
- Datum mit Uhrzeit bleibt beim Speichern erhalten; Lightroom-„abgelehnt“ (-1) bleibt erhalten
- gesperrte Fotos: beim Ingest nur getaggt, Sterne aus der Kamera bleiben

Zuverlässigkeit:
- exiftool-Fehlermeldungen werden sicher erkannt (Marker auf stderr statt 5 ms warten)
- ein defektes Bild kostet nicht mehr 49 andere ihre Metadaten
- LR-Export: Upload/IPTC auch nach Ordnerwechsel, Zeitlimit für Jobs ohne Antwort
- Trikot-Erkennung bleibt beim Ordnerwechsel beim richtigen Ordner; nach Ingest mit den neuen Fotos
- Absturz beim Löschen eines FTP-Servers behoben
- doppelte Namen beim FTP-Umbenennen werden nummeriert; Wiederholen öffnet die Aufgabe wieder
- Vorschau-Cache beachtet die angeforderte Größe (echte 100 %-Ansicht)
- Ingest: Verlauf auch bei Abbruch gespeichert, keine Lücken in der Laufnummer
- Auswerfen schließt keine Tabs anderer Karten; eigener exiftool-Pfad hat Vorrang

Tempo: Massenänderungen sortieren die Liste einmal statt pro Bild, Einstellungen werden verzögert gespeichert.
Tests für Namenskollision, Kodierung, tolerante Code-Bibliothek und Datum mit Uhrzeit.

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

172 lines
7.8 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
/// One code line: "w10 ⇥ Svenja Huth (VfL Wolfsburg, 10) ⇥ …"
public struct CodeEntry: Codable, Hashable, Identifiable, Sendable {
public var id = UUID()
public var code: String
public var columns: [String]
public init(code: String, columns: [String]) { self.code = code; self.columns = columns }
enum CodingKeys: String, CodingKey { case code, columns }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
code = try c.decode(String.self, forKey: .code)
columns = try c.decodeIfPresent([String].self, forKey: .columns) ?? []
}
}
/// A team (or any group of codes) – like one enabled file in PM's Code Replacement list,
/// but stored in the app so players can be added by hand and merged from new TXT files.
public struct CodeSet: Codable, Hashable, Identifiable, Sendable {
public var id = UUID()
public var name: String
public var enabled = true
public var entries: [CodeEntry] = []
/// TXT file the team was imported from (for "Reload" / auto reload).
public var sourcePath: String?
public var sourceModified: Date?
public init(name: String, entries: [CodeEntry] = [], sourcePath: String? = nil) {
self.name = name; self.entries = entries; self.sourcePath = sourcePath
}
enum CodingKeys: String, CodingKey { case id, name, enabled, entries, sourcePath, sourceModified }
/// Tolerant: a missing/new field must never cost the players.
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)) ?? "Team"
enabled = (try? c.decode(Bool.self, forKey: .enabled)) ?? true
entries = (try? c.decode([CodeEntry].self, forKey: .entries)) ?? []
sourcePath = try? c.decode(String.self, forKey: .sourcePath)
sourceModified = try? c.decode(Date.self, forKey: .sourceModified)
}
/// Adds only codes that are not in the team yet (existing players stay untouched).
@discardableResult
public mutating func merge(_ new: [CodeEntry]) -> (added: Int, existing: Int) {
var known = Set(entries.map { $0.code.lowercased() })
var added = 0, existing = 0
for e in new {
let k = e.code.lowercased()
if known.contains(k) { existing += 1; continue }
entries.append(e)
known.insert(k)
added += 1
}
return (added, existing)
}
}
public struct CodeLibrary: Codable, Sendable {
public var sets: [CodeSet] = []
public var delimiter: String = "\\"
public var defaultReplacement = ""
public var bareCodes = true
public var autoReload = false
public init() {}
enum CodingKeys: String, CodingKey { case sets, delimiter, defaultReplacement, bareCodes, autoReload }
/// Tolerant decoding (see CodeSet).
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
sets = (try? c.decode([CodeSet].self, forKey: .sets)) ?? []
delimiter = (try? c.decode(String.self, forKey: .delimiter)) ?? "\\"
defaultReplacement = (try? c.decode(String.self, forKey: .defaultReplacement)) ?? ""
bareCodes = (try? c.decode(Bool.self, forKey: .bareCodes)) ?? true
autoReload = (try? c.decode(Bool.self, forKey: .autoReload)) ?? false
}
/// Flat lookup table for the enabled teams – first team in the list wins on duplicate codes.
public var replacements: CodeReplacements {
var table: [String: [String]] = [:]
for set in sets where set.enabled {
for e in set.entries where table[e.code.lowercased()] == nil { table[e.code.lowercased()] = e.columns }
}
var r = CodeReplacements(table: table)
r.delimiter = delimiter.first ?? "\\"
r.defaultReplacement = defaultReplacement
r.bareCodes = bareCodes
return r
}
/// Parses PM's tab-delimited code file (code ⇥ replacement ⇥ more columns). '#' lines are comments.
public static func parse(_ text: String) -> [CodeEntry] {
var out: [CodeEntry] = []
for line in text.components(separatedBy: .newlines) {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed.isEmpty || trimmed.hasPrefix("#") { continue }
let cols = line.components(separatedBy: "\t")
guard cols.count >= 2 else { continue }
let code = cols[0].trimmingCharacters(in: .whitespaces)
guard !code.isEmpty else { continue }
out.append(CodeEntry(code: code, columns: cols.dropFirst().map { $0.trimmingCharacters(in: .whitespaces) }))
}
return out
}
/// Reads a code file in UTF-8, UTF-16 (PM sometimes saves that), Windows-1252 or Mac Roman.
public static func readText(_ url: URL) throws -> String {
let data = try Data(contentsOf: url)
// UTF-16 only with a byte order mark – without one, almost any Latin-1 file "decodes" as UTF-16 garbage
if data.starts(with: [0xFF, 0xFE]) || data.starts(with: [0xFE, 0xFF]), let s = String(data: data, encoding: .utf16) {
return s
}
for enc in [String.Encoding.utf8, .windowsCP1252, .macOSRoman] {
if let s = String(data: data, encoding: enc) { return s }
}
return String(decoding: data, as: UTF8.self)
}
/// Imports a TXT: merges into the team with the same source file (or name), otherwise creates a new team.
@discardableResult
public mutating func importFile(_ url: URL, into setID: UUID? = nil) throws -> (team: String, added: Int, existing: Int) {
let entries = CodeLibrary.parse(try CodeLibrary.readText(url))
let mod = (try? FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate]) as? Date
let name = url.deletingPathExtension().lastPathComponent.replacingOccurrences(of: "_", with: " ")
let idx = setID.flatMap { id in sets.firstIndex { $0.id == id } }
?? sets.firstIndex { $0.sourcePath == url.path }
?? sets.firstIndex { $0.name.caseInsensitiveCompare(name) == .orderedSame }
if let i = idx {
let r = sets[i].merge(entries)
if sets[i].sourcePath == nil || setID == nil { sets[i].sourcePath = url.path }
sets[i].sourceModified = mod
return (sets[i].name, r.added, r.existing)
}
var set = CodeSet(name: name, sourcePath: url.path)
let r = set.merge(entries)
set.sourceModified = mod
sets.append(set)
return (name, r.added, r.existing)
}
/// Re-reads all source files (PM "Reload All" / auto reload) – only new codes are added.
@discardableResult
public mutating func reloadAll(onlyChanged: Bool = false) -> Int {
var added = 0
for i in sets.indices {
guard let path = sets[i].sourcePath, FileManager.default.fileExists(atPath: path) else { continue }
let mod = (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate]) as? Date
if onlyChanged, let m = mod, let known = sets[i].sourceModified, m <= known { continue }
guard let text = try? CodeLibrary.readText(URL(fileURLWithPath: path)) else { continue }
added += sets[i].merge(CodeLibrary.parse(text)).added
sets[i].sourceModified = mod
}
return added
}
/// Migration from the old flat code table.
public static func migrate(_ old: CodeReplacements) -> CodeLibrary {
var lib = CodeLibrary()
lib.delimiter = String(old.delimiter)
if !old.table.isEmpty {
lib.sets = [CodeSet(name: "Importiert", entries: old.table.sorted { $0.key < $1.key }.map { CodeEntry(code: $0.key, columns: $0.value) })]
}
return lib
}
}