commit e13cbf416d218d1bc2f3089deea76bde46af356b Author: Lichtkasten Dev Date: Tue Nov 3 22:40:28 2026 +0000 Lichtkasten v0.1: Culling, IPTC (PM-kompatibel), Vorlagen, FTP/Immich, Lightroom-Bridge Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4f1800d --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.build/ +.swiftpm/ +build/ +*.xcodeproj/xcuserdata/ +DerivedData/ +.DS_Store diff --git a/LightroomPlugin/LichtkastenBridge.lrplugin/Bridge.lua b/LightroomPlugin/LichtkastenBridge.lrplugin/Bridge.lua new file mode 100644 index 0000000..400c743 --- /dev/null +++ b/LightroomPlugin/LichtkastenBridge.lrplugin/Bridge.lua @@ -0,0 +1,203 @@ +--[[ Job processing for the Lichtkasten Bridge. + Job file format (one key=value per line, "file=" may repeat): + id, preset, collection, export (0/1), exportFolder, quality (0-100), longEdge (px, 0 = full), + sharpening (none|screen|matte|glossy), colorSpace (sRGB|AdobeRGB), file=/abs/path ... ]] + +local LrApplication = import 'LrApplication' +local LrExportSession = import 'LrExportSession' +local LrFileUtils = import 'LrFileUtils' +local LrPathUtils = import 'LrPathUtils' +local LrLogger = import 'LrLogger' +local LrTasks = import 'LrTasks' + +local log = LrLogger('LichtkastenBridge') + +local Bridge = {} + +local function root() + local appData = LrPathUtils.getStandardFilePath('appData') + return LrPathUtils.child(LrPathUtils.child(appData, 'Lichtkasten'), 'LRBridge') +end + +function Bridge.inbox() return LrPathUtils.child(root(), 'inbox') end +function Bridge.outbox() return LrPathUtils.child(root(), 'outbox') end + +local function ensureDir(path) + if not LrFileUtils.exists(path) then LrFileUtils.createAllDirectories(path) end +end + +function Bridge.heartbeat() + ensureDir(root()) + local f = io.open(LrPathUtils.child(root(), 'heartbeat'), 'w') + if f then f:write(tostring(os.time())); f:close() end +end + +local function parseJob(path) + local job = { files = {}, quality = 90, longEdge = 0, export = false, preset = '', collection = '', + sharpening = 'none', colorSpace = 'sRGB', exportFolder = '' } + local f = io.open(path, 'r') + if not f then return nil end + for line in f:lines() do + local k, v = string.match(line, '^([^=]+)=(.*)$') + if k == 'file' then + if v ~= '' then table.insert(job.files, v) end + elseif k == 'export' then + job.export = (v == '1') + elseif k == 'quality' or k == 'longEdge' then + job[k] = tonumber(v) or job[k] + elseif k then + job[k] = v + end + end + f:close() + return job +end + +local function findPreset(name) + if name == nil or name == '' then return nil end + -- "Ordner/Preset" or just "Preset" + local folderName, presetName = string.match(name, '^(.-)/([^/]+)$') + presetName = presetName or name + for _, folder in ipairs(LrApplication.developPresetFolders()) do + if folderName == nil or folder:getName() == folderName then + for _, preset in ipairs(folder:getDevelopPresets()) do + if preset:getName() == presetName then return preset end + end + end + end + return nil +end + +local function writeResult(job, status, imported, exported, errors) + local outbox = Bridge.outbox() + ensureDir(outbox) + local tmp = LrPathUtils.child(outbox, job.id .. '.tmp') + local f = io.open(tmp, 'w') + if not f then return end + f:write('id=' .. job.id .. '\n') + f:write('status=' .. status .. '\n') + f:write('imported=' .. tostring(imported) .. '\n') + for _, p in ipairs(exported) do f:write('exported=' .. p .. '\n') end + for _, e in ipairs(errors) do f:write('error=' .. string.gsub(tostring(e), '\n', ' ') .. '\n') end + f:close() + os.rename(tmp, LrPathUtils.child(outbox, job.id .. '.result')) +end + +local function exportPhotos(job, photos, exported, errors) + ensureDir(job.exportFolder) + local constrain = (job.longEdge or 0) > 0 + local settings = { + LR_export_destinationType = 'specificFolder', + LR_export_destinationPathPrefix = job.exportFolder, + LR_export_useSubfolder = false, + LR_collisionHandling = 'rename', + LR_format = 'JPEG', + LR_jpeg_quality = (job.quality or 90) / 100, + LR_jpeg_useLimitSize = false, + LR_export_colorSpace = job.colorSpace or 'sRGB', + LR_export_bitDepth = 8, + LR_size_doConstrain = constrain, + LR_size_doNotEnlarge = true, + LR_size_resizeType = 'longEdge', + LR_size_maxHeight = constrain and job.longEdge or 0, + LR_size_maxWidth = constrain and job.longEdge or 0, + LR_size_units = 'pixels', + LR_size_resolution = 300, + LR_size_resolutionUnits = 'inch', + LR_outputSharpeningOn = job.sharpening ~= 'none', + LR_outputSharpeningMedia = (job.sharpening ~= 'none') and job.sharpening or 'screen', + LR_outputSharpeningLevel = 2, + LR_minimizeEmbeddedMetadata = false, + LR_metadata_keywordOptions = 'flat', + LR_removeLocationMetadata = false, + LR_removeFaceMetadata = false, + LR_includeVideoFiles = false, + LR_reimportExportedPhoto = false, + LR_renamingTokensOn = false, + LR_useWatermark = false, + } + local session = LrExportSession({ photosToExport = photos, exportSettings = settings }) + session:doExportOnCurrentTask() + for _, rendition in session:renditions() do + local ok, pathOrMessage = rendition:waitForRender() + if ok then + table.insert(exported, pathOrMessage) + else + table.insert(errors, 'Export: ' .. tostring(pathOrMessage)) + end + end +end + +local function processJob(job) + local catalog = LrApplication.activeCatalog() + local photos, errors, exported = {}, {}, {} + + catalog:withWriteAccessDo('Lichtkasten: Import', function() + for _, path in ipairs(job.files) do + if LrFileUtils.exists(path) then + local photo = catalog:findPhotoByPath(path) + if not photo then + local ok, result = LrTasks.pcall(function() return catalog:addPhoto(path) end) + if ok then photo = result else table.insert(errors, path .. ': ' .. tostring(result)) end + end + if photo then table.insert(photos, photo) end + else + table.insert(errors, 'Datei fehlt: ' .. path) + end + end + end, { timeout = 60 }) + + if #photos > 0 then + local preset = findPreset(job.preset) + if job.preset ~= '' and preset == nil then + table.insert(errors, 'Entwicklungsvorgabe nicht gefunden: ' .. job.preset) + end + catalog:withWriteAccessDo('Lichtkasten: Vorgabe & Sammlung', function() + if preset then + for _, photo in ipairs(photos) do photo:applyDevelopPreset(preset) end + end + if job.collection ~= '' then + local collection = catalog:createCollection(job.collection, nil, true) + if collection then collection:addPhotos(photos) end + end + end, { timeout = 60 }) + + if job.export and job.exportFolder ~= '' then + exportPhotos(job, photos, exported, errors) + end + -- Select the imported photos so the user sees them right away. + pcall(function() catalog:setSelectedPhotos(photos[1], photos) end) + end + + local status = (#errors == 0 or #photos > 0) and 'done' or 'error' + writeResult(job, status, #photos, exported, errors) + log:info(string.format('Job %s: %d importiert, %d exportiert, %d Fehler', job.id, #photos, #exported, #errors)) +end + +--- Processes all pending jobs. Returns the number of processed jobs. +function Bridge.processInbox() + local inbox = Bridge.inbox() + ensureDir(inbox) + local count = 0 + local pending = {} + for path in LrFileUtils.files(inbox) do + if LrPathUtils.extension(path) == 'job' then table.insert(pending, path) end + end + table.sort(pending) + for _, path in ipairs(pending) do + do + local working = LrPathUtils.replaceExtension(path, 'working') + if os.rename(path, working) then + local job = parseJob(working) + if job and job.id then + processJob(job) + count = count + 1 + end + LrFileUtils.delete(working) + end + end + end + return count +end + +return Bridge diff --git a/LightroomPlugin/LichtkastenBridge.lrplugin/Info.lua b/LightroomPlugin/LichtkastenBridge.lrplugin/Info.lua new file mode 100644 index 0000000..49038d6 --- /dev/null +++ b/LightroomPlugin/LichtkastenBridge.lrplugin/Info.lua @@ -0,0 +1,19 @@ +--[[ Lichtkasten Bridge – Lightroom Classic plug-in + Receives jobs from the Lichtkasten app (import, develop preset, collection, JPEG export). ]] +return { + LrSdkVersion = 10.0, + LrSdkMinimumVersion = 6.0, + LrToolkitIdentifier = 'de.lichtkasten.bridge', + LrPluginName = 'Lichtkasten Bridge', + LrPluginInfoUrl = 'https://gitlab.com/', + LrInitPlugin = 'Init.lua', + LrForceInitPlugin = true, + LrShutdownPlugin = 'Shutdown.lua', + LrExportMenuItems = { + { title = 'Lichtkasten: Inbox jetzt verarbeiten', file = 'ProcessNow.lua' }, + }, + LrLibraryMenuItems = { + { title = 'Lichtkasten: Inbox jetzt verarbeiten', file = 'ProcessNow.lua' }, + }, + VERSION = { major = 0, minor = 1, revision = 0, build = 1 }, +} diff --git a/LightroomPlugin/LichtkastenBridge.lrplugin/Init.lua b/LightroomPlugin/LichtkastenBridge.lrplugin/Init.lua new file mode 100644 index 0000000..d12608a --- /dev/null +++ b/LightroomPlugin/LichtkastenBridge.lrplugin/Init.lua @@ -0,0 +1,18 @@ +local LrTasks = import 'LrTasks' +local LrLogger = import 'LrLogger' +local Bridge = require 'Bridge' + +local log = LrLogger('LichtkastenBridge') +log:enable('logfile') + +_G.LichtkastenRunning = true + +LrTasks.startAsyncTask(function() + log:info('Lichtkasten Bridge gestartet, Inbox: ' .. Bridge.inbox()) + while _G.LichtkastenRunning do + Bridge.heartbeat() + local ok, err = LrTasks.pcall(Bridge.processInbox) + if not ok then log:error('Fehler beim Verarbeiten: ' .. tostring(err)) end + LrTasks.sleep(2) + end +end) diff --git a/LightroomPlugin/LichtkastenBridge.lrplugin/ProcessNow.lua b/LightroomPlugin/LichtkastenBridge.lrplugin/ProcessNow.lua new file mode 100644 index 0000000..e3f790c --- /dev/null +++ b/LightroomPlugin/LichtkastenBridge.lrplugin/ProcessNow.lua @@ -0,0 +1,12 @@ +local LrTasks = import 'LrTasks' +local LrDialogs = import 'LrDialogs' +local Bridge = require 'Bridge' + +LrTasks.startAsyncTask(function() + local ok, result = LrTasks.pcall(Bridge.processInbox) + if ok then + LrDialogs.showBezel('Lichtkasten: ' .. tostring(result or 0) .. ' Auftrag/Aufträge verarbeitet') + else + LrDialogs.message('Lichtkasten Bridge', tostring(result), 'critical') + end +end) diff --git a/LightroomPlugin/LichtkastenBridge.lrplugin/Shutdown.lua b/LightroomPlugin/LichtkastenBridge.lrplugin/Shutdown.lua new file mode 100644 index 0000000..1cbe4a8 --- /dev/null +++ b/LightroomPlugin/LichtkastenBridge.lrplugin/Shutdown.lua @@ -0,0 +1 @@ +_G.LichtkastenRunning = false diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..15d7dde --- /dev/null +++ b/Package.swift @@ -0,0 +1,24 @@ +// swift-tools-version: 5.9 +import PackageDescription + +let package = Package( + name: "Lichtkasten", + platforms: [.macOS(.v14)], + products: [ + .executable(name: "Lichtkasten", targets: ["Lichtkasten"]), + .library(name: "LichtkastenCore", targets: ["LichtkastenCore"]), + ], + targets: [ + .target(name: "LichtkastenCore", path: "Sources/LichtkastenCore"), + .executableTarget( + name: "Lichtkasten", + dependencies: ["LichtkastenCore"], + path: "Sources/Lichtkasten" + ), + .testTarget( + name: "LichtkastenCoreTests", + dependencies: ["LichtkastenCore"], + path: "Tests/LichtkastenCoreTests" + ), + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..c9e8df3 --- /dev/null +++ b/README.md @@ -0,0 +1,79 @@ +# Lichtkasten + +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. + +## Funktionen + +| Bereich | Was geht | +|---|---| +| **Culling** | Kontaktabzug über die eingebetteten RAW-Vorschauen (ImageIO), RAW+JPEG als Paar, Vollbildvorschau, 100-%-Ansicht (Z), Filter (Tag, Sterne, Farbe), Suche, Sortierung | +| **Bewertung** | Sterne, Farbmarkierungen und Tags. Gespeichert als `xmp:Rating`, `xmp:Label` und `photomechanic:Tagged/ColorClass`, damit Lightroom **und** PM die Werte lesen | +| **IPTC** | Alle Felder in der Reihenfolge des PM-Stationery-Pads. Geschrieben werden IIM **und** XMP synchron (UTF-8, `CodedCharacterSet`, `IPTCDigest`), bei RAWs als XMP-Sidecar. Byte-Zähler warnt bei IIM-Limits | +| **Vorlagen** | Vorlagen anlegen, Import von Photo-Mechanic-Vorlagen (`.xmp`), Import aus Bildern mit IPTC, Export als XMP, Stichwörter anhängen oder ersetzen | +| **Variablen & Codes** | `{date}`, `{city}`, `{filenamebase}`, `{model}` usw. sowie PM-Code-Ersetzungen `\code\` und `\code#2\` aus Tab-Dateien | +| **Ingest** | Von einer oder mehreren Karten kopieren, mit Backup-Ziel, Ordner- und Umbenennungsmuster, Vorlage beim Ingest | +| **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) | + +## Voraussetzungen + +- macOS 14 Sonoma oder neuer, Xcode 15 oder neuer (mit Xcode 16 getestet) +- [exiftool](https://exiftool.org): `brew install exiftool` +- Optional für SFTP mit Passwort: `brew install curl` + +## Bauen + +```bash +git clone && cd Lichtkasten +./scripts/build-app.sh # → build/Lichtkasten.app +open build/Lichtkasten.app +``` + +Zum Entwickeln `Package.swift` in Xcode öffnen und das Scheme **Lichtkasten** starten. `swift test` führt die Core-Tests aus. + +## Tastatur + +| Taste | Lightroom-Belegung (Standard) | PM-Belegung | +|---|---|---| +| 0–5 | Sterne | 1–5 Farbklasse, 0 = keine | +| ⌥0–5 | – | Sterne | +| 6/7/8/9 | Rot/Gelb/Grün/Blau | – | +| T | Tag umschalten | Tag umschalten | +| Leertaste / ↩ | Vorschau ↔ Kontaktabzug | | +| Z | 100 % in der Vorschau | | +| ⌘I | IPTC-Bereich | | +| ⌘⇧I | Vorlage anwenden | | +| ⌘⇧V | Letzte Vorlage erneut | | +| ⌘↩ | IPTC-Änderungen übernehmen | | +| ⌘⇧L | An Lightroom senden | | +| ⌘⌥L | LR: Vorgabe + JPEG-Export (+ Upload) | | +| ⌘⇧U | Upload zum ersten FTP-Profil | | +| ⌘⇧M | Upload zu Immich | | +| ⌘G | Ingest | | + +## Lightroom-Bridge + +`LightroomPlugin/LichtkastenBridge.lrplugin` ist ein kleines Lightroom-Classic-Plugin. +Installation: Einstellungen → Lightroom → **Plugin installieren**, danach Lightroom neu starten. +Alternativ in Lightroom über **Datei → Zusatzmodul-Manager → Hinzufügen**. + +Ablauf: Lichtkasten legt einen Auftrag nach `~/Library/Application Support/Lichtkasten/LRBridge/inbox`. Das Plugin +prüft diesen Ordner alle 2 Sekunden. Es importiert die Dateien (dabei liest LR die XMP-Sidecars mit Sternen und IPTC), +wendet die Entwicklungsvorgabe an, fügt die Bilder einer Sammlung hinzu und exportiert auf Wunsch JPEGs. Danach schreibt +Lichtkasten den Original-IPTC-Block wieder in die JPEGs (PM-identischer Aufbau) und lädt sie hoch. + +Hinweis zu den Farbmarkierungen: Lightroom zeigt Labels nur mit dem Label-Satz **„Lightroom-Standard“** korrekt an. +Lichtkasten schreibt die englischen Werte `Red/Yellow/Green/Blue/Purple`. + +## Aufbau + +``` +Sources/LichtkastenCore reine Logik (Foundation): IPTC-Felder, Vorlagen, Variablen, exiftool, FTP, Immich, LR-Jobs, Ingest +Sources/Lichtkasten SwiftUI-App +LightroomPlugin Lua-Plugin für Lightroom Classic +Tests XCTest für den Core +``` diff --git a/Resources/Info.plist b/Resources/Info.plist new file mode 100644 index 0000000..3110b3b --- /dev/null +++ b/Resources/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleNameLichtkasten + CFBundleDisplayNameLichtkasten + CFBundleIdentifierde.lichtkasten.app + CFBundleExecutableLichtkasten + CFBundlePackageTypeAPPL + CFBundleShortVersionString0.1.0 + CFBundleVersion1 + LSMinimumSystemVersion14.0 + LSApplicationCategoryTypepublic.app-category.photography + NSHighResolutionCapable + NSPrincipalClassNSApplication + NSRemovableVolumesUsageDescriptionLichtkasten liest Bilder von Speicherkarten für den Ingest. + NSDesktopFolderUsageDescriptionLichtkasten zeigt und verschlagwortet Bilder in diesem Ordner. + NSDocumentsFolderUsageDescriptionLichtkasten zeigt und verschlagwortet Bilder in diesem Ordner. + NSDownloadsFolderUsageDescriptionLichtkasten zeigt und verschlagwortet Bilder in diesem Ordner. + NSAppleEventsUsageDescriptionLichtkasten startet Lightroom Classic für den Import. + + diff --git a/Sources/Lichtkasten/LichtkastenApp.swift b/Sources/Lichtkasten/LichtkastenApp.swift new file mode 100644 index 0000000..88dc20e --- /dev/null +++ b/Sources/Lichtkasten/LichtkastenApp.swift @@ -0,0 +1,102 @@ +import AppKit +import SwiftUI +import LichtkastenCore + +final class AppDelegate: NSObject, NSApplicationDelegate { + func applicationDidFinishLaunching(_ notification: Notification) { + // Needed when started via `swift run` (no app bundle). + NSApp.setActivationPolicy(.regular) + NSApp.activate(ignoringOtherApps: true) + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true } +} + +@main +struct LichtkastenApp: App { + @NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate + @StateObject private var state = AppState() + + var body: some Scene { + WindowGroup("Lichtkasten") { + ContentView() + .environmentObject(state) + .environmentObject(state.uploads) + .frame(minWidth: 1000, minHeight: 640) + } + .commands { AppCommands(state: state) } + + Settings { + SettingsView() + .environmentObject(state) + .frame(width: 720, height: 560) + } + } +} + +struct AppCommands: Commands { + @ObservedObject var state: AppState + + var body: some Commands { + CommandGroup(after: .newItem) { + Button("Ordner öffnen …") { state.chooseFolder() }.keyboardShortcut("o") + Button("Ingest (von Karte kopieren) …") { state.showIngest = true }.keyboardShortcut("g") + Button("Ordner neu laden") { state.reload() }.keyboardShortcut("r") + Divider() + Button("Im Finder zeigen") { + NSWorkspace.shared.activateFileViewerSelecting(state.selectedItems.map(\.primary)) + }.keyboardShortcut("r", modifiers: [.command, .shift]) + } + CommandMenu("Bild") { + Button("Alle auswählen") { state.selectAll() }.keyboardShortcut("a", modifiers: [.command, .option]) + Button("Getaggte auswählen") { state.selectTagged() }.keyboardShortcut("t", modifiers: [.command, .option]) + Button("Auswahl aufheben") { state.deselectAll() }.keyboardShortcut("d") + Divider() + Button("Tag umschalten (T)") { state.toggleTag() } + Menu("Bewertung") { + ForEach(0...5, id: \.self) { n in + Button(n == 0 ? "Keine" : String(repeating: "★", count: n)) { state.setRating(n) } + } + } + Menu("Farbmarkierung") { + ForEach(ColorLabel.allCases, id: \.self) { l in Button(l.germanName) { state.setLabel(l) } } + Button("Keine") { state.setLabel(nil) } + } + Divider() + Button(state.previewMode ? "Kontaktabzug (Leertaste)" : "Vorschau (Leertaste)") { state.previewMode.toggle() } + Button(state.showInspector ? "IPTC-Bereich ausblenden" : "IPTC-Bereich einblenden") { state.showInspector.toggle() } + .keyboardShortcut("i") + } + CommandMenu("IPTC") { + Button("Vorlage anwenden …") { state.showTemplatePicker = true }.keyboardShortcut("i", modifiers: [.command, .shift]) + Button("Letzte Vorlage erneut anwenden") { + if let id = state.settings.lastTemplateID, let t = state.templates.first(where: { $0.id == id }) { + state.applyTemplate(t) + } + }.keyboardShortcut("v", modifiers: [.command, .shift]) + Button("Vorlagen verwalten …") { state.showTemplateManager = true }.keyboardShortcut("t", modifiers: [.command, .shift]) + Divider() + Button("Photo-Mechanic-Vorlage importieren …") { state.importPMTemplate() } + Button("Code-Ersetzungen laden …") { state.importCodeReplacements() } + } + CommandMenu("Ausgabe") { + Button("An Lightroom Classic senden") { state.sendToLightroom(export: false) } + .keyboardShortcut("l", modifiers: [.command, .shift]) + Button("Lightroom: Vorgabe anwenden + JPEG exportieren") { state.sendToLightroom(export: true) } + .keyboardShortcut("l", modifiers: [.command, .option]) + Divider() + ForEach(Array(state.settings.ftpDestinations.enumerated()), id: \.element.id) { idx, d in + if idx == 0 { + Button("FTP: \(d.name)") { state.upload(to: d.id.uuidString) }.keyboardShortcut("u", modifiers: [.command, .shift]) + } else { + Button("FTP: \(d.name)") { state.upload(to: d.id.uuidString) } + } + } + Button("Zu Immich hochladen") { state.upload(to: "immich") } + .keyboardShortcut("m", modifiers: [.command, .shift]) + .disabled(!state.settings.immich.enabled) + Divider() + Button("Upload-Warteschlange") { state.showUploads = true }.keyboardShortcut("u", modifiers: [.command, .option]) + } + } +} diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift new file mode 100644 index 0000000..7484ed4 --- /dev/null +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -0,0 +1,500 @@ +import AppKit +import SwiftUI +import LichtkastenCore + +enum ItemFilter: Hashable { + case all, tagged, untagged, minRating(Int), label(ColorLabel) + + var title: String { + switch self { + case .all: return "Alle" + case .tagged: return "Getaggt" + case .untagged: return "Nicht getaggt" + case .minRating(let n): return "≥ \(n) ★" + case .label(let l): return l.germanName + } + } +} + +enum SortOrder: String, CaseIterable { + case captureTime = "Aufnahmezeit" + case filename = "Dateiname" +} + +struct AppAlert: Identifiable { + let id = UUID() + let title: String + let message: String +} + +@MainActor +final class AppState: ObservableObject { + @Published private(set) var items: [PhotoItem] = [] + @Published var folder: URL? + @Published var selection: Set = [] + @Published var cursorID: String? + @Published var filter: ItemFilter = .all { didSet { rebuildVisible() } } + @Published var sortOrder: SortOrder = .captureTime { didSet { rebuildVisible() } } + @Published var searchText = "" { didSet { rebuildVisible() } } + @Published private(set) var visible: [PhotoItem] = [] + @Published var previewMode = false + @Published var zoom100 = false + @Published var showInspector = true + @Published var loadingMetadata = false + @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 codes: CodeReplacements { didSet { Storage.save(codes, to: Storage.codesURL) } } + @Published var gridColumns = 5 + + // Sheets + @Published var showTemplatePicker = false + @Published var showTemplateManager = false + @Published var showIngest = false + @Published var showUploads = false + + let uploads = UploadQueue() + private var indexByID: [String: Int] = [:] + private var exiftoolInstance: ExifTool? + private var lrPollTimer: Timer? + private var pendingLRJobs: [String: LightroomJob] = [:] + @Published var lrPendingCount = 0 + + init() { + settings = Storage.load(AppSettings.self, from: Storage.settingsURL) ?? AppSettings() + templates = Storage.load([IPTCTemplate].self, from: Storage.templatesURL) ?? [] + codes = Storage.load(CodeReplacements.self, from: Storage.codesURL) ?? CodeReplacements() + uploads.state = self + startLightroomPolling() + } + + // MARK: exiftool + + var exiftool: ExifTool? { + if let e = exiftoolInstance { return e } + guard let url = ExifTool.locate(custom: settings.exiftoolPath) else { return nil } + let e = ExifTool(executable: url) + exiftoolInstance = e + return e + } + + func requireExifTool() -> ExifTool? { + if let e = exiftool { return e } + alert = AppAlert(title: "exiftool fehlt", message: ExifToolError.notInstalled.localizedDescription) + return nil + } + + var writer: MetadataWriter? { requireExifTool().map { MetadataWriter(exiftool: $0) } } + + func resetExifTool() { + exiftoolInstance?.shutdown() + exiftoolInstance = nil + } + + // MARK: Folder loading + + func chooseFolder() { + let panel = NSOpenPanel() + panel.canChooseDirectories = true + panel.canChooseFiles = false + panel.allowsMultipleSelection = false + panel.prompt = "Öffnen" + if panel.runModal() == .OK, let url = panel.url { open(folder: url) } + } + + func open(folder url: URL) { + folder = url + settings.recentFolders.removeAll { $0 == url.path } + settings.recentFolders.insert(url.path, at: 0) + settings.recentFolders = Array(settings.recentFolders.prefix(15)) + do { + let scanned = try FolderScanner.scan(folder: url) + setItems(scanned) + selection = [] + cursorID = visible.first?.id + if let c = cursorID { selection = [c] } + statusText = "\(scanned.count) Bilder" + Task { await loadMetadata() } + } catch { + alert = AppAlert(title: "Ordner konnte nicht gelesen werden", message: error.localizedDescription) + } + } + + func reload() { if let f = folder { open(folder: f) } } + + private func setItems(_ new: [PhotoItem]) { + items = new + indexByID = Dictionary(uniqueKeysWithValues: items.enumerated().map { ($1.id, $0) }) + rebuildVisible() + } + + private func rebuildVisible() { + var list = items.filter { item in + switch filter { + case .all: return true + case .tagged: return item.tagged + case .untagged: return !item.tagged + case .minRating(let n): return item.rating >= n + case .label(let l): return item.label == l + } + } + let q = searchText.trimmingCharacters(in: .whitespaces).lowercased() + if !q.isEmpty { + list = list.filter { item in + item.filename.lowercased().contains(q) + || item.iptc.text.values.contains { $0.lowercased().contains(q) } + || item.iptc.lists.values.contains { $0.contains { $0.lowercased().contains(q) } } + } + } + switch sortOrder { + case .filename: + list.sort { $0.filename.localizedStandardCompare($1.filename) == .orderedAscending } + case .captureTime: + list.sort { ($0.captureDate ?? $0.modified, $0.filename) < ($1.captureDate ?? $1.modified, $1.filename) } + } + visible = list + } + + func loadMetadata() async { + guard let et = requireExifTool() else { return } + loadingMetadata = true + defer { loadingMetadata = false } + let snapshot = items + let chunkSize = 40 + var start = 0 + while start < snapshot.count { + let chunk = Array(snapshot[start.. PhotoItem? { indexByID[id].map { items[$0] } } + + var selectedItems: [PhotoItem] { + let ids = selection.isEmpty ? Set([cursorID].compactMap { $0 }) : selection + return visible.filter { ids.contains($0.id) } + } + + var cursorItem: PhotoItem? { cursorID.flatMap { item($0) } } + + func click(_ id: String, modifiers: NSEvent.ModifierFlags) { + if modifiers.contains(.command) { + if selection.contains(id) { selection.remove(id) } else { selection.insert(id) } + cursorID = id + } else if modifiers.contains(.shift), let anchor = cursorID, + let a = visible.firstIndex(where: { $0.id == anchor }), let b = visible.firstIndex(where: { $0.id == id }) { + let range = min(a, b)...max(a, b) + selection.formUnion(visible[range].map(\.id)) + } else { + selection = [id] + cursorID = id + } + } + + func moveCursor(by delta: Int, extend: Bool = false) { + guard !visible.isEmpty else { return } + let current = cursorID.flatMap { id in visible.firstIndex { $0.id == id } } ?? -1 + let next = max(0, min(visible.count - 1, current + delta)) + let id = visible[next].id + cursorID = id + if extend { selection.insert(id) } else { selection = [id] } + if previewMode { + let around = [next + 1, next + 2, next - 1].filter { $0 >= 0 && $0 < visible.count } + ImageLoader.shared.prefetchPreviews(around.map { previewURL(for: visible[$0]) }) + } + } + + func selectAll() { selection = Set(visible.map(\.id)) } + func deselectAll() { selection = cursorID.map { [$0] } ?? [] } + func selectTagged() { selection = Set(visible.filter(\.tagged).map(\.id)) } + + func previewURL(for item: PhotoItem) -> URL { item.jpegForUpload ?? item.primary } + + // MARK: Rating / labels / tags + + private func mutate(_ targets: [PhotoItem], _ change: (inout PhotoItem) -> Void) { + for t in targets { if let i = indexByID[t.id] { change(&items[i]) } } + rebuildVisible() + } + + private var actionTargets: [PhotoItem] { + if previewMode, let c = cursorItem { return [c] } + return selectedItems + } + + private func advanceIfSingle(_ count: Int) { + if settings.autoAdvance && count == 1 { moveCursor(by: 1) } + } + + func setRating(_ n: Int) { + let targets = actionTargets + guard !targets.isEmpty, let w = writer else { return } + mutate(targets) { $0.rating = n } + Task { for t in targets { do { try await w.writeRating(n, to: t) } catch { report(error) } } } + advanceIfSingle(targets.count) + } + + func setLabel(_ l: ColorLabel?) { + let targets = actionTargets + 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 + mutate(targets) { $0.label = newLabel } + Task { for t in targets { do { try await w.writeLabel(newLabel, to: t) } catch { report(error) } } } + advanceIfSingle(targets.count) + } + + func toggleTag() { + let targets = actionTargets + guard !targets.isEmpty, let w = writer else { return } + let newValue = !targets.allSatisfy(\.tagged) + mutate(targets) { $0.tagged = newValue } + Task { for t in targets { do { try await w.writeTag(newValue, to: t) } catch { report(error) } } } + advanceIfSingle(targets.count) + } + + func report(_ error: Error) { + alert = AppAlert(title: "Fehler", message: error.localizedDescription) + } + + // MARK: IPTC + + /// Writes edited fields to all selected images, expanding variables/codes per image. + func applyIPTC(_ draft: IPTCValues, fields: [IPTCField]) { + let targets = selectedItems + guard !targets.isEmpty, !fields.isEmpty, let w = writer else { return } + let fmt = settings.dateFormat + let codes = self.codes + statusText = "Schreibe IPTC in \(targets.count) Bild(er)…" + Task { + var count = 0 + for t in targets { + var merged = t.iptc + for f in fields { + if f.kind == .list { merged.lists[f.id] = draft.lists[f.id] } else { merged.text[f.id] = draft.text[f.id] } + } + let ctx = VariableContext.make(fileURL: t.primary, exif: t.exif, iptc: merged, dateFormat: fmt) + let expanded = VariableExpander.expand(merged, context: ctx, codes: codes) + do { + try await w.write(values: expanded, fields: fields, to: t) + mutate([t]) { $0.iptc = expanded } + count += 1 + } catch { report(error); break } + } + statusText = "IPTC in \(count) Bild(er) geschrieben" + } + } + + func applyTemplate(_ template: IPTCTemplate, to targets: [PhotoItem]? = nil) { + let targets = targets ?? selectedItems + Task { await applyTemplateAndWait(template, to: targets) } + } + + func applyTemplateAndWait(_ template: IPTCTemplate, to targets: [PhotoItem]) async { + guard !targets.isEmpty, let w = writer else { return } + settings.lastTemplateID = template.id + statusText = "Wende Vorlage „\(template.name)“ an …" + 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 } } } + statusText = "Vorlage auf \(targets.count) Bild(er) angewendet" + } catch { report(error) } + } + + func importPMTemplate() { + let panel = NSOpenPanel() + panel.allowedContentTypes = [] + panel.allowsOtherFileTypes = true + panel.allowsMultipleSelection = true + panel.message = "Photo Mechanic Vorlage(n) (.xmp) oder Bilder mit IPTC wählen" + guard panel.runModal() == .OK else { return } + for url in panel.urls { + do { + if url.pathExtension.lowercased() == "xmp" || url.pathExtension.lowercased() == "xml" { + templates.append(try XMPTemplateIO.importTemplate(from: url)) + } else { + try templateFromImage(url) + } + } catch { report(error) } + } + } + + /// Creates a template from the IPTC of an existing image (e.g. a JPEG captioned in PM). + func templateFromImage(_ url: URL) throws { + guard let et = requireExifTool() else { return } + Task { + do { + let meta = try await et.readMetadata(files: [url]) + var item = PhotoItem(primary: url) + item.apply(fileMeta: meta[url.path] ?? [:], sidecarMeta: nil) + templates.append(IPTCTemplate(name: url.deletingPathExtension().lastPathComponent, values: item.iptc)) + } catch { report(error) } + } + } + + func exportTemplate(_ t: IPTCTemplate) { + let panel = NSSavePanel() + panel.nameFieldStringValue = t.name + ".xmp" + guard panel.runModal() == .OK, let url = panel.url else { return } + do { try XMPTemplateIO.export(t).write(to: url, atomically: true, encoding: .utf8) } catch { report(error) } + } + + func importCodeReplacements() { + let panel = NSOpenPanel() + panel.allowsMultipleSelection = false + panel.message = "Code-Ersetzungsdatei (Tab-getrennt, wie in Photo Mechanic)" + guard panel.runModal() == .OK, let url = panel.url else { return } + do { + let data = try Data(contentsOf: url) + let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .macOSRoman) ?? "" + let delimiter = codes.delimiter + codes = CodeReplacements.load(tabDelimited: text) + codes.delimiter = delimiter + statusText = "\(codes.table.count) Codes geladen" + } catch { report(error) } + } + + // MARK: Lightroom + + var lightroomAppURL: URL? { + for id in LightroomBridge.lightroomBundleIDs { + if let u = NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) { return u } + } + let guess = URL(fileURLWithPath: "/Applications/Adobe Lightroom Classic/Adobe Lightroom Classic.app") + return FileManager.default.fileExists(atPath: guess.path) ? guess : nil + } + + private func rawOrPrimary(_ items: [PhotoItem]) -> [URL] { items.map { $0.rawFile ?? $0.primary } } + + /// ⌘⇧L – selected images straight into the open LR catalog via the bridge plugin + /// (falls back to LR's import dialog if the plugin is not running). + func sendToLightroom(export: Bool) { + let targets = selectedItems + guard !targets.isEmpty else { return } + let lr = settings.lightroom + if LightroomBridge.pluginIsAlive { + let exportFolder = lr.exportFolder.isEmpty + ? (folder ?? targets[0].primary.deletingLastPathComponent()).appendingPathComponent("Export") + : URL(fileURLWithPath: lr.exportFolder) + let job = LightroomJob(files: rawOrPrimary(targets), developPreset: lr.developPreset, collection: lr.collection, + export: export, exportFolder: export ? exportFolder : nil, jpegQuality: lr.jpegQuality, + longEdge: lr.longEdge, sharpening: lr.sharpening, colorSpace: lr.colorSpace, + rewriteIPTCAfterExport: lr.rewriteIPTCAfterExport, + uploadTargets: export ? lr.autoUploadTargets : []) + do { + try LightroomBridge.submit(job) + pendingLRJobs[job.id] = job + lrPendingCount = pendingLRJobs.count + statusText = "\(targets.count) Bild(er) an Lightroom übergeben" + (export ? " (mit JPEG-Export)" : "") + if let app = lightroomAppURL { NSWorkspace.shared.openApplication(at: app, configuration: .init()) } + } catch { report(error) } + } else { + guard let app = lightroomAppURL else { + alert = AppAlert(title: "Lightroom Classic nicht gefunden", message: "Bitte Lightroom Classic installieren.") + return + } + if export { + alert = AppAlert(title: "Lichtkasten Bridge läuft nicht", + message: "Für Import mit Vorgabe und automatischem JPEG-Export muss Lightroom Classic mit dem Plugin laufen. Einstellungen → Lightroom → Plugin installieren, dann Lightroom (neu) starten.") + return + } + let cfg = NSWorkspace.OpenConfiguration() + NSWorkspace.shared.open(rawOrPrimary(targets), withApplicationAt: app, configuration: cfg) + statusText = "Lightroom-Importdialog geöffnet (Bridge-Plugin nicht aktiv)" + } + } + + private func startLightroomPolling() { + lrPollTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] _ in + Task { @MainActor in self?.pollLightroom() } + } + } + + private func pollLightroom() { + guard !pendingLRJobs.isEmpty else { return } + for result in LightroomBridge.collectResults() { + let job = pendingLRJobs.removeValue(forKey: result.id) + lrPendingCount = pendingLRJobs.count + if !result.errors.isEmpty { + alert = AppAlert(title: "Lightroom meldet Probleme", message: result.errors.joined(separator: "\n")) + } + statusText = "Lightroom: \(result.imported) importiert, \(result.exported.count) JPEG(s) exportiert" + guard let job, !result.exported.isEmpty else { continue } + Task { await handleExported(result.exported, job: job) } + } + } + + /// After LR export: re-apply the original IPTC (PM-identical structure) and upload. + private func handleExported(_ files: [URL], job: LightroomJob) async { + // Map exported JPEG → source item by base name (LR keeps the file name, may append "-2"). + let sources = job.files.compactMap { f in items.first { $0.primary == f || $0.companions.contains(f) } } + if job.rewriteIPTCAfterExport, let w = writer { + for file in files { + let base = file.deletingPathExtension().lastPathComponent + guard let src = sources.first(where: { base == $0.baseName || base.hasPrefix($0.baseName + "-") }) else { continue } + let jpegItem = PhotoItem(primary: file) + do { try await w.write(values: src.iptc, fields: IPTCField.all, to: jpegItem) } catch { report(error) } + } + } + for target in job.uploadTargets { + uploads.enqueue(files: files, target: target) + } + if !job.uploadTargets.isEmpty { showUploads = true } + } + + // MARK: Upload + + /// Files to upload for an item, depending on the destination's variant. + func uploadFiles(for item: PhotoItem, variant: UploadVariant) -> [URL] { + switch variant { + case .jpeg: return [item.jpegForUpload].compactMap { $0 } + case .original: return [item.primary] + case .both: return Array(Set([item.primary] + [item.jpegForUpload].compactMap { $0 })).sorted { $0.path < $1.path } + } + } + + 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 + } + 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) + showUploads = true + } +} diff --git a/Sources/Lichtkasten/Services/ImageLoader.swift b/Sources/Lichtkasten/Services/ImageLoader.swift new file mode 100644 index 0000000..c65b936 --- /dev/null +++ b/Sources/Lichtkasten/Services/ImageLoader.swift @@ -0,0 +1,68 @@ +import AppKit +import ImageIO +import LichtkastenCore + +/// Fast thumbnails/previews via ImageIO. RAWs use their embedded JPEG preview first (like PM), +/// and fall back to Apple's RAW engine only if the embedded preview is too small. +final class ImageLoader: @unchecked Sendable { + static let shared = ImageLoader() + + private let thumbs = NSCache() + private let previews = NSCache() + private let queue = OperationQueue() + + init() { + thumbs.countLimit = 4000 + previews.countLimit = 12 + queue.maxConcurrentOperationCount = 6 + queue.qualityOfService = .userInitiated + } + + func cachedThumbnail(_ url: URL) -> NSImage? { thumbs.object(forKey: url.path as NSString) } + func cachedPreview(_ url: URL) -> NSImage? { previews.object(forKey: url.path as NSString) } + + func thumbnail(for url: URL, maxPixel: Int = 480) async -> NSImage? { + if let c = cachedThumbnail(url) { return c } + return await withCheckedContinuation { cont in + queue.addOperation { + let img = Self.makeImage(url, maxPixel: maxPixel, minAcceptable: 240) + if let img { self.thumbs.setObject(img, forKey: url.path as NSString) } + cont.resume(returning: img) + } + } + } + + func preview(for url: URL, maxPixel: Int = 3200) async -> NSImage? { + if let c = cachedPreview(url) { return c } + return await withCheckedContinuation { cont in + queue.addOperation { + let img = Self.makeImage(url, maxPixel: maxPixel, minAcceptable: 1400) + if let img { self.previews.setObject(img, forKey: url.path as NSString) } + cont.resume(returning: img) + } + } + } + + func prefetchPreviews(_ urls: [URL]) { + for u in urls where cachedPreview(u) == nil { + Task { _ = await preview(for: u) } + } + } + + static func makeImage(_ url: URL, maxPixel: Int, minAcceptable: Int) -> NSImage? { + guard let src = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil } + var opts: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageIfAbsent: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: maxPixel, + kCGImageSourceShouldCacheImmediately: true, + ] + var cg = CGImageSourceCreateThumbnailAtIndex(src, 0, opts as CFDictionary) + if let c = cg, max(c.width, c.height) < minAcceptable { + opts[kCGImageSourceCreateThumbnailFromImageAlways] = true + if let better = CGImageSourceCreateThumbnailAtIndex(src, 0, opts as CFDictionary) { cg = better } + } + guard let cg else { return nil } + return NSImage(cgImage: cg, size: NSSize(width: cg.width, height: cg.height)) + } +} diff --git a/Sources/Lichtkasten/Services/KeyboardMonitor.swift b/Sources/Lichtkasten/Services/KeyboardMonitor.swift new file mode 100644 index 0000000..b922e37 --- /dev/null +++ b/Sources/Lichtkasten/Services/KeyboardMonitor.swift @@ -0,0 +1,70 @@ +import AppKit +import LichtkastenCore + +/// Global key handling for culling (works regardless of SwiftUI focus, ignores text fields). +@MainActor +final class KeyboardMonitor { + private var monitor: Any? + weak var state: AppState? + + func install(state: AppState) { + self.state = state + guard monitor == nil else { return } + monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in + guard let self, let state = self.state else { return event } + return self.handle(event, state: state) ? nil : event + } + } + + private func isTyping(_ event: NSEvent) -> Bool { + guard let window = event.window else { return true } + if window.attachedSheet != nil || window.isSheet || window != NSApp.mainWindow { return true } + return window.firstResponder is NSText || window.firstResponder is NSTextView + } + + private func handle(_ event: NSEvent, state: AppState) -> Bool { + if isTyping(event) { return false } + let mods = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + let shift = mods.contains(.shift) + if mods.contains(.command) || mods.contains(.control) { return false } + + switch event.keyCode { + case 123: state.moveCursor(by: -1, extend: shift); return true // ← + case 124: state.moveCursor(by: 1, extend: shift); return true // → + case 126: state.moveCursor(by: state.previewMode ? -1 : -state.gridColumns, extend: shift); return true // ↑ + case 125: state.moveCursor(by: state.previewMode ? 1 : state.gridColumns, extend: shift); return true // ↓ + case 49, 36, 76: state.previewMode.toggle(); return true // Space / Return + case 53: if state.previewMode { state.previewMode = false; return true }; return false // Esc + case 115: state.moveCursor(by: -100_000); return true // Home + case 119: state.moveCursor(by: 100_000); return true // End + default: break + } + + guard let ch = event.charactersIgnoringModifiers?.lowercased(), let c = ch.first else { return false } + if c == "t" { state.toggleTag(); return true } + if c == "z", state.previewMode { state.zoom100.toggle(); return true } + guard let digit = c.wholeNumberValue else { return false } + + switch state.settings.keyScheme { + case .lightroom: + switch digit { + case 0...5: state.setRating(digit) + case 6: state.setLabel(.red) + case 7: state.setLabel(.yellow) + case 8: state.setLabel(.green) + case 9: state.setLabel(.blue) + default: return false + } + case .photoMechanic: + if mods.contains(.option) { + guard digit <= 5 else { return false } + state.setRating(digit) + } else if digit == 0 { + state.setLabel(nil) + } else if let l = ColorLabel(pmColorClass: digit) { + state.setLabel(l) + } else { return false } + } + return true + } +} diff --git a/Sources/Lichtkasten/Services/Keychain.swift b/Sources/Lichtkasten/Services/Keychain.swift new file mode 100644 index 0000000..892cb3a --- /dev/null +++ b/Sources/Lichtkasten/Services/Keychain.swift @@ -0,0 +1,30 @@ +import Foundation +import Security + +/// Passwords / API keys in the macOS login keychain. +enum Keychain { + static let service = "de.lichtkasten.app" + + static func set(_ value: String, account: String) { + let base: [String: Any] = [kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account] + SecItemDelete(base as CFDictionary) + guard !value.isEmpty else { return } + var add = base + add[kSecValueData as String] = Data(value.utf8) + add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock + SecItemAdd(add as CFDictionary, nil) + } + + static func get(_ account: String) -> String? { + let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne] + var out: AnyObject? + guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil } + return String(data: d, encoding: .utf8) + } +} diff --git a/Sources/Lichtkasten/Services/Persistence.swift b/Sources/Lichtkasten/Services/Persistence.swift new file mode 100644 index 0000000..892aa27 --- /dev/null +++ b/Sources/Lichtkasten/Services/Persistence.swift @@ -0,0 +1,81 @@ +import Foundation +import LichtkastenCore + +enum KeyScheme: String, Codable, CaseIterable { + case lightroom = "Lightroom (0–5 Sterne, 6–9 Farben)" + case photoMechanic = "Photo Mechanic (1–8 Farbklassen, ⌥1–5 Sterne)" +} + +struct LightroomSettings: Codable, Hashable { + var developPreset = "" + var collection = "Lichtkasten" + var exportFolder = "" + var jpegQuality = 90 + var longEdge = 0 + var sharpening = "none" + var colorSpace = "sRGB" + var rewriteIPTCAfterExport = true + /// Upload targets after export: FTP destination ids and/or "immich". + var autoUploadTargets: [String] = [] +} + +struct AppSettings: Codable { + var exiftoolPath = "" + var dateFormat = "dd.MM.yyyy" + var keyScheme: KeyScheme = .lightroom + var thumbnailSize: Double = 200 + var autoAdvance = true // after rating/tagging jump to next image (PM: "Auto-advance") + var ftpDestinations: [FTPDestination] = [] + var immich = ImmichSettings() + var lightroom = LightroomSettings() + var ingest = IngestSettings() + var recentFolders: [String] = [] + var favoriteFolders: [String] = [] + var lastTemplateID: UUID? + + init() {} + + // Tolerant decoding so new settings never wipe old ones. + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = AppSettings() + exiftoolPath = (try? c.decode(String.self, forKey: .exiftoolPath)) ?? d.exiftoolPath + dateFormat = (try? c.decode(String.self, forKey: .dateFormat)) ?? d.dateFormat + keyScheme = (try? c.decode(KeyScheme.self, forKey: .keyScheme)) ?? d.keyScheme + thumbnailSize = (try? c.decode(Double.self, forKey: .thumbnailSize)) ?? d.thumbnailSize + autoAdvance = (try? c.decode(Bool.self, forKey: .autoAdvance)) ?? d.autoAdvance + ftpDestinations = (try? c.decode([FTPDestination].self, forKey: .ftpDestinations)) ?? d.ftpDestinations + immich = (try? c.decode(ImmichSettings.self, forKey: .immich)) ?? d.immich + lightroom = (try? c.decode(LightroomSettings.self, forKey: .lightroom)) ?? d.lightroom + ingest = (try? c.decode(IngestSettings.self, forKey: .ingest)) ?? d.ingest + recentFolders = (try? c.decode([String].self, forKey: .recentFolders)) ?? d.recentFolders + favoriteFolders = (try? c.decode([String].self, forKey: .favoriteFolders)) ?? d.favoriteFolders + lastTemplateID = try? c.decode(UUID.self, forKey: .lastTemplateID) + } +} + +enum Storage { + static var appSupport: URL { + let u = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appendingPathComponent("Lichtkasten", isDirectory: true) + try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true) + return u + } + static var settingsURL: URL { appSupport.appendingPathComponent("settings.json") } + static var templatesURL: URL { appSupport.appendingPathComponent("templates.json") } + static var codesURL: URL { appSupport.appendingPathComponent("codes.json") } + + static func load(_ type: T.Type, from url: URL) -> T? { + guard let d = try? Data(contentsOf: url) else { return nil } + let dec = JSONDecoder() + dec.dateDecodingStrategy = .iso8601 + return try? dec.decode(T.self, from: d) + } + + static func save(_ value: T, to url: URL) { + let enc = JSONEncoder() + enc.outputFormatting = [.prettyPrinted, .sortedKeys] + enc.dateEncodingStrategy = .iso8601 + if let d = try? enc.encode(value) { try? d.write(to: url, options: .atomic) } + } +} diff --git a/Sources/Lichtkasten/Services/UploadQueue.swift b/Sources/Lichtkasten/Services/UploadQueue.swift new file mode 100644 index 0000000..d9fce28 --- /dev/null +++ b/Sources/Lichtkasten/Services/UploadQueue.swift @@ -0,0 +1,131 @@ +import Foundation +import SwiftUI +import LichtkastenCore + +struct UploadJob: Identifiable { + enum Status: Equatable { case waiting, running, done, duplicate, failed(String) } + let id = UUID() + let file: URL + let target: String // FTP destination id or "immich" + let targetName: String + let remoteName: String + let captureDate: Date? + var status: Status = .waiting + var attempts = 0 +} + +/// Upload queue for FTP destinations and Immich (2 parallel transfers, 2 retries). +@MainActor +final class UploadQueue: ObservableObject { + @Published var jobs: [UploadJob] = [] + weak var state: AppState? + private var running = 0 + private let maxParallel = 2 + private var immichClient: ImmichClient? + private var immichAlbumId: String? + private var immichNewAssets: [String] = [] + + var activeCount: Int { jobs.filter { $0.status == .waiting || $0.status == .running }.count } + var failedCount: Int { jobs.filter { if case .failed = $0.status { return true } else { return false } }.count } + + func enqueue(files: [URL], target: String, sourceItems: [PhotoItem] = []) { + guard let state else { return } + let name: String + var pattern = "" + if target == "immich" { + name = "Immich" + } else if let d = state.settings.ftpDestinations.first(where: { $0.id.uuidString == target }) { + name = d.name + pattern = d.renamePattern + } else { return } + for f in files { + let src = sourceItems.first { $0.primary == f || $0.companions.contains(f) } + var remote = f.lastPathComponent + if !pattern.isEmpty { + let ctx = VariableContext.make(fileURL: f, exif: src?.exif ?? [:], iptc: src?.iptc ?? IPTCValues(), + dateFormat: state.settings.dateFormat) + remote = VariableExpander.expand(pattern, context: ctx) + .replacingOccurrences(of: "/", with: "-") + "." + f.pathExtension.lowercased() + } + jobs.append(UploadJob(file: f, target: target, targetName: name, remoteName: remote, captureDate: src?.captureDate)) + } + pump() + } + + func retryFailed() { + for i in jobs.indices { if case .failed = jobs[i].status { jobs[i].status = .waiting; jobs[i].attempts = 0 } } + pump() + } + + func clearFinished() { + jobs.removeAll { $0.status == .done || $0.status == .duplicate } + } + + private func pump() { + while running < maxParallel, let idx = jobs.firstIndex(where: { $0.status == .waiting }) { + jobs[idx].status = .running + jobs[idx].attempts += 1 + running += 1 + let job = jobs[idx] + Task { await self.run(job) } + } + if running == 0 { finishImmichBatch() } + } + + private func setStatus(_ id: UUID, _ s: UploadJob.Status) { + if let i = jobs.firstIndex(where: { $0.id == id }) { jobs[i].status = s } + } + + private func run(_ job: UploadJob) async { + defer { running -= 1; pump() } + guard let state else { return } + do { + if job.target == "immich" { + let client = try immich(state) + let r = try await client.upload(file: job.file, captureDate: job.captureDate) + if !r.duplicate { immichNewAssets.append(r.assetId) } + setStatus(job.id, r.duplicate ? .duplicate : .done) + } else { + guard let d = state.settings.ftpDestinations.first(where: { $0.id.uuidString == job.target }) else { + setStatus(job.id, .failed("Server-Profil gelöscht")); return + } + try await FTPUploader().upload(file: job.file, remoteName: job.remoteName, to: d, + password: Keychain.get(d.keychainAccount)) + setStatus(job.id, .done) + } + } catch { + if let i = jobs.firstIndex(where: { $0.id == job.id }), jobs[i].attempts < 3 { + jobs[i].status = .waiting + } else { + setStatus(job.id, .failed(error.localizedDescription)) + } + } + } + + private func immich(_ state: AppState) throws -> ImmichClient { + if let c = immichClient { return c } + let key = Keychain.get(ImmichSettings.keychainAccount) ?? "" + let c = try ImmichClient(settings: state.settings.immich, apiKey: key) + immichClient = c + return c + } + + /// Settings changed → rebuild client next time. + func resetImmich() { immichClient = nil; immichAlbumId = nil } + + private func finishImmichBatch() { + guard !immichNewAssets.isEmpty, let state, let client = immichClient else { return } + let album = state.settings.immich.albumName.trimmingCharacters(in: .whitespaces) + let ids = immichNewAssets + immichNewAssets = [] + guard !album.isEmpty else { return } + Task { + do { + let albumId = try await client.albumId(named: album) + try await client.add(assetIds: ids, toAlbum: albumId) + } catch { + state.report(error) + } + } + } +} diff --git a/Sources/Lichtkasten/Views/ContactSheetView.swift b/Sources/Lichtkasten/Views/ContactSheetView.swift new file mode 100644 index 0000000..69790fb --- /dev/null +++ b/Sources/Lichtkasten/Views/ContactSheetView.swift @@ -0,0 +1,156 @@ +import SwiftUI +import LichtkastenCore + +struct ContactSheetView: View { + @EnvironmentObject var state: AppState + + var body: some View { + GeometryReader { geo in + let size = CGFloat(state.settings.thumbnailSize) + let spacing: CGFloat = 10 + let cols = max(1, Int((geo.size.width - 20 + spacing) / (size + spacing))) + ScrollViewReader { proxy in + ScrollView { + LazyVGrid(columns: Array(repeating: GridItem(.fixed(size), spacing: spacing), count: cols), spacing: spacing) { + ForEach(state.visible) { item in + ThumbnailCell(item: item, size: size, + selected: state.selection.contains(item.id), + isCursor: state.cursorID == item.id) + .id(item.id) + .contentShape(Rectangle()) + .gesture(TapGesture(count: 2).onEnded { + state.cursorID = item.id + state.selection = [item.id] + state.previewMode = true + }.exclusively(before: TapGesture().onEnded { + state.click(item.id, modifiers: NSEvent.modifierFlags) + })) + .contextMenu { ItemContextMenu(item: item) } + } + } + .padding(10) + } + .background(Color(nsColor: .underPageBackgroundColor)) + .onChange(of: state.cursorID) { _, id in + if let id { proxy.scrollTo(id) } + } + .onAppear { state.gridColumns = cols } + .onChange(of: cols) { _, c in state.gridColumns = c } + } + } + } +} + +struct ItemContextMenu: View { + @EnvironmentObject var state: AppState + let item: PhotoItem + + var body: some View { + Button("Tag umschalten") { ensureSelected(); state.toggleTag() } + Menu("Bewertung") { + ForEach(0...5, id: \.self) { n in + Button(n == 0 ? "Keine" : String(repeating: "★", count: n)) { ensureSelected(); state.setRating(n) } + } + } + Menu("Farbmarkierung") { + ForEach(ColorLabel.allCases, id: \.self) { l in Button(l.germanName) { ensureSelected(); state.setLabel(l) } } + } + Divider() + Button("An Lightroom senden") { ensureSelected(); state.sendToLightroom(export: false) } + Button("Im Finder zeigen") { NSWorkspace.shared.activateFileViewerSelecting([item.primary]) } + Button("Als Vorlage übernehmen") { + state.templates.append(IPTCTemplate(name: item.baseName, values: item.iptc)) + } + } + + private func ensureSelected() { + if !state.selection.contains(item.id) { state.selection = [item.id]; state.cursorID = item.id } + } +} + +struct ThumbnailCell: View { + @EnvironmentObject var state: AppState + let item: PhotoItem + let size: CGFloat + let selected: Bool + let isCursor: Bool + @State private var image: NSImage? + + var body: some View { + VStack(spacing: 4) { + ZStack { + Rectangle().fill(Color.black.opacity(0.25)) + if let image { + Image(nsImage: image).resizable().interpolation(.medium).scaledToFit() + } else { + ProgressView().controlSize(.small) + } + } + .frame(width: size - 12, height: (size - 12) * 0.72) + .clipped() + + HStack(spacing: 4) { + Button { + if !state.selection.contains(item.id) { state.selection = [item.id]; state.cursorID = item.id } + state.toggleTag() + } label: { + Image(systemName: item.tagged ? "checkmark.square.fill" : "square") + .foregroundStyle(item.tagged ? Color.accentColor : .secondary) + } + .buttonStyle(.plain) + .help("Tag (T)") + + Text(item.filename).font(.caption).lineLimit(1).truncationMode(.middle) + Spacer(minLength: 2) + if !item.companions.isEmpty { + Text("+\(item.companions.map { $0.pathExtension.uppercased() }.joined(separator: "+"))") + .font(.system(size: 9, weight: .semibold)) + .padding(.horizontal, 3) + .background(RoundedRectangle(cornerRadius: 3).fill(Color.secondary.opacity(0.25))) + } + } + HStack(spacing: 1) { + ForEach(1...5, id: \.self) { n in + Image(systemName: n <= item.rating ? "star.fill" : "star") + .font(.system(size: 9)) + .foregroundStyle(n <= item.rating ? Color.yellow : Color.secondary.opacity(0.4)) + } + Spacer() + if !item.iptc.isEmpty(IPTCField.byID["caption"]!) { + Image(systemName: "text.alignleft").font(.system(size: 9)).foregroundStyle(.secondary) + .help("Hat Bildunterschrift") + } + } + } + .padding(6) + .frame(width: size) + .background( + RoundedRectangle(cornerRadius: 6) + .fill(selected ? Color.accentColor.opacity(0.35) : Color.gray.opacity(0.14)) + ) + .overlay( + RoundedRectangle(cornerRadius: 6) + .strokeBorder(item.label.map(\.color) ?? .clear, lineWidth: 3) + ) + .overlay( + RoundedRectangle(cornerRadius: 6) + .strokeBorder(isCursor ? Color.white.opacity(0.9) : .clear, lineWidth: 1) + ) + .task(id: item.primary) { + image = ImageLoader.shared.cachedThumbnail(state.previewURL(for: item)) + if image == nil { image = await ImageLoader.shared.thumbnail(for: state.previewURL(for: item)) } + } + } +} + +extension ColorLabel { + var color: Color { + switch self { + case .red: return .red + case .yellow: return .yellow + case .green: return .green + case .blue: return .blue + case .purple: return .purple + } + } +} diff --git a/Sources/Lichtkasten/Views/ContentView.swift b/Sources/Lichtkasten/Views/ContentView.swift new file mode 100644 index 0000000..c87bf81 --- /dev/null +++ b/Sources/Lichtkasten/Views/ContentView.swift @@ -0,0 +1,198 @@ +import SwiftUI +import LichtkastenCore + +struct ContentView: View { + @EnvironmentObject var state: AppState + @EnvironmentObject var uploads: UploadQueue + @State private var keyboard = KeyboardMonitor() + + var body: some View { + NavigationSplitView { + SidebarView() + .navigationSplitViewColumnWidth(min: 180, ideal: 220) + } detail: { + VStack(spacing: 0) { + if state.folder == nil { + EmptyStateView() + } else if state.previewMode { + PreviewView() + } else { + ContactSheetView() + } + StatusBar() + } + .inspector(isPresented: $state.showInspector) { + IPTCInspectorView() + .inspectorColumnWidth(min: 300, ideal: 360, max: 520) + } + } + .navigationTitle(state.folder?.lastPathComponent ?? "Lichtkasten") + .toolbar { MainToolbar() } + .searchable(text: $state.searchText, placement: .toolbar, prompt: "Dateiname, IPTC …") + .onAppear { keyboard.install(state: state) } + .sheet(isPresented: $state.showTemplatePicker) { TemplatePickerSheet() } + .sheet(isPresented: $state.showTemplateManager) { TemplateManagerView().frame(minWidth: 900, minHeight: 620) } + .sheet(isPresented: $state.showIngest) { IngestView() } + .sheet(isPresented: $state.showUploads) { UploadsView() } + .alert(item: $state.alert) { a in + Alert(title: Text(a.title), message: Text(a.message), dismissButton: .default(Text("OK"))) + } + } +} + +struct EmptyStateView: View { + @EnvironmentObject var state: AppState + var body: some View { + VStack(spacing: 16) { + Image(systemName: "photo.on.rectangle.angled").font(.system(size: 56)).foregroundStyle(.secondary) + Text("Ordner öffnen oder Karte ingesten").font(.title2) + HStack { + Button("Ordner öffnen … (⌘O)") { state.chooseFolder() } + Button("Ingest … (⌘G)") { state.showIngest = true } + } + .controlSize(.large) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} + +struct MainToolbar: ToolbarContent { + @EnvironmentObject var state: AppState + @EnvironmentObject var uploads: UploadQueue + + var body: some ToolbarContent { + ToolbarItemGroup(placement: .navigation) { + Button { state.chooseFolder() } label: { Label("Öffnen", systemImage: "folder") } + } + ToolbarItemGroup(placement: .primaryAction) { + Picker("Filter", selection: $state.filter) { + Text("Alle").tag(ItemFilter.all) + Text("Getaggt").tag(ItemFilter.tagged) + Text("Nicht getaggt").tag(ItemFilter.untagged) + Divider() + ForEach(1...5, id: \.self) { n in Text("≥ \(n) ★").tag(ItemFilter.minRating(n)) } + Divider() + ForEach(ColorLabel.allCases, id: \.self) { l in Text(l.germanName).tag(ItemFilter.label(l)) } + } + .frame(width: 130) + .help("Filter") + + Picker("Sortierung", selection: $state.sortOrder) { + ForEach(SortOrder.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + .frame(width: 130) + + Slider(value: $state.settings.thumbnailSize, in: 110...420) + .frame(width: 110) + .help("Vorschaugröße") + + Button { state.showTemplatePicker = true } label: { Label("Vorlage", systemImage: "text.badge.plus") } + .help("IPTC-Vorlage anwenden (⌘⇧I)") + + Menu { + Button("Nur importieren (⌘⇧L)") { state.sendToLightroom(export: false) } + Button("Importieren + Vorgabe + JPEG (⌘⌥L)") { state.sendToLightroom(export: true) } + } label: { + Label("Lightroom", systemImage: "square.and.arrow.up.on.square") + } primaryAction: { + state.sendToLightroom(export: false) + } + .help("Auswahl an Lightroom Classic senden") + + Menu { + ForEach(state.settings.ftpDestinations) { d in + Button("FTP: \(d.name)") { state.upload(to: d.id.uuidString) } + } + if state.settings.immich.enabled { + Button("Immich") { state.upload(to: "immich") } + } + Divider() + Button("Warteschlange anzeigen …") { state.showUploads = true } + } label: { + Label(uploads.activeCount > 0 ? "Upload (\(uploads.activeCount))" : "Upload", systemImage: "icloud.and.arrow.up") + } + + Button { state.showInspector.toggle() } label: { Label("IPTC", systemImage: "sidebar.right") } + } + } +} + +struct StatusBar: View { + @EnvironmentObject var state: AppState + @EnvironmentObject var uploads: UploadQueue + + var body: some View { + HStack(spacing: 12) { + if state.loadingMetadata { ProgressView().controlSize(.small) } + Text(state.statusText).lineLimit(1) + Spacer() + if state.lrPendingCount > 0 { + Label("LR: \(state.lrPendingCount) Auftrag/Aufträge", systemImage: "hourglass") + } + if uploads.activeCount > 0 { + Label("\(uploads.activeCount) Uploads", systemImage: "arrow.up.circle") + .onTapGesture { state.showUploads = true } + } + if uploads.failedCount > 0 { + Label("\(uploads.failedCount) fehlgeschlagen", systemImage: "exclamationmark.triangle.fill") + .foregroundStyle(.red) + .onTapGesture { state.showUploads = true } + } + Text("\(state.selection.count) / \(state.visible.count) ausgewählt") + .foregroundStyle(.secondary) + } + .font(.callout) + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background(.bar) + } +} + +struct SidebarView: View { + @EnvironmentObject var state: AppState + + var body: some View { + List { + Section("Favoriten") { + ForEach(state.settings.favoriteFolders, id: \.self) { path in + folderRow(path) + .contextMenu { Button("Aus Favoriten entfernen") { state.settings.favoriteFolders.removeAll { $0 == path } } } + } + if let f = state.folder, !state.settings.favoriteFolders.contains(f.path) { + Button { state.settings.favoriteFolders.append(f.path) } label: { + Label("Aktuellen Ordner merken", systemImage: "star") + } + .buttonStyle(.borderless) + } + } + Section("Zuletzt") { + ForEach(state.settings.recentFolders, id: \.self) { folderRow($0) } + } + Section("Wechseldatenträger") { + ForEach(volumes(), id: \.self) { v in + Button { state.showIngest = true } label: { Label(v.lastPathComponent, systemImage: "sdcard") } + .buttonStyle(.borderless) + } + } + } + .listStyle(.sidebar) + } + + private func folderRow(_ path: String) -> some View { + let url = URL(fileURLWithPath: path) + return Button { state.open(folder: url) } label: { + Label(url.lastPathComponent, systemImage: state.folder?.path == path ? "folder.fill" : "folder") + } + .buttonStyle(.borderless) + .help(path) + } + + private func volumes() -> [URL] { + let keys: [URLResourceKey] = [.volumeIsRemovableKey] + let vols = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: keys, options: [.skipHiddenVolumes]) ?? [] + return vols.filter { v in + (try? v.resourceValues(forKeys: Set(keys)).volumeIsRemovable) == true + || FileManager.default.fileExists(atPath: v.appendingPathComponent("DCIM").path) + } + } +} diff --git a/Sources/Lichtkasten/Views/IPTCForm.swift b/Sources/Lichtkasten/Views/IPTCForm.swift new file mode 100644 index 0000000..a4b8646 --- /dev/null +++ b/Sources/Lichtkasten/Views/IPTCForm.swift @@ -0,0 +1,209 @@ +import SwiftUI +import LichtkastenCore + +/// Editor texts for all fields (lists are kept as raw "a, b, c" text while typing). +typealias FieldTexts = [String: String] + +extension IPTCValues { + func texts() -> FieldTexts { + var t: FieldTexts = [:] + for f in IPTCField.all { t[f.id] = self[f] } + return t + } + + init(texts: FieldTexts) { + self.init() + for f in IPTCField.all { self[f] = (texts[f.id] ?? "").trimmingCharacters(in: .whitespaces) } + } +} + +/// The field layout used everywhere (inspector + template editor) – PM Stationery Pad order. +struct IPTCFieldsForm: View { + @Binding var texts: FieldTexts + var mixed: Set = [] + var dirty: Set = [] + var onEdit: (String) -> Void = { _ in } + @AppStorage("collapsedIPTCSections") private var collapsedRaw = "" + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + ForEach(IPTCSection.allCases, id: \.self) { section in + let fields = IPTCField.all.filter { $0.section == section } + DisclosureGroup(isExpanded: expandedBinding(section)) { + VStack(alignment: .leading, spacing: 6) { + ForEach(fields) { field in + FieldRow(field: field, text: binding(field), isMixed: mixed.contains(field.id) && !dirty.contains(field.id), + isDirty: dirty.contains(field.id)) + } + } + .padding(.top, 4) + } label: { + Text(section.rawValue).font(.headline) + } + } + } + } + + private func expandedBinding(_ s: IPTCSection) -> Binding { + Binding(get: { !collapsedRaw.components(separatedBy: "|").contains(s.rawValue) }, + set: { expanded in + var set = Set(collapsedRaw.components(separatedBy: "|").filter { !$0.isEmpty }) + if expanded { set.remove(s.rawValue) } else { set.insert(s.rawValue) } + collapsedRaw = set.sorted().joined(separator: "|") + }) + } + + private func binding(_ f: IPTCField) -> Binding { + Binding(get: { texts[f.id] ?? "" }, + set: { texts[f.id] = $0; onEdit(f.id) }) + } +} + +struct FieldRow: View { + let field: IPTCField + @Binding var text: String + let isMixed: Bool + let isDirty: Bool + + private static let variableFields: Set = ["caption", "headline", "objectName", "instructions", "event", + "transmissionReference", "keywords"] + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 4) { + Text(field.label).font(.caption).foregroundStyle(isDirty ? Color.accentColor : .secondary) + if field.kind == .list { Text("(Komma-getrennt)").font(.caption2).foregroundStyle(.tertiary) } + Spacer() + if let max = field.iimMaxBytes { + let used = text.utf8.count + if used > 0 { + Text("\(used)/\(max)") + .font(.caption2.monospacedDigit()) + .foregroundStyle(used > max && !text.contains("{") ? .red : .secondary) + .help("IPTC-IIM-Limit in Bytes. Agenturen kürzen oder lehnen längere Werte ab.") + } + } + if Self.variableFields.contains(field.id) { + Menu { + ForEach(VariableExpander.documented, id: \.0) { v in + Button("\(v.0) – \(v.1)") { text += v.0 } + } + } label: { Image(systemName: "curlybraces") } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .fixedSize() + .help("Variable einfügen") + } + } + if field.kind == .multiline || field.id == "keywords" { + TextField(isMixed ? "‹mehrere Werte›" : "", text: $text, axis: .vertical) + .lineLimit(field.id == "caption" ? 4...12 : 2...6) + .textFieldStyle(.roundedBorder) + } else { + TextField(isMixed ? "‹mehrere Werte›" : "", text: $text) + .textFieldStyle(.roundedBorder) + } + } + } +} + +/// Right-hand inspector: edit IPTC of the current selection. +struct IPTCInspectorView: View { + @EnvironmentObject var state: AppState + @State private var texts: FieldTexts = [:] + @State private var mixed: Set = [] + @State private var dirty: Set = [] + @State private var loadedSelection: [String] = [] + @State private var newTemplateName = "" + @State private var showSaveTemplate = false + + var body: some View { + VStack(spacing: 0) { + header + Divider() + ScrollView { + IPTCFieldsForm(texts: $texts, mixed: mixed, dirty: dirty) { dirty.insert($0) } + .padding(12) + } + Divider() + footer + } + .onAppear(perform: reload) + .onChange(of: state.selection) { _, _ in reload() } + .onChange(of: state.cursorID) { _, _ in if state.selection.isEmpty { reload() } } + .onReceive(state.$items) { _ in + // Refresh when metadata arrives / changes, unless the user is editing. + if dirty.isEmpty { DispatchQueue.main.async { reload() } } + } + .alert("Als Vorlage speichern", isPresented: $showSaveTemplate) { + TextField("Name", text: $newTemplateName) + Button("Speichern") { + let values = IPTCValues(texts: texts) + state.templates.append(IPTCTemplate(name: newTemplateName.isEmpty ? "Neue Vorlage" : newTemplateName, values: values)) + } + Button("Abbrechen", role: .cancel) {} + } + } + + private var header: some View { + HStack { + let n = state.selectedItems.count + VStack(alignment: .leading) { + Text("IPTC").font(.headline) + Text(n == 0 ? "Keine Auswahl" : n == 1 ? state.selectedItems[0].filename : "\(n) Bilder ausgewählt") + .font(.caption).foregroundStyle(.secondary).lineLimit(1) + } + Spacer() + Menu { + ForEach(state.templates) { t in + Button(t.name) { state.applyTemplate(t) } + } + if state.templates.isEmpty { Text("Noch keine Vorlagen") } + Divider() + Button("Vorlagen verwalten …") { state.showTemplateManager = true } + Button("PM-Vorlage importieren …") { state.importPMTemplate() } + } label: { + Label("Vorlage", systemImage: "doc.on.clipboard") + } + .fixedSize() + } + .padding(12) + } + + private var footer: some View { + HStack { + Button("Als Vorlage …") { newTemplateName = ""; showSaveTemplate = true } + Spacer() + Button("Verwerfen") { dirty = []; reload() }.disabled(dirty.isEmpty) + Button("Übernehmen") { + let fields = IPTCField.all.filter { dirty.contains($0.id) } + state.applyIPTC(IPTCValues(texts: texts), fields: fields) + dirty = [] + } + .keyboardShortcut(.return, modifiers: .command) + .buttonStyle(.borderedProminent) + .disabled(dirty.isEmpty || state.selectedItems.isEmpty) + } + .padding(12) + } + + private func reload() { + let items = state.selectedItems + let ids = items.map(\.id) + if ids != loadedSelection { dirty = [] } + loadedSelection = ids + guard dirty.isEmpty else { return } + guard let first = items.first else { texts = [:]; mixed = []; return } + var t = first.iptc.texts() + var m = Set() + for item in items.dropFirst() { + let other = item.iptc.texts() + for f in IPTCField.all where (other[f.id] ?? "") != (t[f.id] ?? "") { + m.insert(f.id) + t[f.id] = "" + } + } + texts = t + mixed = m + } +} diff --git a/Sources/Lichtkasten/Views/IngestView.swift b/Sources/Lichtkasten/Views/IngestView.swift new file mode 100644 index 0000000..44fab5f --- /dev/null +++ b/Sources/Lichtkasten/Views/IngestView.swift @@ -0,0 +1,110 @@ +import SwiftUI +import LichtkastenCore + +struct IngestView: View { + @EnvironmentObject var state: AppState + @Environment(\.dismiss) private var dismiss + @State private var sources: [URL] = [] + @State private var running = false + @State private var progress: IngestProgress? + @State private var error = "" + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Ingest – von Karte kopieren").font(.headline) + Form { + Section("Quelle") { + ForEach(sources, id: \.self) { Text($0.path) } + HStack { + Button("Quelle hinzufügen …") { pickSource() } + Button("Karten automatisch finden") { sources = detectCards() } + if !sources.isEmpty { Button("Leeren") { sources = [] } } + } + } + Section("Ziel") { + folderRow("Hauptziel", path: $state.settings.ingest.primaryDestination) + folderRow("Backup (optional)", path: $state.settings.ingest.backupDestination) + TextField("Unterordner", text: $state.settings.ingest.folderPattern, prompt: Text("{year4}/{isodate}")) + TextField("Umbenennen (leer = Original)", text: $state.settings.ingest.renamePattern, prompt: Text("{isodate}_{seqn4}")) + Stepper("Startnummer {seqn}: \(state.settings.ingest.startSequence)", value: $state.settings.ingest.startSequence, in: 0...999_999) + Toggle("Duplikate überspringen", isOn: $state.settings.ingest.skipDuplicates) + } + Section("Metadaten") { + Picker("IPTC-Vorlage", selection: $state.settings.ingest.templateID) { + Text("Keine").tag(UUID?.none) + ForEach(state.templates) { Text($0.name).tag(UUID?.some($0.id)) } + } + Toggle("Danach Ordner öffnen", isOn: $state.settings.ingest.openAfterIngest) + } + } + .formStyle(.grouped) + if let p = progress { + ProgressView(value: Double(p.done), total: Double(max(p.total, 1))) { + Text("\(p.done)/\(p.total) – \(p.currentFile)").font(.caption) + } + } + if !error.isEmpty { Text(error).foregroundStyle(.red).font(.caption) } + HStack { + Spacer() + Button("Abbrechen") { dismiss() }.keyboardShortcut(.cancelAction).disabled(running) + Button("Ingest starten") { start() } + .keyboardShortcut(.defaultAction) + .disabled(running || sources.isEmpty || state.settings.ingest.primaryDestination.isEmpty) + } + } + .padding(16) + .frame(width: 620, height: 680) + .onAppear { if sources.isEmpty { sources = detectCards() } } + } + + private func folderRow(_ title: String, path: Binding) -> some View { + HStack { + TextField(title, text: path) + Button("Wählen …") { + let p = NSOpenPanel(); p.canChooseDirectories = true; p.canChooseFiles = false; p.canCreateDirectories = true + if p.runModal() == .OK, let u = p.url { path.wrappedValue = u.path } + } + } + } + + private func pickSource() { + let p = NSOpenPanel(); p.canChooseDirectories = true; p.canChooseFiles = false; p.allowsMultipleSelection = true + if p.runModal() == .OK { sources += p.urls } + } + + private func detectCards() -> [URL] { + let vols = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: nil, options: [.skipHiddenVolumes]) ?? [] + return vols.map { $0.appendingPathComponent("DCIM") }.filter { FileManager.default.fileExists(atPath: $0.path) } + } + + private func start() { + guard let et = state.requireExifTool() else { return } + running = true + error = "" + let settings = state.settings.ingest + let srcs = sources + Task { + do { + let folders = try await IngestService.run(sources: srcs, settings: settings, exiftool: et) { p in + Task { @MainActor in progress = p } + } + running = false + if let tid = settings.templateID, let template = state.templates.first(where: { $0.id == tid }) { + for f in folders { + let items = try FolderScanner.scan(folder: f) + let meta = try await et.readMetadata(files: items.map(\.primary)) + let loaded = items.map { item -> PhotoItem in + var i = item; i.apply(fileMeta: meta[item.primary.path] ?? [:], sidecarMeta: nil); return i + } + await state.applyTemplateAndWait(template, to: loaded) + } + } + if settings.openAfterIngest, let first = folders.first { state.open(folder: first) } + dismiss() + } catch let e { + running = false + error = e.localizedDescription + } + } + } +} diff --git a/Sources/Lichtkasten/Views/PreviewView.swift b/Sources/Lichtkasten/Views/PreviewView.swift new file mode 100644 index 0000000..2afce68 --- /dev/null +++ b/Sources/Lichtkasten/Views/PreviewView.swift @@ -0,0 +1,62 @@ +import SwiftUI +import LichtkastenCore + +struct PreviewView: View { + @EnvironmentObject var state: AppState + @State private var image: NSImage? + + var body: some View { + ZStack(alignment: .bottom) { + Color.black + if let image { + if state.zoom100 { + ScrollView([.horizontal, .vertical]) { + Image(nsImage: image) + .frame(width: image.size.width / (NSScreen.main?.backingScaleFactor ?? 2), + height: image.size.height / (NSScreen.main?.backingScaleFactor ?? 2)) + } + } else { + Image(nsImage: image).resizable().scaledToFit().padding(8) + } + } else { + ProgressView() + } + if let item = state.cursorItem { infoBar(item) } + } + .onTapGesture(count: 2) { state.previewMode = false } + .task(id: "\(state.cursorID ?? "")|\(state.zoom100)") { await load() } + } + + private func load() async { + guard let item = state.cursorItem else { image = nil; return } + let url = state.previewURL(for: item) + // Show the thumbnail immediately, then the big preview. + image = ImageLoader.shared.cachedPreview(url) ?? ImageLoader.shared.cachedThumbnail(url) + let maxPixel = state.zoom100 ? 8000 : 3200 + if let big = await ImageLoader.shared.preview(for: url, maxPixel: maxPixel), state.cursorID == item.id { + image = big + } + } + + private func infoBar(_ item: PhotoItem) -> some View { + HStack(spacing: 14) { + Image(systemName: item.tagged ? "checkmark.square.fill" : "square") + Text(item.filename).bold() + HStack(spacing: 1) { + ForEach(1...5, id: \.self) { n in Image(systemName: n <= item.rating ? "star.fill" : "star") } + } + .foregroundStyle(.yellow) + if let l = item.label { Circle().fill(l.color).frame(width: 10, height: 10) } + Spacer() + Text([item.exif["Model"], item.exif["LensModel"], item.exif["FocalLength"], + item.exif["ExposureTime"].map { "\($0) s" }, item.exif["FNumber"].map { "f/\($0)" }, + item.exif["ISO"].map { "ISO \($0)" }].compactMap { $0 }.joined(separator: " · ")) + .foregroundStyle(.secondary) + Text(state.zoom100 ? "100 % (Z)" : "Einpassen (Z)").foregroundStyle(.secondary) + } + .font(.callout) + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background(.ultraThinMaterial) + } +} diff --git a/Sources/Lichtkasten/Views/SettingsView.swift b/Sources/Lichtkasten/Views/SettingsView.swift new file mode 100644 index 0000000..312f290 --- /dev/null +++ b/Sources/Lichtkasten/Views/SettingsView.swift @@ -0,0 +1,270 @@ +import SwiftUI +import LichtkastenCore + +struct SettingsView: View { + var body: some View { + TabView { + GeneralSettings().tabItem { Label("Allgemein", systemImage: "gearshape") } + FTPSettings().tabItem { Label("FTP", systemImage: "server.rack") } + ImmichSettingsView().tabItem { Label("Immich", systemImage: "photo.stack") } + LightroomSettingsView().tabItem { Label("Lightroom", systemImage: "camera.aperture") } + CodesSettings().tabItem { Label("Codes", systemImage: "character.textbox") } + } + .padding(16) + } +} + +struct GeneralSettings: View { + @EnvironmentObject var state: AppState + + var body: some View { + Form { + Section("Tastatur") { + Picker("Belegung", selection: $state.settings.keyScheme) { + ForEach(KeyScheme.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + Toggle("Nach Bewertung/Tag automatisch zum nächsten Bild", isOn: $state.settings.autoAdvance) + Text("T = Tag · Leertaste = Vorschau · Z = 100 % · Pfeile = Navigation · ⌘⌥A = alle auswählen") + .font(.caption).foregroundStyle(.secondary) + } + Section("exiftool") { + HStack { + TextField("Pfad (leer = automatisch)", text: $state.settings.exiftoolPath) + Button("Neu verbinden") { state.resetExifTool() } + } + if let url = ExifTool.locate(custom: state.settings.exiftoolPath) { + Label("Gefunden: \(url.path)", systemImage: "checkmark.circle.fill").foregroundStyle(.green) + } else { + Label("Nicht gefunden – Terminal: brew install exiftool", systemImage: "xmark.octagon.fill").foregroundStyle(.red) + } + } + Section("Variablen") { + TextField("Datumsformat für {date}", text: $state.settings.dateFormat) + Text("z. B. dd.MM.yyyy → 03.11.2026 · d. MMMM yyyy → 3. November 2026") + .font(.caption).foregroundStyle(.secondary) + } + } + .formStyle(.grouped) + } +} + +struct FTPSettings: View { + @EnvironmentObject var state: AppState + @State private var selected: UUID? + @State private var password = "" + @State private var testResult = "" + @State private var testing = false + + private var index: Int? { state.settings.ftpDestinations.firstIndex { $0.id == selected } } + + var body: some View { + HSplitView { + VStack(spacing: 0) { + List(selection: $selected) { + ForEach(state.settings.ftpDestinations) { d in Text(d.name).tag(d.id) } + } + HStack { + Button { let d = FTPDestination(); state.settings.ftpDestinations.append(d); selected = d.id } label: { Image(systemName: "plus") } + Button { + if let i = index { Keychain.set("", account: state.settings.ftpDestinations[i].keychainAccount) + state.settings.ftpDestinations.remove(at: i); selected = nil } + } label: { Image(systemName: "minus") }.disabled(index == nil) + Spacer() + } + .buttonStyle(.borderless).padding(6) + } + .frame(minWidth: 170, maxWidth: 220) + + if let i = index { + Form { + TextField("Name", text: $state.settings.ftpDestinations[i].name) + Picker("Protokoll", selection: Binding( + get: { state.settings.ftpDestinations[i].proto }, + set: { p in + state.settings.ftpDestinations[i].proto = p + state.settings.ftpDestinations[i].port = p.defaultPort + })) { + ForEach(FTPProtocol.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + TextField("Server", text: $state.settings.ftpDestinations[i].host) + TextField("Port", value: $state.settings.ftpDestinations[i].port, format: .number.grouping(.never)) + TextField("Benutzer", text: $state.settings.ftpDestinations[i].username) + SecureField("Passwort (Schlüsselbund)", text: $password) + .onSubmit { Keychain.set(password, account: state.settings.ftpDestinations[i].keychainAccount) } + .onChange(of: password) { _, p in Keychain.set(p, account: state.settings.ftpDestinations[i].keychainAccount) } + if state.settings.ftpDestinations[i].proto == .sftp { + TextField("SSH-Schlüssel (optional)", text: $state.settings.ftpDestinations[i].sshKeyPath) + } + TextField("Zielordner", text: $state.settings.ftpDestinations[i].remoteDirectory) + Picker("Dateien", selection: $state.settings.ftpDestinations[i].variant) { + ForEach(UploadVariant.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + TextField("Umbenennen (leer = Originalname)", text: $state.settings.ftpDestinations[i].renamePattern) + Toggle("Passiver Modus", isOn: $state.settings.ftpDestinations[i].passive) + Toggle("Mit .part hochladen und danach umbenennen", isOn: $state.settings.ftpDestinations[i].uploadWithTempName) + Toggle("TLS-Zertifikat nicht prüfen (nur wenn nötig)", isOn: $state.settings.ftpDestinations[i].allowInsecureTLS) + HStack { + Button("Verbindung testen") { test(state.settings.ftpDestinations[i]) }.disabled(testing) + if testing { ProgressView().controlSize(.small) } + Text(testResult).font(.caption).lineLimit(3) + } + } + .formStyle(.grouped) + .onAppear { password = Keychain.get(state.settings.ftpDestinations[i].keychainAccount) ?? "" } + .onChange(of: selected) { _, _ in + testResult = "" + if let i = index { password = Keychain.get(state.settings.ftpDestinations[i].keychainAccount) ?? "" } + } + } else { + Text("Server hinzufügen oder auswählen").foregroundStyle(.secondary).frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + } + + private func test(_ d: FTPDestination) { + testing = true + testResult = "" + Task { + do { + try await FTPUploader().testConnection(d, password: Keychain.get(d.keychainAccount)) + testResult = "✅ Verbindung OK" + } catch { testResult = "❌ " + error.localizedDescription } + testing = false + } + } +} + +struct ImmichSettingsView: View { + @EnvironmentObject var state: AppState + @State private var apiKey = "" + @State private var result = "" + + var body: some View { + Form { + Toggle("Immich-Upload aktivieren", isOn: $state.settings.immich.enabled) + TextField("Server-URL", text: $state.settings.immich.serverURL, prompt: Text("https://immich.example.de")) + SecureField("API-Schlüssel (Schlüsselbund)", text: $apiKey) + .onChange(of: apiKey) { _, k in Keychain.set(k, account: ImmichSettings.keychainAccount); state.uploads.resetImmich() } + TextField("Album (leer = keins, wird angelegt)", text: $state.settings.immich.albumName) + Picker("Dateien", selection: $state.settings.immich.variant) { + ForEach(UploadVariant.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + HStack { + Button("Verbindung testen") { test() } + Text(result).font(.caption) + } + Text("API-Schlüssel in Immich: Konto-Einstellungen → API-Schlüssel. Benötigte Rechte: asset.upload, album.read, album.create, albumAsset.create.") + .font(.caption).foregroundStyle(.secondary) + } + .formStyle(.grouped) + .onAppear { apiKey = Keychain.get(ImmichSettings.keychainAccount) ?? "" } + .onChange(of: state.settings.immich) { _, _ in state.uploads.resetImmich() } + } + + private func test() { + result = "…" + Task { + do { + let c = try ImmichClient(settings: state.settings.immich, apiKey: apiKey) + result = "✅ Angemeldet als \(try await c.testConnection())" + } catch { result = "❌ " + error.localizedDescription } + } + } +} + +struct LightroomSettingsView: View { + @EnvironmentObject var state: AppState + @State private var pluginMessage = "" + + var body: some View { + Form { + Section("Lichtkasten-Bridge-Plugin") { + HStack { + if LightroomBridge.pluginIsAlive { + Label("Plugin aktiv (Lightroom läuft)", systemImage: "checkmark.circle.fill").foregroundStyle(.green) + } else if LightroomBridge.pluginInstalled { + Label("Installiert – Lightroom starten", systemImage: "pause.circle").foregroundStyle(.orange) + } else { + Label("Nicht installiert", systemImage: "xmark.circle").foregroundStyle(.red) + } + Spacer() + Button(LightroomBridge.pluginInstalled ? "Neu installieren" : "Plugin installieren") { install() } + } + if !pluginMessage.isEmpty { Text(pluginMessage).font(.caption) } + Text("Ohne Plugin öffnet ⌘⇧L den normalen Importdialog von Lightroom.") + .font(.caption).foregroundStyle(.secondary) + } + Section("Import") { + TextField("Entwicklungsvorgabe (exakter Name, optional „Ordner/Name“)", text: $state.settings.lightroom.developPreset) + TextField("Sammlung (leer = keine)", text: $state.settings.lightroom.collection) + } + Section("JPEG-Export (⌘⌥L)") { + HStack { + TextField("Exportordner (leer = Unterordner „Export“)", text: $state.settings.lightroom.exportFolder) + Button("Wählen …") { + let p = NSOpenPanel(); p.canChooseDirectories = true; p.canChooseFiles = false; p.canCreateDirectories = true + if p.runModal() == .OK, let u = p.url { state.settings.lightroom.exportFolder = u.path } + } + } + Stepper("JPEG-Qualität: \(state.settings.lightroom.jpegQuality)", value: $state.settings.lightroom.jpegQuality, in: 50...100, step: 5) + TextField("Lange Kante in px (0 = volle Größe)", value: $state.settings.lightroom.longEdge, format: .number.grouping(.never)) + Picker("Ausgabeschärfung", selection: $state.settings.lightroom.sharpening) { + Text("Keine").tag("none"); Text("Bildschirm").tag("screen"); Text("Matt").tag("matte"); Text("Glanz").tag("glossy") + } + Picker("Farbraum", selection: $state.settings.lightroom.colorSpace) { + Text("sRGB").tag("sRGB"); Text("Adobe RGB").tag("AdobeRGB") + } + Toggle("Original-IPTC nach Export erneut schreiben (PM-identischer Aufbau)", isOn: $state.settings.lightroom.rewriteIPTCAfterExport) + } + Section("Nach dem Export automatisch hochladen") { + ForEach(state.settings.ftpDestinations) { d in + Toggle("FTP: \(d.name)", isOn: uploadBinding(d.id.uuidString)) + } + Toggle("Immich", isOn: uploadBinding("immich")).disabled(!state.settings.immich.enabled) + } + } + .formStyle(.grouped) + } + + private func uploadBinding(_ id: String) -> Binding { + Binding(get: { state.settings.lightroom.autoUploadTargets.contains(id) }, + set: { on in + state.settings.lightroom.autoUploadTargets.removeAll { $0 == id } + if on { state.settings.lightroom.autoUploadTargets.append(id) } + }) + } + + private func install() { + guard let bundle = Bundle.main.url(forResource: "LichtkastenBridge", withExtension: "lrplugin") else { + pluginMessage = "Plugin nicht im App-Bundle gefunden. Bitte LightroomPlugin/LichtkastenBridge.lrplugin über Lightroom → Zusatzmodul-Manager hinzufügen." + return + } + do { + try LightroomBridge.installPlugin(from: bundle) + pluginMessage = "Installiert. Lightroom Classic bitte neu starten." + } catch { pluginMessage = error.localizedDescription } + } +} + +struct CodesSettings: View { + @EnvironmentObject var state: AppState + @State private var testInput = "\\bvb\\ gegen \\s04\\" + + var body: some View { + Form { + Section("Code-Ersetzung (wie Photo Mechanic)") { + HStack { + Text("\(state.codes.table.count) Codes geladen") + Spacer() + Button("Datei laden …") { state.importCodeReplacements() } + Button("Leeren") { state.codes = CodeReplacements() } + } + Text("Tab-getrennte Textdatei: Code ⇥ Ersetzung ⇥ weitere Spalten. Im Text: \\code\\ oder \\code#2\\ für Spalte 2.") + .font(.caption).foregroundStyle(.secondary) + TextField("Test", text: $testInput) + Text(state.codes.expand(testInput)).font(.callout).textSelection(.enabled) + } + } + .formStyle(.grouped) + } +} diff --git a/Sources/Lichtkasten/Views/TemplateViews.swift b/Sources/Lichtkasten/Views/TemplateViews.swift new file mode 100644 index 0000000..e5610af --- /dev/null +++ b/Sources/Lichtkasten/Views/TemplateViews.swift @@ -0,0 +1,169 @@ +import SwiftUI +import UniformTypeIdentifiers +import LichtkastenCore + +/// ⌘⇧I – quick picker (type to filter, Return applies to the selection). +struct TemplatePickerSheet: View { + @EnvironmentObject var state: AppState + @Environment(\.dismiss) private var dismiss + @State private var query = "" + @State private var selected: UUID? + + private var filtered: [IPTCTemplate] { + let q = query.lowercased() + return state.templates.filter { q.isEmpty || $0.name.lowercased().contains(q) } + } + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text("Vorlage auf \(state.selectedItems.count) Bild(er) anwenden").font(.headline) + TextField("Suchen …", text: $query).textFieldStyle(.roundedBorder) + List(filtered, selection: $selected) { t in + VStack(alignment: .leading) { + Text(t.name) + Text(summary(t)).font(.caption).foregroundStyle(.secondary).lineLimit(1) + } + .tag(t.id) + } + .frame(minHeight: 260) + HStack { + Button("Vorlagen verwalten …") { dismiss(); state.showTemplateManager = true } + Spacer() + Button("Abbrechen") { dismiss() }.keyboardShortcut(.cancelAction) + Button("Anwenden") { apply() } + .keyboardShortcut(.defaultAction) + .disabled((selected ?? filtered.first?.id) == nil || state.selectedItems.isEmpty) + } + } + .padding(16) + .frame(width: 520, height: 440) + .onAppear { selected = state.settings.lastTemplateID ?? state.templates.first?.id } + } + + private func summary(_ t: IPTCTemplate) -> String { + ["creator", "credit", "city", "headline", "caption"].compactMap { id in + IPTCField.byID[id].map { t.values[$0] }.flatMap { $0.isEmpty ? nil : $0 } + }.joined(separator: " · ") + } + + private func apply() { + guard let id = selected ?? filtered.first?.id, let t = state.templates.first(where: { $0.id == id }) else { return } + state.applyTemplate(t) + dismiss() + } +} + +struct TemplateManagerView: View { + @EnvironmentObject var state: AppState + @Environment(\.dismiss) private var dismiss + @State private var selected: UUID? + @State private var texts: FieldTexts = [:] + + private var index: Int? { state.templates.firstIndex { $0.id == selected } } + + var body: some View { + VStack(spacing: 0) { + HSplitView { + VStack(spacing: 0) { + List(selection: $selected) { + ForEach(state.templates) { t in Text(t.name).tag(t.id) } + .onMove { state.templates.move(fromOffsets: $0, toOffset: $1) } + } + Divider() + HStack(spacing: 6) { + Button { addNew() } label: { Image(systemName: "plus") }.help("Neue Vorlage") + Button { duplicate() } label: { Image(systemName: "plus.square.on.square") } + .help("Duplizieren").disabled(index == nil) + Button { delete() } label: { Image(systemName: "minus") }.help("Löschen").disabled(index == nil) + Spacer() + Menu { + Button("Photo-Mechanic-Vorlage (.xmp) …") { state.importPMTemplate() } + Button("Aus Bild mit IPTC …") { state.importPMTemplate() } + if let first = state.selectedItems.first { + Button("Aus ausgewähltem Bild (\(first.filename))") { + state.templates.append(IPTCTemplate(name: first.baseName, values: first.iptc)) + } + } + } label: { Text("Importieren") } + .fixedSize() + } + .buttonStyle(.borderless) + .padding(8) + } + .frame(minWidth: 220, idealWidth: 240, maxWidth: 320) + + if let i = index { + VStack(alignment: .leading, spacing: 10) { + HStack { + TextField("Name", text: $state.templates[i].name).font(.title3).textFieldStyle(.roundedBorder) + Button("Als XMP exportieren …") { state.exportTemplate(state.templates[i]) } + } + HStack(spacing: 18) { + Picker("Listenfelder (Stichwörter …)", selection: $state.templates[i].listMergeMode) { + ForEach(ListMergeMode.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + .fixedSize() + Toggle("Leere Felder löschen beim Anwenden", isOn: $state.templates[i].clearEmptyFields) + } + .font(.callout) + if !state.templates[i].extras.isEmpty { + Text("\(state.templates[i].extras.count) zusätzliche XMP-Felder aus PM werden beim Export beibehalten.") + .font(.caption).foregroundStyle(.secondary) + } + Divider() + ScrollView { + IPTCFieldsForm(texts: $texts) { _ in save() } + .padding(.trailing, 8) + } + } + .padding(14) + .frame(minWidth: 520) + } else { + Text("Vorlage auswählen oder neu anlegen").foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + Divider() + HStack { + Text("Variablen wie {date}, {city} und PM-Codes wie \\code\\ werden beim Anwenden pro Bild ersetzt.") + .font(.caption).foregroundStyle(.secondary) + Spacer() + Button("Fertig") { dismiss() }.keyboardShortcut(.defaultAction) + } + .padding(12) + } + .onAppear { selected = selected ?? state.templates.first?.id; loadTexts() } + .onChange(of: selected) { _, _ in loadTexts() } + } + + private func loadTexts() { + if let i = index { texts = state.templates[i].values.texts() } else { texts = [:] } + } + + private func save() { + guard let i = index else { return } + state.templates[i].values = IPTCValues(texts: texts) + state.templates[i].modified = Date() + } + + private func addNew() { + let t = IPTCTemplate(name: "Neue Vorlage") + state.templates.append(t) + selected = t.id + } + + private func duplicate() { + guard let i = index else { return } + var t = state.templates[i] + t.id = UUID() + t.name += " Kopie" + state.templates.append(t) + selected = t.id + } + + private func delete() { + guard let i = index else { return } + state.templates.remove(at: i) + selected = state.templates.first?.id + } +} diff --git a/Sources/Lichtkasten/Views/UploadsView.swift b/Sources/Lichtkasten/Views/UploadsView.swift new file mode 100644 index 0000000..70cc263 --- /dev/null +++ b/Sources/Lichtkasten/Views/UploadsView.swift @@ -0,0 +1,38 @@ +import SwiftUI + +struct UploadsView: View { + @EnvironmentObject var uploads: UploadQueue + @Environment(\.dismiss) private var dismiss + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text("Uploads").font(.headline) + Table(uploads.jobs) { + TableColumn("Datei") { j in Text(j.file.lastPathComponent) } + TableColumn("Als") { j in Text(j.remoteName).foregroundStyle(.secondary) } + TableColumn("Ziel") { j in Text(j.targetName) } + TableColumn("Status") { j in statusView(j.status) } + } + .frame(minHeight: 300) + HStack { + Button("Fehlgeschlagene wiederholen") { uploads.retryFailed() }.disabled(uploads.failedCount == 0) + Button("Erledigte entfernen") { uploads.clearFinished() } + Spacer() + Button("Schließen") { dismiss() }.keyboardShortcut(.defaultAction) + } + } + .padding(16) + .frame(width: 760, height: 460) + } + + @ViewBuilder + private func statusView(_ s: UploadJob.Status) -> some View { + switch s { + case .waiting: Label("Wartet", systemImage: "clock").foregroundStyle(.secondary) + case .running: HStack { ProgressView().controlSize(.small); Text("Lädt …") } + case .done: Label("Fertig", systemImage: "checkmark.circle.fill").foregroundStyle(.green) + case .duplicate: Label("Schon vorhanden", systemImage: "equal.circle").foregroundStyle(.secondary) + case .failed(let m): Label(m, systemImage: "xmark.octagon.fill").foregroundStyle(.red).help(m) + } + } +} diff --git a/Sources/LichtkastenCore/Ingest/IngestService.swift b/Sources/LichtkastenCore/Ingest/IngestService.swift new file mode 100644 index 0000000..c8922e0 --- /dev/null +++ b/Sources/LichtkastenCore/Ingest/IngestService.swift @@ -0,0 +1,87 @@ +import Foundation + +/// Ingest settings (PM: "Ingest"): copy from card to primary + optional backup destination. +public struct IngestSettings: Codable, Hashable, Sendable { + public var primaryDestination: String = "" + public var backupDestination: String = "" + /// Sub folder pattern, e.g. "{year4}/{isodate}_{event}". Empty = directly into destination. + public var folderPattern: String = "{isodate}" + /// Rename pattern without extension, e.g. "{isodate}_{seqn4}". Empty = keep original name. + public var renamePattern: String = "" + public var startSequence: Int = 1 + public var skipDuplicates = true + public var templateID: UUID? + public var openAfterIngest = true + public var onlyNewSinceLastIngest = false + + public init() {} +} + +public struct IngestProgress: Sendable { + public var done: Int + public var total: Int + public var currentFile: String +} + +public enum IngestService { + /// Copies all images (and their XMP sidecars) from `sources`. Returns the destination folders used. + public static func run(sources: [URL], settings: IngestSettings, exiftool: ExifTool, + progress: @escaping @Sendable (IngestProgress) -> Void) async throws -> [URL] { + let fm = FileManager.default + var items: [PhotoItem] = [] + for s in sources { items += try FolderScanner.scan(folder: s, recursive: true) } + guard !settings.primaryDestination.isEmpty else { throw UploadError.failed("Kein Ziel für den Ingest gewählt.") } + + // Read capture dates for folder/rename patterns in one go. + let meta = try await exiftool.readMetadata(files: items.map(\.primary)) + for i in items.indices { + items[i].apply(fileMeta: meta[items[i].primary.path] ?? [:], sidecarMeta: nil) + } + items.sort { ($0.captureDate ?? $0.modified) < ($1.captureDate ?? $1.modified) } + + var usedFolders = Set() + var seq = settings.startSequence + let total = items.reduce(0) { $0 + 1 + $1.companions.count } + var done = 0 + + for item in items { + let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, sequence: seq, iptc: item.iptc) + let sub = VariableExpander.expand(settings.folderPattern, context: ctx) + .replacingOccurrences(of: ":", with: "-") + let baseName = settings.renamePattern.isEmpty + ? item.baseName + : VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-") + seq += 1 + + for destRoot in [settings.primaryDestination, settings.backupDestination] where !destRoot.isEmpty { + let folder = sub.isEmpty ? URL(fileURLWithPath: destRoot) : URL(fileURLWithPath: destRoot).appendingPathComponent(sub) + try fm.createDirectory(at: folder, withIntermediateDirectories: true) + if destRoot == settings.primaryDestination { usedFolders.insert(folder) } + var files = [item.primary] + item.companions + if item.kind.usesSidecar, fm.fileExists(atPath: item.sidecarURL.path) { files.append(item.sidecarURL) } + for src in files { + let dest = folder.appendingPathComponent(baseName).appendingPathExtension(src.pathExtension) + if fm.fileExists(atPath: dest.path) { + if settings.skipDuplicates, sameSize(src, dest) { continue } + try fm.removeItem(at: dest) + } + try fm.copyItem(at: src, to: dest) + if destRoot == settings.primaryDestination { + done += 1 + progress(IngestProgress(done: done, total: total, currentFile: src.lastPathComponent)) + } + } + } + } + return Array(usedFolders).sorted { $0.path < $1.path } + } + + static func sameSize(_ a: URL, _ b: URL) -> Bool { + func size(_ u: URL) -> Int64? { + guard let attrs = try? FileManager.default.attributesOfItem(atPath: u.path) else { return nil } + return (attrs[.size] as? NSNumber)?.int64Value + } + let sa = size(a) + return sa != nil && sa == size(b) + } +} diff --git a/Sources/LichtkastenCore/Library/PhotoItem.swift b/Sources/LichtkastenCore/Library/PhotoItem.swift new file mode 100644 index 0000000..e50e635 --- /dev/null +++ b/Sources/LichtkastenCore/Library/PhotoItem.swift @@ -0,0 +1,190 @@ +import Foundation + +public enum FileKind: String, Sendable, Codable { + case raw, dng, jpeg, heic, tiff, png, other + + public static let rawExtensions: Set = [ + "cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "raf", "orf", "rw2", "pef", + "3fr", "iiq", "erf", "mos", "mrw", "x3f", "srw", "gpr", "rwl", "fff", + ] + + public init(url: URL) { + let ext = url.pathExtension.lowercased() + switch ext { + case _ where FileKind.rawExtensions.contains(ext): self = .raw + case "dng": self = .dng + case "jpg", "jpeg", "jpe": self = .jpeg + case "heic", "heif", "hif": self = .heic + case "tif", "tiff": self = .tiff + case "png": self = .png + default: self = .other + } + } + + public var isImage: Bool { self != .other } + public var isRawLike: Bool { self == .raw || self == .dng } + /// Proprietary RAWs get an XMP sidecar (like PM & Lightroom). Everything else is written in place. + public var usesSidecar: Bool { self == .raw } + /// IPTC-IIM can be embedded (JPEG/TIFF/DNG/PSD). PNG/HEIC get XMP only. + public var supportsIIM: Bool { self == .jpeg || self == .tiff || self == .dng } +} + +public enum ColorLabel: String, CaseIterable, Codable, Sendable { + case red = "Red", yellow = "Yellow", green = "Green", blue = "Blue", purple = "Purple" + + /// Value written to Lightroom's xmp:Label (LR default label set, German UI uses the same English keys + /// only if the label set is "Lightroom-Standard"; see README). + public var xmpValue: String { rawValue } + /// Photo Mechanic color class number for compatibility. + public var pmColorClass: Int { (ColorLabel.allCases.firstIndex(of: self) ?? 0) + 1 } + public var germanName: String { + switch self { + case .red: return "Rot" + case .yellow: return "Gelb" + case .green: return "Grün" + case .blue: return "Blau" + case .purple: return "Lila" + } + } + + public init?(xmp: String) { + let l = xmp.lowercased() + let map: [String: ColorLabel] = ["red": .red, "rot": .red, "yellow": .yellow, "gelb": .yellow, + "green": .green, "grün": .green, "blue": .blue, "blau": .blue, + "purple": .purple, "lila": .purple, "violett": .purple] + guard let c = map[l] else { return nil } + self = c + } + + public init?(pmColorClass n: Int) { + guard n >= 1, n <= ColorLabel.allCases.count else { return nil } + self = ColorLabel.allCases[n - 1] + } +} + +/// One entry in the contact sheet. A RAW+JPEG pair is shown as a single item (like PM). +public struct PhotoItem: Identifiable, Hashable, Sendable { + public var id: String { primary.path } + public var primary: URL + /// Other files with the same base name (e.g. the JPEG next to a RAW). + public var companions: [URL] + public var kind: FileKind + public var fileSize: Int64 + public var modified: Date + + public var rating: Int = 0 + public var label: ColorLabel? + public var tagged = false + public var iptc = IPTCValues() + public var exif: [String: String] = [:] + public var captureDate: Date? + public var metadataLoaded = false + + public init(primary: URL, companions: [URL] = [], fileSize: Int64 = 0, modified: Date = Date()) { + self.primary = primary + self.companions = companions + self.kind = FileKind(url: primary) + self.fileSize = fileSize + self.modified = modified + } + + public static func == (a: PhotoItem, b: PhotoItem) -> Bool { + a.id == b.id && a.rating == b.rating && a.label == b.label && a.tagged == b.tagged && a.iptc == b.iptc + && a.metadataLoaded == b.metadataLoaded + } + + public func hash(into h: inout Hasher) { h.combine(id) } + + public var filename: String { primary.lastPathComponent } + public var baseName: String { primary.deletingPathExtension().lastPathComponent } + + public var sidecarURL: URL { primary.deletingPathExtension().appendingPathExtension("xmp") } + + /// All files that should receive metadata (RAW → sidecar, plus embedded JPEG companions). + public var metadataTargets: [(url: URL, kind: FileKind)] { + var t: [(url: URL, kind: FileKind)] = [] + t.append(kind.usesSidecar ? (url: sidecarURL, kind: FileKind.raw) : (url: primary, kind: kind)) + for c in companions { + let k = FileKind(url: c) + if k.isImage, !k.usesSidecar { t.append((url: c, kind: k)) } + } + return t + } + + /// The JPEG that represents this item for upload (companion JPEG or primary JPEG). + public var jpegForUpload: URL? { + if kind == .jpeg { return primary } + return companions.first { FileKind(url: $0) == .jpeg } + } + + public var rawFile: URL? { kind.isRawLike ? primary : companions.first { FileKind(url: $0).isRawLike } } + + /// Applies exiftool output (primary file + optional sidecar) to the item. + public mutating func apply(fileMeta: [String: MetadataValue], sidecarMeta: [String: MetadataValue]?) { + // EXIF from the image itself + var exif: [String: String] = [:] + for (k, v) in fileMeta where !k.hasPrefix("IPTC:") && !k.hasPrefix("XMP-") { exif[k] = v.string } + self.exif = exif + if let d = exif["DateTimeOriginal"] ?? exif["CreateDate"] { captureDate = ExifDate.parse(d) } + + // Sidecar wins for XMP (that is what LR and PM do), embedded values are the fallback. + let xmpSource = sidecarMeta ?? [:] + func xmp(_ tag: String) -> MetadataValue? { xmpSource[tag] ?? fileMeta[tag] } + + rating = xmp("XMP-xmp:Rating")?.int ?? 0 + label = xmp("XMP-xmp:Label").flatMap { ColorLabel(xmp: $0.string) } + ?? xmp("XMP-photomech:ColorClass")?.int.flatMap { ColorLabel(pmColorClass: $0) } + tagged = xmp("XMP-photomech:Tagged")?.bool ?? false + + var values = IPTCValues() + for field in IPTCField.all { + let v = xmp(field.xmpTag) ?? field.iimTag.flatMap { fileMeta[$0] } + guard let v else { continue } + if field.kind == .list { + let l = v.list.filter { !$0.isEmpty } + if !l.isEmpty { values.lists[field.id] = l } + } else { + var s = v.string + if field.id == "dateCreated" { s = String(s.prefix(10)).replacingOccurrences(of: ":", with: "-") } + if !s.isEmpty { values.text[field.id] = s } + } + } + iptc = values + metadataLoaded = true + } +} + +public enum FolderScanner { + /// Lists images in a folder and pairs RAW+JPEG by base name. + public static func scan(folder: URL, recursive: Bool = false) throws -> [PhotoItem] { + let fm = FileManager.default + let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey, .isHiddenKey] + var urls: [URL] = [] + if recursive { + if let e = fm.enumerator(at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles, .skipsPackageDescendants]) { + for case let u as URL in e { urls.append(u) } + } + } else { + urls = try fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles]) + } + urls = urls.filter { !$0.lastPathComponent.hasPrefix("._") && FileKind(url: $0).isImage } + + // Group by directory + lowercase base name + var groups: [String: [URL]] = [:] + for u in urls { + let key = u.deletingLastPathComponent().path + "/" + u.deletingPathExtension().lastPathComponent.lowercased() + groups[key, default: []].append(u) + } + var items: [PhotoItem] = [] + for (_, files) in groups { + // Primary: RAW > DNG > TIFF > HEIC > JPEG > PNG + let order: [FileKind] = [.raw, .dng, .tiff, .heic, .jpeg, .png] + let sorted = files.sorted { (order.firstIndex(of: FileKind(url: $0)) ?? 9) < (order.firstIndex(of: FileKind(url: $1)) ?? 9) } + guard let primary = sorted.first else { continue } + let rv = try? primary.resourceValues(forKeys: Set(keys)) + items.append(PhotoItem(primary: primary, companions: Array(sorted.dropFirst()), + fileSize: Int64(rv?.fileSize ?? 0), modified: rv?.contentModificationDate ?? Date())) + } + return items.sorted { $0.filename.localizedStandardCompare($1.filename) == .orderedAscending } + } +} diff --git a/Sources/LichtkastenCore/Lightroom/LightroomBridge.swift b/Sources/LichtkastenCore/Lightroom/LightroomBridge.swift new file mode 100644 index 0000000..7e4702d --- /dev/null +++ b/Sources/LichtkastenCore/Lightroom/LightroomBridge.swift @@ -0,0 +1,133 @@ +import Foundation + +/// A job for the "Lichtkasten Bridge" Lightroom Classic plugin. +/// The plugin polls the inbox, imports the files into the open catalog, applies the develop preset, +/// optionally adds them to a collection and exports JPEGs – then writes a result file. +public struct LightroomJob: Codable, Identifiable, Sendable { + public var id: String + public var files: [URL] + public var developPreset: String // name of the LR develop preset, empty = none + public var collection: String // collection name, empty = none + public var export: Bool + public var exportFolder: URL? + public var jpegQuality: Int // 0–100 + public var longEdge: Int // px, 0 = full size + public var sharpening: String // "none" | "screen" | "matte" | "glossy" + public var colorSpace: String // "sRGB" | "AdobeRGB" + public var created: Date + /// After export Lichtkasten writes the original IPTC block again (PM-identical structure). + public var rewriteIPTCAfterExport: Bool + /// Upload targets applied after export (FTP destination ids, "immich"). + public var uploadTargets: [String] + + public init(id: String = UUID().uuidString, files: [URL], developPreset: String = "", collection: String = "", + export: Bool = false, exportFolder: URL? = nil, jpegQuality: Int = 90, longEdge: Int = 0, + sharpening: String = "none", colorSpace: String = "sRGB", rewriteIPTCAfterExport: Bool = true, + uploadTargets: [String] = []) { + self.id = id; self.files = files; self.developPreset = developPreset; self.collection = collection + self.export = export; self.exportFolder = exportFolder; self.jpegQuality = jpegQuality; self.longEdge = longEdge + self.sharpening = sharpening; self.colorSpace = colorSpace; self.created = Date() + self.rewriteIPTCAfterExport = rewriteIPTCAfterExport; self.uploadTargets = uploadTargets + } + + /// Simple line format, trivial to parse in Lua (no JSON library in the LR SDK). + public func serialized() -> String { + var lines = ["version=1", "id=\(id)", "preset=\(developPreset)", "collection=\(collection)", + "export=\(export ? 1 : 0)", "exportFolder=\(exportFolder?.path ?? "")", + "quality=\(jpegQuality)", "longEdge=\(longEdge)", "sharpening=\(sharpening)", + "colorSpace=\(colorSpace)"] + lines += files.map { "file=\($0.path)" } + return lines.map { $0.replacingOccurrences(of: "\n", with: " ") }.joined(separator: "\n") + "\n" + } +} + +public struct LightroomJobResult: Sendable { + public var id: String + public var ok: Bool + public var imported: Int + public var exported: [URL] + public var errors: [String] + + public static func parse(_ text: String) -> LightroomJobResult { + var r = LightroomJobResult(id: "", ok: false, imported: 0, exported: [], errors: []) + for line in text.components(separatedBy: .newlines) { + guard let eq = line.firstIndex(of: "=") else { continue } + let k = String(line[.. [LightroomJobResult] { + guard let files = try? FileManager.default.contentsOfDirectory(at: outbox, includingPropertiesForKeys: nil) else { return [] } + var results: [LightroomJobResult] = [] + for f in files where f.pathExtension == "result" { + if let text = try? String(contentsOf: f, encoding: .utf8) { + var r = LightroomJobResult.parse(text) + if r.id.isEmpty { r.id = f.deletingPathExtension().lastPathComponent } + results.append(r) + } + try? FileManager.default.removeItem(at: f) + } + return results + } + + /// The plugin touches the heartbeat file every few seconds while LR is running. + public static var pluginIsAlive: Bool { + guard let attrs = try? FileManager.default.attributesOfItem(atPath: heartbeat.path), + let date = attrs[.modificationDate] as? Date else { return false } + return Date().timeIntervalSince(date) < 15 + } + + /// Installs (copies) the plugin bundle into Lightroom's Modules folder. + public static func installPlugin(from bundle: URL) throws { + let fm = FileManager.default + try fm.createDirectory(at: lightroomModulesFolder, withIntermediateDirectories: true) + let dest = lightroomModulesFolder.appendingPathComponent(bundle.lastPathComponent) + if fm.fileExists(atPath: dest.path) { try fm.removeItem(at: dest) } + try fm.copyItem(at: bundle, to: dest) + } + + public static var pluginInstalled: Bool { + FileManager.default.fileExists(atPath: lightroomModulesFolder.appendingPathComponent("LichtkastenBridge.lrplugin").path) + } +} diff --git a/Sources/LichtkastenCore/Metadata/ExifTool.swift b/Sources/LichtkastenCore/Metadata/ExifTool.swift new file mode 100644 index 0000000..6791024 --- /dev/null +++ b/Sources/LichtkastenCore/Metadata/ExifTool.swift @@ -0,0 +1,204 @@ +import Foundation + +public enum ExifToolError: LocalizedError { + case notInstalled + case failed(String) + + public var errorDescription: String? { + switch self { + case .notInstalled: + return "exiftool wurde nicht gefunden. Installation: `brew install exiftool` oder Pfad in den Einstellungen angeben." + case .failed(let m): return "exiftool-Fehler: \(m)" + } + } +} + +/// Long-running exiftool process (`-stay_open`). exiftool is the reference implementation +/// for IPTC-IIM + XMP and produces exactly what agencies expect (incl. CodedCharacterSet & IPTCDigest). +public final class ExifTool: @unchecked Sendable { + public static let searchPaths = ["/opt/homebrew/bin/exiftool", "/usr/local/bin/exiftool", "/usr/bin/exiftool"] + + public static func locate(custom: String? = nil) -> URL? { + let candidates = [custom].compactMap { $0 }.filter { !$0.isEmpty } + searchPaths + if let bundled = Bundle.main.url(forResource: "exiftool", withExtension: nil, subdirectory: "exiftool") { + return bundled + } + return candidates.map { URL(fileURLWithPath: $0) }.first { FileManager.default.isExecutableFile(atPath: $0.path) } + } + + private let executable: URL + private let queue = DispatchQueue(label: "lichtkasten.exiftool") + private var process: Process? + private var stdinHandle: FileHandle? + private var stdoutHandle: FileHandle? + private var stderrBuffer = Data() + private let stderrLock = NSLock() + private var counter = 0 + private let tempDir: URL + + public init(executable: URL) { + self.executable = executable + tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("lichtkasten-exiftool", isDirectory: true) + try? FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + } + + deinit { shutdown() } + + public func shutdown() { + if let h = stdinHandle { + try? h.write(contentsOf: Data("-stay_open\nFalse\n".utf8)) + } + process?.terminate() + process = nil + } + + private func startIfNeeded() throws { + if let p = process, p.isRunning { return } + let p = Process() + p.executableURL = executable + p.arguments = ["-stay_open", "True", "-@", "-", "-common_args", "-charset", "utf8", "-charset", "iptc=utf8"] + let inPipe = Pipe(), outPipe = Pipe(), errPipe = Pipe() + p.standardInput = inPipe + p.standardOutput = outPipe + p.standardError = errPipe + errPipe.fileHandleForReading.readabilityHandler = { [weak self] h in + let d = h.availableData + guard let self, !d.isEmpty else { return } + self.stderrLock.lock(); self.stderrBuffer.append(d); self.stderrLock.unlock() + } + try p.run() + process = p + stdinHandle = inPipe.fileHandleForWriting + stdoutHandle = outPipe.fileHandleForReading + } + + /// Runs one exiftool command. Arguments must not contain newlines (use `writeValueFile`). + public func execute(_ args: [String]) async throws -> (stdout: String, stderr: String) { + try await withCheckedThrowingContinuation { cont in + queue.async { + do { cont.resume(returning: try self.executeSync(args)) } catch { cont.resume(throwing: error) } + } + } + } + + private func executeSync(_ args: [String]) throws -> (stdout: String, stderr: String) { + try startIfNeeded() + guard let stdin = stdinHandle, let stdout = stdoutHandle else { throw ExifToolError.failed("Prozess nicht gestartet") } + counter += 1 + let marker = "{ready\(counter)}" + stderrLock.lock(); stderrBuffer.removeAll(); stderrLock.unlock() + let payload = (args.map { $0.replacingOccurrences(of: "\n", with: " ") } + ["-execute\(counter)"]).joined(separator: "\n") + "\n" + try stdin.write(contentsOf: Data(payload.utf8)) + var out = Data() + let markerData = Data(marker.utf8) + while true { + let chunk = stdout.availableData + if chunk.isEmpty { throw ExifToolError.failed("exiftool wurde unerwartet beendet") } + out.append(chunk) + if let r = out.range(of: markerData, options: .backwards) { + out.removeSubrange(r.lowerBound.. URL { + let url = tempDir.appendingPathComponent(UUID().uuidString + ".txt") + try Data(value.utf8).write(to: url) + return url + } + + // MARK: Reading + + /// Reads metadata for many files at once. Returns SourceFile path → flat [tag: value] dictionary. + /// Keys for IPTC/XMP keep their group ("IPTC:Keywords"), EXIF keys are plain ("Model"). + public func readMetadata(files: [URL]) async throws -> [String: [String: MetadataValue]] { + guard !files.isEmpty else { return [:] } + var args = ["-json", "-G1", "-fast", "-a", + "-XMP-xmp:Rating#", "-XMP-xmp:Label", "-XMP-photomech:Tagged#", "-XMP-photomech:ColorClass#", + "-Make", "-Model", "-LensModel", "-LensID", "-SerialNumber", "-ISO", "-ExposureTime", "-FNumber", + "-FocalLength", "-DateTimeOriginal", "-CreateDate", "-SubSecTimeOriginal", "-ImageWidth", "-ImageHeight", + "-Orientation#", "-Artist", "-GPSLatitude#", "-GPSLongitude#"] + for f in IPTCField.all { + if let iim = f.iimTag { args.append("-" + iim) } + args.append("-" + f.xmpTag) + } + args += files.map(\.path) + let (out, err) = try await execute(args) + guard let data = out.data(using: .utf8), !out.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + if !err.isEmpty, !err.contains("Warning") { throw ExifToolError.failed(err) } + return [:] + } + guard let arr = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return [:] } + var result: [String: [String: MetadataValue]] = [:] + for obj in arr { + guard let src = obj["SourceFile"] as? String else { continue } + var flat: [String: MetadataValue] = [:] + for (k, v) in obj where k != "SourceFile" { + let isMeta = k.hasPrefix("IPTC:") || k.hasPrefix("XMP-") + let key = isMeta ? k : String(k.split(separator: ":").last ?? Substring(k)) + if flat[key] != nil && !isMeta { continue } // first EXIF group wins + flat[key] = MetadataValue(any: v) + } + result[src] = flat + } + return result + } +} + +/// JSON values coming back from exiftool. +public enum MetadataValue: Sendable, Hashable { + case string(String) + case number(Double) + case bool(Bool) + case list([String]) + + init(any: Any) { + switch any { + case let n as NSNumber: + // JSONSerialization returns booleans as NSNumber with objCType "c". + if String(cString: n.objCType) == "c" { self = .bool(n.boolValue) } else { self = .number(n.doubleValue) } + case let s as String: self = .string(s) + case let a as [Any]: self = .list(a.map { "\($0)" }) + default: self = .string("\(any)") + } + } + + public var string: String { + switch self { + case .string(let s): return s + case .number(let n): return n == n.rounded() && abs(n) < 1e15 ? String(Int(n)) : String(n) + case .bool(let b): return b ? "True" : "False" + case .list(let l): return l.joined(separator: ", ") + } + } + + public var list: [String] { + if case .list(let l) = self { return l } + let s = string + return s.isEmpty ? [] : [s] + } + + public var int: Int? { + switch self { + case .number(let n): return Int(n) + case .string(let s): return Int(s) + case .bool(let b): return b ? 1 : 0 + case .list: return nil + } + } + + public var bool: Bool { + switch self { + case .bool(let b): return b + case .number(let n): return n != 0 + case .string(let s): return ["true", "yes", "1"].contains(s.lowercased()) + case .list: return false + } + } +} diff --git a/Sources/LichtkastenCore/Metadata/IPTCField.swift b/Sources/LichtkastenCore/Metadata/IPTCField.swift new file mode 100644 index 0000000..908ba88 --- /dev/null +++ b/Sources/LichtkastenCore/Metadata/IPTCField.swift @@ -0,0 +1,168 @@ +import Foundation + +/// XMP namespaces as written by Photo Mechanic, Lightroom and Photoshop. +public enum XMPNamespace { + public static let dc = "http://purl.org/dc/elements/1.1/" + public static let photoshop = "http://ns.adobe.com/photoshop/1.0/" + public static let iptcCore = "http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" + public static let iptcExt = "http://iptc.org/std/Iptc4xmpExt/2008-02-29/" + public static let xmpRights = "http://ns.adobe.com/xap/1.0/rights/" + public static let xmp = "http://ns.adobe.com/xap/1.0/" + public static let photomechanic = "http://ns.camerabits.com/photomechanic/1.0/" + public static let rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" + + /// Prefix normally used when we write a template file back out. + public static let preferredPrefix: [String: String] = [ + dc: "dc", photoshop: "photoshop", iptcCore: "Iptc4xmpCore", iptcExt: "Iptc4xmpExt", + xmpRights: "xmpRights", xmp: "xmp", photomechanic: "photomechanic", + ] +} + +public enum IPTCFieldKind: String, Codable, Sendable { + case text // single line + case multiline // caption / instructions + case list // keywords etc. – stored as [String] +} + +public enum IPTCSection: String, CaseIterable, Codable, Sendable { + case description = "Beschreibung" + case location = "Ort" + case creator = "Urheber & Rechte" + case contact = "Kontakt des Urhebers" + case extended = "Erweitert (IPTC Core/Ext)" +} + +/// How an XMP property is stored inside rdf. +public enum XMPContainer: String, Codable, Sendable { + case simple, alt, seq, bag +} + +/// One IPTC field. The order of `IPTCField.all` mirrors the Photo Mechanic +/// IPTC Stationery Pad so agency workflows stay the same. +public struct IPTCField: Identifiable, Hashable, Sendable { + public let id: String + public let label: String + /// Name as shown in Photo Mechanic (helps when switching). + public let pmLabel: String + public let section: IPTCSection + public let kind: IPTCFieldKind + /// exiftool tag for the legacy IPTC-IIM record (nil = XMP only). + public let iimTag: String? + /// exiftool tag for XMP. + public let xmpTag: String + /// XMP property (namespace URI + local name) used in PM templates. + public let xmpNamespace: String + public let xmpLocalName: String + public let xmpContainer: XMPContainer + /// Byte limit of the IIM dataset (UTF-8 bytes). Agencies truncate/reject above this. + public let iimMaxBytes: Int? + + public static func == (a: IPTCField, b: IPTCField) -> Bool { a.id == b.id } + public func hash(into h: inout Hasher) { h.combine(id) } +} + +public extension IPTCField { + private static func f(_ id: String, _ label: String, pm: String, _ section: IPTCSection, _ kind: IPTCFieldKind = .text, + iim: String?, xmp: String, ns: String, local: String, container: XMPContainer = .simple, + max: Int? = nil) -> IPTCField { + IPTCField(id: id, label: label, pmLabel: pm, section: section, kind: kind, iimTag: iim, xmpTag: xmp, + xmpNamespace: ns, xmpLocalName: local, xmpContainer: container, iimMaxBytes: max) + } + + static let all: [IPTCField] = [ + // --- Beschreibung --- + f("caption", "Bildunterschrift", pm: "Caption", .description, .multiline, + iim: "IPTC:Caption-Abstract", xmp: "XMP-dc:Description", ns: XMPNamespace.dc, local: "description", container: .alt, max: 2000), + f("captionWriter", "Verfasser Bildunterschrift", pm: "Caption Writer", .description, + iim: "IPTC:Writer-Editor", xmp: "XMP-photoshop:CaptionWriter", ns: XMPNamespace.photoshop, local: "CaptionWriter", max: 32), + f("headline", "Überschrift", pm: "Headline", .description, + iim: "IPTC:Headline", xmp: "XMP-photoshop:Headline", ns: XMPNamespace.photoshop, local: "Headline", max: 256), + f("instructions", "Anweisungen", pm: "Special Instructions", .description, .multiline, + iim: "IPTC:SpecialInstructions", xmp: "XMP-photoshop:Instructions", ns: XMPNamespace.photoshop, local: "Instructions", max: 256), + f("transmissionReference", "Job-ID / Übertragungsreferenz", pm: "Transmission Reference", .description, + iim: "IPTC:OriginalTransmissionReference", xmp: "XMP-photoshop:TransmissionReference", ns: XMPNamespace.photoshop, local: "TransmissionReference", max: 32), + f("objectName", "Titel (Objektname)", pm: "Object Name", .description, + iim: "IPTC:ObjectName", xmp: "XMP-dc:Title", ns: XMPNamespace.dc, local: "title", container: .alt, max: 64), + f("keywords", "Stichwörter", pm: "Keywords", .description, .list, + iim: "IPTC:Keywords", xmp: "XMP-dc:Subject", ns: XMPNamespace.dc, local: "subject", container: .bag, max: 64), + f("category", "Kategorie", pm: "Category", .description, + iim: "IPTC:Category", xmp: "XMP-photoshop:Category", ns: XMPNamespace.photoshop, local: "Category", max: 3), + f("supplementalCategories", "Zusatzkategorien", pm: "Supplemental Categories", .description, .list, + iim: "IPTC:SupplementalCategories", xmp: "XMP-photoshop:SupplementalCategories", ns: XMPNamespace.photoshop, local: "SupplementalCategories", container: .bag, max: 32), + f("urgency", "Dringlichkeit", pm: "Urgency", .description, + iim: "IPTC:Urgency", xmp: "XMP-photoshop:Urgency", ns: XMPNamespace.photoshop, local: "Urgency", max: 1), + f("dateCreated", "Erstellungsdatum (JJJJ-MM-TT)", pm: "Date Created", .description, + iim: "IPTC:DateCreated", xmp: "XMP-photoshop:DateCreated", ns: XMPNamespace.photoshop, local: "DateCreated", max: 8), + + // --- Ort --- + f("event", "Ereignis", pm: "Event", .location, + iim: nil, xmp: "XMP-iptcExt:Event", ns: XMPNamespace.iptcExt, local: "Event", container: .alt), + f("sublocation", "Ortsdetail", pm: "Location / Sublocation", .location, + iim: "IPTC:Sub-location", xmp: "XMP-iptcCore:Location", ns: XMPNamespace.iptcCore, local: "Location", max: 32), + f("city", "Stadt", pm: "City", .location, + iim: "IPTC:City", xmp: "XMP-photoshop:City", ns: XMPNamespace.photoshop, local: "City", max: 32), + f("state", "Bundesland", pm: "State / Province", .location, + iim: "IPTC:Province-State", xmp: "XMP-photoshop:State", ns: XMPNamespace.photoshop, local: "State", max: 32), + f("country", "Land", pm: "Country", .location, + iim: "IPTC:Country-PrimaryLocationName", xmp: "XMP-photoshop:Country", ns: XMPNamespace.photoshop, local: "Country", max: 64), + f("countryCode", "Ländercode (ISO)", pm: "Country Code", .location, + iim: "IPTC:Country-PrimaryLocationCode", xmp: "XMP-iptcCore:CountryCode", ns: XMPNamespace.iptcCore, local: "CountryCode", max: 3), + + // --- Urheber & Rechte --- + f("creator", "Fotograf", pm: "Photographer / Creator", .creator, + iim: "IPTC:By-line", xmp: "XMP-dc:Creator", ns: XMPNamespace.dc, local: "creator", container: .seq, max: 32), + f("creatorJobTitle", "Position des Fotografen", pm: "Photographer's Title", .creator, + iim: "IPTC:By-lineTitle", xmp: "XMP-photoshop:AuthorsPosition", ns: XMPNamespace.photoshop, local: "AuthorsPosition", max: 32), + f("credit", "Credit / Anbieter", pm: "Credit", .creator, + iim: "IPTC:Credit", xmp: "XMP-photoshop:Credit", ns: XMPNamespace.photoshop, local: "Credit", max: 32), + f("source", "Quelle", pm: "Source", .creator, + iim: "IPTC:Source", xmp: "XMP-photoshop:Source", ns: XMPNamespace.photoshop, local: "Source", max: 32), + f("copyright", "Copyright-Vermerk", pm: "Copyright Notice", .creator, + iim: "IPTC:CopyrightNotice", xmp: "XMP-dc:Rights", ns: XMPNamespace.dc, local: "rights", container: .alt, max: 128), + f("usageTerms", "Nutzungsbedingungen", pm: "Rights Usage Terms", .creator, .multiline, + iim: nil, xmp: "XMP-xmpRights:UsageTerms", ns: XMPNamespace.xmpRights, local: "UsageTerms", container: .alt), + f("webStatement", "Copyright-URL", pm: "Copyright Info URL", .creator, + iim: nil, xmp: "XMP-xmpRights:WebStatement", ns: XMPNamespace.xmpRights, local: "WebStatement"), + + // --- Kontakt (IPTC Core CreatorContactInfo) --- + f("ciAddress", "Adresse", pm: "Address", .contact, + iim: nil, xmp: "XMP-iptcCore:CreatorAddress", ns: XMPNamespace.iptcCore, local: "CiAdrExtadr"), + f("ciCity", "Stadt", pm: "City (Contact)", .contact, + iim: nil, xmp: "XMP-iptcCore:CreatorCity", ns: XMPNamespace.iptcCore, local: "CiAdrCity"), + f("ciRegion", "Bundesland", pm: "State (Contact)", .contact, + iim: nil, xmp: "XMP-iptcCore:CreatorRegion", ns: XMPNamespace.iptcCore, local: "CiAdrRegion"), + f("ciPostalCode", "PLZ", pm: "Postal Code", .contact, + iim: nil, xmp: "XMP-iptcCore:CreatorPostalCode", ns: XMPNamespace.iptcCore, local: "CiAdrPcode"), + f("ciCountry", "Land", pm: "Country (Contact)", .contact, + iim: nil, xmp: "XMP-iptcCore:CreatorCountry", ns: XMPNamespace.iptcCore, local: "CiAdrCtry"), + f("ciPhone", "Telefon", pm: "Phone", .contact, + iim: nil, xmp: "XMP-iptcCore:CreatorWorkTelephone", ns: XMPNamespace.iptcCore, local: "CiTelWork"), + f("ciEmail", "E-Mail", pm: "E-Mail", .contact, + iim: nil, xmp: "XMP-iptcCore:CreatorWorkEmail", ns: XMPNamespace.iptcCore, local: "CiEmailWork"), + f("ciURL", "Website", pm: "Web URL", .contact, + iim: nil, xmp: "XMP-iptcCore:CreatorWorkURL", ns: XMPNamespace.iptcCore, local: "CiUrlWork"), + + // --- Erweitert --- + f("intellectualGenre", "Genre", pm: "Intellectual Genre", .extended, + iim: "IPTC:ObjectAttributeReference", xmp: "XMP-iptcCore:IntellectualGenre", ns: XMPNamespace.iptcCore, local: "IntellectualGenre", max: 68), + f("scene", "Szenen-Code", pm: "IPTC Scene", .extended, .list, + iim: nil, xmp: "XMP-iptcCore:Scene", ns: XMPNamespace.iptcCore, local: "Scene", container: .bag), + f("subjectCode", "Themen-Code", pm: "IPTC Subject Code", .extended, .list, + iim: "IPTC:SubjectReference", xmp: "XMP-iptcCore:SubjectCode", ns: XMPNamespace.iptcCore, local: "SubjectCode", container: .bag, max: 236), + f("personInImage", "Abgebildete Personen", pm: "Person Shown", .extended, .list, + iim: nil, xmp: "XMP-iptcExt:PersonInImage", ns: XMPNamespace.iptcExt, local: "PersonInImage", container: .bag), + ] + + static let byID: [String: IPTCField] = Dictionary(uniqueKeysWithValues: all.map { ($0.id, $0) }) + + /// Lookup by XMP namespace + local name (used by the PM template importer). + static func forXMP(namespace: String, localName: String) -> IPTCField? { + all.first { $0.xmpNamespace == namespace && $0.xmpLocalName == localName } + } + + /// Byte length check against the IIM limit. Returns overflow in bytes (0 = ok). + func overflow(of value: String) -> Int { + guard let max = iimMaxBytes else { return 0 } + return Swift.max(0, value.utf8.count - max) + } +} diff --git a/Sources/LichtkastenCore/Metadata/IPTCTemplate.swift b/Sources/LichtkastenCore/Metadata/IPTCTemplate.swift new file mode 100644 index 0000000..06c4fa0 --- /dev/null +++ b/Sources/LichtkastenCore/Metadata/IPTCTemplate.swift @@ -0,0 +1,104 @@ +import Foundation + +/// IPTC values keyed by `IPTCField.id`. Text fields and list fields are stored separately +/// so list semantics (keywords, persons …) survive round trips exactly. +public struct IPTCValues: Codable, Hashable, Sendable { + public var text: [String: String] = [:] + public var lists: [String: [String]] = [:] + + public init(text: [String: String] = [:], lists: [String: [String]] = [:]) { + self.text = text + self.lists = lists + } + + public subscript(field: IPTCField) -> String { + get { + if field.kind == .list { return (lists[field.id] ?? []).joined(separator: ", ") } + return text[field.id] ?? "" + } + set { + if field.kind == .list { + let items = IPTCValues.splitList(newValue) + lists[field.id] = items.isEmpty ? nil : items + } else { + text[field.id] = newValue.isEmpty ? nil : newValue + } + } + } + + public func list(_ field: IPTCField) -> [String] { lists[field.id] ?? [] } + + public func isEmpty(_ field: IPTCField) -> Bool { + field.kind == .list ? (lists[field.id]?.isEmpty ?? true) : (text[field.id]?.isEmpty ?? true) + } + + public var isCompletelyEmpty: Bool { text.isEmpty && lists.isEmpty } + + /// Keywords are separated by comma or semicolon (PM accepts both). + public static func splitList(_ s: String) -> [String] { + s.split(whereSeparator: { $0 == "," || $0 == ";" || $0 == "\n" }) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + } +} + +public enum ListMergeMode: String, Codable, CaseIterable, Sendable { + case append = "Anhängen" + case replace = "Ersetzen" +} + +/// A metadata template (PM: "IPTC Stationery Pad" / "IPTC Template"). +public struct IPTCTemplate: Codable, Identifiable, Hashable, Sendable { + public var id: UUID + public var name: String + public var values: IPTCValues + public var listMergeMode: ListMergeMode + /// If true, empty template fields clear the target field (PM: "Replace all"). + public var clearEmptyFields: Bool + /// XMP properties from an imported PM template we do not model; written back on export. + public var extras: [String: String] + public var modified: Date + + public init(id: UUID = UUID(), name: String, values: IPTCValues = IPTCValues(), + listMergeMode: ListMergeMode = .append, clearEmptyFields: Bool = false, + extras: [String: String] = [:], modified: Date = Date()) { + self.id = id + self.name = name + self.values = values + self.listMergeMode = listMergeMode + self.clearEmptyFields = clearEmptyFields + self.extras = extras + self.modified = modified + } + + /// Merges the template into existing image values. Variables / codes are NOT expanded here, + /// that happens per image in `MetadataWriter`. + public func apply(to existing: IPTCValues) -> IPTCValues { + var result = existing + for field in IPTCField.all { + if field.kind == .list { + let tpl = values.list(field) + if tpl.isEmpty { + if clearEmptyFields { result.lists[field.id] = nil } + continue + } + switch listMergeMode { + case .replace: + result.lists[field.id] = tpl + case .append: + var merged = existing.list(field) + for k in tpl where !merged.contains(k) { merged.append(k) } + result.lists[field.id] = merged + } + } else { + let tpl = values.text[field.id] ?? "" + if tpl.isEmpty { + if clearEmptyFields { result.text[field.id] = nil } + continue + } + result.text[field.id] = tpl + } + } + return result + } +} diff --git a/Sources/LichtkastenCore/Metadata/MetadataWriter.swift b/Sources/LichtkastenCore/Metadata/MetadataWriter.swift new file mode 100644 index 0000000..a2d849f --- /dev/null +++ b/Sources/LichtkastenCore/Metadata/MetadataWriter.swift @@ -0,0 +1,107 @@ +import Foundation + +/// Builds exiftool commands that write IPTC exactly like Photo Mechanic does: +/// IIM (UTF-8, CodedCharacterSet set) + XMP in sync for JPEG/TIFF/DNG, XMP sidecar for RAW. +public struct MetadataWriter: Sendable { + public let exiftool: ExifTool + + public init(exiftool: ExifTool) { self.exiftool = exiftool } + + /// Writes the given fields (only those – other fields stay untouched) to all targets of the item. + @discardableResult + public func write(values: IPTCValues, fields: [IPTCField], to item: PhotoItem) async throws -> [String] { + var warnings: [String] = [] + for target in item.metadataTargets { + let args = try arguments(values: values, fields: fields, targetKind: target.kind) + [target.url.path] + let (_, err) = try await exiftool.execute(["-overwrite_original", "-m"] + args) + if !err.isEmpty { warnings.append(contentsOf: Self.relevantMessages(err, file: target.url)) } + if err.contains("Error:") { throw ExifToolError.failed(err) } + } + return warnings + } + + public func writeRating(_ rating: Int, to item: PhotoItem) async throws { + try await writeFlags(["-XMP-xmp:Rating=\(max(0, min(5, rating)))"], item: item) + } + + public func writeLabel(_ label: ColorLabel?, to item: PhotoItem) async throws { + if let label { + try await writeFlags(["-XMP-xmp:Label=\(label.xmpValue)", "-XMP-photomech:ColorClass=\(label.pmColorClass)"], item: item) + } else { + try await writeFlags(["-XMP-xmp:Label=", "-XMP-photomech:ColorClass="], item: item) + } + } + + public func writeTag(_ tagged: Bool, to item: PhotoItem) async throws { + try await writeFlags(["-XMP-photomech:Tagged=\(tagged ? "Yes" : "No")"], item: item) + } + + private func writeFlags(_ args: [String], item: PhotoItem) async throws { + for target in item.metadataTargets { + let (_, err) = try await exiftool.execute(["-overwrite_original", "-m"] + args + [target.url.path]) + if err.contains("Error:") { throw ExifToolError.failed(err) } + } + } + + /// Argument list for one target file (without the file path). + public func arguments(values: IPTCValues, fields: [IPTCField], targetKind: FileKind) throws -> [String] { + let writeIIM = targetKind.supportsIIM + var args: [String] = [] + if writeIIM { args.append("-IPTC:CodedCharacterSet=UTF8") } + for field in fields { + var tags = [field.xmpTag] + if writeIIM, let iim = field.iimTag { tags.append(iim) } + if field.kind == .list { + let list = values.list(field) + for tag in tags { + if list.isEmpty { args.append("-\(tag)=") } + for item in list { args.append("-\(tag)=\(item)") } + } + } else { + var value = values.text[field.id] ?? "" + if field.id == "dateCreated" { + value = value.replacingOccurrences(of: "-", with: ":") + if !value.isEmpty, value.count != 10 { continue } // ignore incomplete dates + } + for tag in tags { + if value.isEmpty { + args.append("-\(tag)=") + } else if value.contains("\n") || value.contains("\r") { + let file = try exiftool.writeValueFile(value) + args.append("-\(tag)<=\(file.path)") + } else { + args.append("-\(tag)=\(value)") + } + } + } + } + if writeIIM && targetKind != .dng { args.append("-IPTCDigest=new") } + return args + } + + static func relevantMessages(_ stderr: String, file: URL) -> [String] { + stderr.components(separatedBy: .newlines) + .filter { !$0.isEmpty && !$0.contains("image files updated") } + .map { "\(file.lastPathComponent): \($0)" } + } +} + +public extension MetadataWriter { + /// Applies a template to the items, expanding variables & codes per image. + /// Returns the new values per item id (so the UI can update without re-reading). + func apply(template: IPTCTemplate, to items: [PhotoItem], codes: CodeReplacements?, + dateFormat: String, progress: (@Sendable (Int) -> Void)? = nil) async throws -> [String: IPTCValues] { + var result: [String: IPTCValues] = [:] + // Fields touched by the template (non-empty, or all if clearEmptyFields). + let fields = IPTCField.all.filter { template.clearEmptyFields || !template.values.isEmpty($0) } + for (i, item) in items.enumerated() { + let merged = template.apply(to: item.iptc) + let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, iptc: merged, dateFormat: dateFormat) + let expanded = VariableExpander.expand(merged, context: ctx, codes: codes) + try await write(values: expanded, fields: fields, to: item) + result[item.id] = expanded + progress?(i + 1) + } + return result + } +} diff --git a/Sources/LichtkastenCore/Metadata/Variables.swift b/Sources/LichtkastenCore/Metadata/Variables.swift new file mode 100644 index 0000000..6025f61 --- /dev/null +++ b/Sources/LichtkastenCore/Metadata/Variables.swift @@ -0,0 +1,196 @@ +import Foundation + +/// Per-image values used for `{variable}` expansion (PM compatible names where possible). +public struct VariableContext: Sendable { + public var values: [String: String] + + public init(values: [String: String] = [:]) { self.values = values } + + /// Builds the context from file info + EXIF as read by exiftool. + public static func make(fileURL: URL, exif: [String: String], sequence: Int? = nil, + iptc: IPTCValues = IPTCValues(), dateFormat: String = "dd.MM.yyyy") -> VariableContext { + var v: [String: String] = [:] + v["filename"] = fileURL.lastPathComponent + v["filenamebase"] = fileURL.deletingPathExtension().lastPathComponent + v["fileext"] = fileURL.pathExtension + v["folder"] = fileURL.deletingLastPathComponent().lastPathComponent + v["make"] = exif["Make"] + v["model"] = exif["Model"] + v["lens"] = exif["LensModel"] ?? exif["Lens"] ?? exif["LensID"] + v["serial"] = exif["SerialNumber"] + v["serialnum"] = exif["SerialNumber"] + v["iso"] = exif["ISO"] + v["aperture"] = exif["FNumber"].map { "f/\($0)" } + v["shutter"] = exif["ExposureTime"] + v["focallength"] = exif["FocalLength"] + v["artist"] = exif["Artist"] + if let seq = sequence { + v["seqn"] = String(seq) + v["seqn3"] = String(format: "%03d", seq) + v["seqn4"] = String(format: "%04d", seq) + } + if let raw = exif["DateTimeOriginal"] ?? exif["CreateDate"], let date = ExifDate.parse(raw) { + let cal = Calendar(identifier: .gregorian) + let c = cal.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) + let df = DateFormatter() + df.locale = Locale(identifier: "de_DE") + df.dateFormat = dateFormat + v["date"] = df.string(from: date) + df.dateFormat = "HH:mm:ss" + v["time"] = df.string(from: date) + df.dateFormat = "MMMM" + v["monthname"] = df.string(from: date) + df.dateFormat = "EEEE" + v["weekday"] = df.string(from: date) + v["isodate"] = String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0) + v["year4"] = String(format: "%04d", c.year ?? 0) + v["year2"] = String(format: "%02d", (c.year ?? 0) % 100) + v["month0"] = String(format: "%02d", c.month ?? 0) + v["month"] = String(c.month ?? 0) + v["day0"] = String(format: "%02d", c.day ?? 0) + v["day"] = String(c.day ?? 0) + v["hour"] = String(format: "%02d", c.hour ?? 0) + v["minute"] = String(format: "%02d", c.minute ?? 0) + v["second"] = String(format: "%02d", c.second ?? 0) + } + // IPTC fields can be referenced too, e.g. "{city}" inside the caption. + for field in IPTCField.all { + let value = iptc[field] + if !value.isEmpty { v[field.id.lowercased()] = value } + } + return VariableContext(values: v.compactMapValues { $0 }) + } +} + +public enum ExifDate { + /// Parses exiftool dates like "2026:11:03 14:22:01" (optionally with sub-seconds / timezone). + public static func parse(_ s: String) -> Date? { + let core = String(s.prefix(19)) + let f = DateFormatter() + f.locale = Locale(identifier: "en_US_POSIX") + f.timeZone = TimeZone.current + f.dateFormat = "yyyy:MM:dd HH:mm:ss" + if let d = f.date(from: core) { return d } + f.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" + return f.date(from: core) + } +} + +/// PM-style code replacement: `\bvb\` → "Borussia Dortmund", `\bvb#2\` → second column. +/// Codes file format (as exported from PM): tab separated, first column = code. +public struct CodeReplacements: Codable, Sendable { + public var delimiter: Character = "\\" + public var table: [String: [String]] = [:] + public var caseSensitive = false + + enum CodingKeys: String, CodingKey { case delimiter, table, caseSensitive } + + public init(table: [String: [String]] = [:]) { self.table = table } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = try c.decodeIfPresent(String.self, forKey: .delimiter) ?? "\\" + delimiter = d.first ?? "\\" + table = try c.decodeIfPresent([String: [String]].self, forKey: .table) ?? [:] + caseSensitive = try c.decodeIfPresent(Bool.self, forKey: .caseSensitive) ?? false + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(String(delimiter), forKey: .delimiter) + try c.encode(table, forKey: .table) + try c.encode(caseSensitive, forKey: .caseSensitive) + } + + /// Loads a tab-delimited PM code replacement file. Lines starting with '#' are ignored. + public static func load(tabDelimited text: String) -> CodeReplacements { + var table: [String: [String]] = [:] + 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 } + table[code.lowercased()] = Array(cols.dropFirst()).map { $0.trimmingCharacters(in: .whitespaces) } + } + return CodeReplacements(table: table) + } + + func lookup(_ code: String) -> String? { + var name = code + var column = 1 + if let hash = code.lastIndex(of: "#"), let n = Int(code[code.index(after: hash)...]) { + name = String(code[..= 1, column <= row.count else { return nil } + return row[column - 1] + } + + public func expand(_ text: String) -> String { + guard !table.isEmpty, text.contains(delimiter) else { return text } + var out = "" + var i = text.startIndex + while i < text.endIndex { + let ch = text[i] + if ch == delimiter, let close = text[text.index(after: i)...].firstIndex(of: delimiter) { + let code = String(text[text.index(after: i).. String { + var s = codes?.expand(text) ?? text + guard s.contains("{") else { return s } + var out = "" + var rest = s[...] + while let open = rest.firstIndex(of: "{") { + out += rest[.. IPTCValues { + var r = values + for (k, v) in values.text { r.text[k] = expand(v, context: context, codes: codes) } + for (k, list) in values.lists { r.lists[k] = list.map { expand($0, context: context, codes: codes) } } + return r + } + + /// Variables offered in the editor's insert menu. + public static let documented: [(String, String)] = [ + ("{filename}", "Dateiname"), ("{filenamebase}", "Dateiname ohne Endung"), + ("{date}", "Aufnahmedatum (Format in Einstellungen)"), ("{isodate}", "Datum JJJJ-MM-TT"), + ("{time}", "Uhrzeit"), ("{weekday}", "Wochentag"), ("{year4}", "Jahr"), ("{month0}", "Monat 01–12"), + ("{monthname}", "Monatsname"), ("{day0}", "Tag 01–31"), + ("{city}", "Stadt (IPTC)"), ("{country}", "Land (IPTC)"), ("{event}", "Ereignis (IPTC)"), + ("{creator}", "Fotograf (IPTC)"), ("{credit}", "Credit (IPTC)"), + ("{model}", "Kameramodell"), ("{serial}", "Seriennummer"), ("{lens}", "Objektiv"), + ("{iso}", "ISO"), ("{aperture}", "Blende"), ("{shutter}", "Belichtungszeit"), + ("{focallength}", "Brennweite"), ("{seqn}", "Laufnummer (Ingest)"), ("{seqn4}", "Laufnummer 4-stellig"), + ] +} diff --git a/Sources/LichtkastenCore/Metadata/XMPTemplateIO.swift b/Sources/LichtkastenCore/Metadata/XMPTemplateIO.swift new file mode 100644 index 0000000..5481091 --- /dev/null +++ b/Sources/LichtkastenCore/Metadata/XMPTemplateIO.swift @@ -0,0 +1,202 @@ +import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif + +public enum TemplateImportError: LocalizedError { + case unreadable(String) + case noFieldsFound + + public var errorDescription: String? { + switch self { + case .unreadable(let m): return "Vorlage konnte nicht gelesen werden: \(m)" + case .noFieldsFound: return "In der Datei wurden keine IPTC-Felder gefunden." + } + } +} + +/// Reads and writes metadata templates as XMP – the format Photo Mechanic uses for +/// saved IPTC Stationery Pad / IPTC templates (also readable by Lightroom & Bridge). +public enum XMPTemplateIO { + + // MARK: Import + + public static func importTemplate(from url: URL) throws -> IPTCTemplate { + let data = try Data(contentsOf: url) + var t = try parse(data: data) + t.name = url.deletingPathExtension().lastPathComponent + return t + } + + public static func parse(data: Data) throws -> IPTCTemplate { + let props = try XMPPropertyCollector.collect(data: data) + var values = IPTCValues() + var extras: [String: String] = [:] + var found = 0 + for p in props { + if let field = IPTCField.forXMP(namespace: p.namespace, localName: p.localName) { + found += 1 + if field.kind == .list { + var list = values.lists[field.id] ?? [] + list.append(contentsOf: p.values.filter { !$0.isEmpty }) + values.lists[field.id] = list.isEmpty ? nil : list + } else { + let v = p.values.joined(separator: field.xmpContainer == .seq ? "; " : "\n") + if !v.isEmpty { values.text[field.id] = v } + } + } else if p.namespace != XMPNamespace.rdf, !p.values.isEmpty, + !(p.namespace == XMPNamespace.iptcCore && p.localName == "CreatorContactInfo") { + extras["\(p.namespace)|\(p.localName)"] = p.values.joined(separator: "\u{1F}") + } + } + // PM stores IIM date as yyyy-mm-dd in photoshop:DateCreated – keep only the date part. + if let d = values.text["dateCreated"], d.count > 10 { values.text["dateCreated"] = String(d.prefix(10)) } + guard found > 0 || !extras.isEmpty else { throw TemplateImportError.noFieldsFound } + return IPTCTemplate(name: "Importiert", values: values, extras: extras) + } + + // MARK: Export + + public static func export(_ t: IPTCTemplate) -> String { + var simpleAttrs: [String] = [] + var elements: [String] = [] + var contact: [String] = [] + + func esc(_ s: String) -> String { + s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<") + .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """) + } + func qname(_ ns: String, _ local: String) -> String { + "\(XMPNamespace.preferredPrefix[ns] ?? "ns"):\(local)" + } + + for field in IPTCField.all where !t.values.isEmpty(field) { + let q = qname(field.xmpNamespace, field.xmpLocalName) + let vals = field.kind == .list ? t.values.list(field) : [t.values[field]] + if field.section == .contact { + contact.append(" <\(q)>\(esc(vals[0]))") + continue + } + switch field.xmpContainer { + case .simple: + simpleAttrs.append(" \(q)=\"\(esc(vals[0]))\"") + case .alt: + elements.append(" <\(q)>\n \n \(esc(vals[0]))\n \n ") + case .seq, .bag: + let tag = field.xmpContainer == .seq ? "rdf:Seq" : "rdf:Bag" + let lis = vals.map { " \(esc($0))" }.joined(separator: "\n") + elements.append(" <\(q)>\n <\(tag)>\n\(lis)\n \n ") + } + } + if !contact.isEmpty { + elements.append(" \n\(contact.joined(separator: "\n"))\n ") + } + // Unknown properties from imported PM templates (simple values only). + var extraNS: [String: String] = [:] + for (key, value) in t.extras.sorted(by: { $0.key < $1.key }) { + let parts = key.components(separatedBy: "|") + guard parts.count == 2 else { continue } + let prefix: String + if let known = XMPNamespace.preferredPrefix[parts[0]] { + prefix = known + } else if let seen = extraNS[parts[0]] { + prefix = seen + } else { + prefix = "ns\(extraNS.count + 1)" + extraNS[parts[0]] = prefix + } + let items = value.components(separatedBy: "\u{1F}") + if items.count == 1 { + simpleAttrs.append(" \(prefix):\(parts[1])=\"\(esc(items[0]))\"") + } else { + let lis = items.map { " \(esc($0))" }.joined(separator: "\n") + elements.append(" <\(prefix):\(parts[1])>\n \n\(lis)\n \n ") + } + } + var nsDecl = XMPNamespace.preferredPrefix.sorted(by: { $0.value < $1.value }) + .map { " xmlns:\($0.value)=\"\($0.key)\"" } + nsDecl += extraNS.map { " xmlns:\($0.value)=\"\($0.key)\"" } + + return """ + + + + + \(elements.joined(separator: "\n")) + + + + + """ + } +} + +/// Flattens all XMP properties (attributes + elements, including structs like +/// CreatorContactInfo) into (namespace, localName, values) triples. +final class XMPPropertyCollector: NSObject, XMLParserDelegate { + struct Property { var namespace: String; var localName: String; var values: [String] } + + private var prefixes: [String: String] = ["xml": "http://www.w3.org/XML/1998/namespace"] + private var props: [Property] = [] + private struct Frame { var ns: String; var local: String; var text = ""; var liValues: [String] = []; var hasChildElements = false } + private var stack: [Frame] = [] + private var error: Error? + + static func collect(data: Data) throws -> [Property] { + let c = XMPPropertyCollector() + let p = XMLParser(data: data) + p.shouldProcessNamespaces = true + p.shouldReportNamespacePrefixes = true + p.delegate = c + if !p.parse() { + throw TemplateImportError.unreadable(p.parserError?.localizedDescription ?? "ungültiges XML") + } + return c.props + } + + func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) { + prefixes[prefix] = namespaceURI + } + + private func isContainer(_ ns: String, _ local: String) -> Bool { + ns == XMPNamespace.rdf || ns == "adobe:ns:meta/" + } + + func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, + qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) { + let ns = namespaceURI ?? "" + if !stack.isEmpty { stack[stack.count - 1].hasChildElements = true } + // Attributes on rdf:Description or on struct property elements are simple properties. + for (qn, value) in attributeDict { + let parts = qn.split(separator: ":", maxSplits: 1).map(String.init) + guard parts.count == 2, let uri = prefixes[parts[0]] else { continue } + if uri == XMPNamespace.rdf || parts[0] == "xml" || parts[0] == "xmlns" || uri == "adobe:ns:meta/" { continue } + props.append(Property(namespace: uri, localName: parts[1], values: [value])) + } + stack.append(Frame(ns: ns, local: elementName)) + } + + func parser(_ parser: XMLParser, foundCharacters string: String) { + guard !stack.isEmpty else { return } + stack[stack.count - 1].text += string + } + + func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { + guard let frame = stack.popLast() else { return } + let text = frame.text.trimmingCharacters(in: .whitespacesAndNewlines) + if frame.ns == XMPNamespace.rdf && frame.local == "li" { + // Hand the li value up to the nearest real property. + if let idx = stack.lastIndex(where: { !isContainer($0.ns, $0.local) }) { + stack[idx].liValues.append(text) + } + return + } + if isContainer(frame.ns, frame.local) { return } + if !frame.liValues.isEmpty { + props.append(Property(namespace: frame.ns, localName: frame.local, values: frame.liValues)) + } else if !frame.hasChildElements { + props.append(Property(namespace: frame.ns, localName: frame.local, values: [text])) + } + } +} diff --git a/Sources/LichtkastenCore/Upload/FTPUploader.swift b/Sources/LichtkastenCore/Upload/FTPUploader.swift new file mode 100644 index 0000000..33bfaac --- /dev/null +++ b/Sources/LichtkastenCore/Upload/FTPUploader.swift @@ -0,0 +1,191 @@ +import Foundation + +public enum FTPProtocol: String, Codable, CaseIterable, Sendable { + case ftp = "FTP" + case ftpsExplicit = "FTPS (explizit, TLS)" + case ftpsImplicit = "FTPS (implizit)" + case sftp = "SFTP" + + public var defaultPort: Int { + switch self { + case .ftp, .ftpsExplicit: return 21 + case .ftpsImplicit: return 990 + case .sftp: return 22 + } + } +} + +public enum UploadVariant: String, Codable, CaseIterable, Sendable { + case jpeg = "Nur JPEG" + case original = "Original (RAW/JPEG)" + case both = "JPEG + RAW" +} + +/// An FTP server profile (PM: "Upload Photos → FTP"). The password lives in the macOS keychain. +public struct FTPDestination: Codable, Identifiable, Hashable, Sendable { + public var id: UUID + public var name: String + public var proto: FTPProtocol + public var host: String + public var port: Int + public var username: String + public var remoteDirectory: String + public var passive: Bool + /// Upload as ".part" and rename when complete – agency ingest never sees half files. + public var uploadWithTempName: Bool + /// Optional rename pattern with variables, e.g. "{isodate}_{filenamebase}". Empty = keep name. + public var renamePattern: String + public var variant: UploadVariant + /// Path to an SSH private key for SFTP (optional; otherwise ssh-agent / password via curl). + public var sshKeyPath: String + public var allowInsecureTLS: 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) { + 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 + } + + public var keychainAccount: String { "ftp-\(id.uuidString)" } +} + +public enum UploadError: LocalizedError { + case failed(String) + case curlMissingSFTP + + public var errorDescription: String? { + switch self { + case .failed(let m): return m + case .curlMissingSFTP: + return "Das System-curl unterstützt kein SFTP. Bitte `brew install curl` ausführen (wird automatisch verwendet)." + } + } +} + +/// FTP/FTPS/SFTP upload via curl (ships with macOS; Homebrew curl is preferred when present for SFTP). +public struct FTPUploader: Sendable { + public init() {} + + static func curlBinary(needsSFTP: Bool) -> String? { + let candidates = ["/opt/homebrew/opt/curl/bin/curl", "/usr/local/opt/curl/bin/curl", "/usr/bin/curl"] + for c in candidates where FileManager.default.isExecutableFile(atPath: c) { + if !needsSFTP || supportsSFTP(c) { return c } + } + return nil + } + + static func supportsSFTP(_ curl: String) -> Bool { + guard let out = try? runSync(curl, ["-V"], stdin: nil).stdout else { return false } + return out.contains(" sftp") + } + + /// Escapes a value for curl's config file syntax. + static func configQuote(_ s: String) -> String { + "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" + } + + static func encodePath(_ p: String) -> String { + p.split(separator: "/", omittingEmptySubsequences: true) + .map { String($0).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))) ?? String($0) } + .joined(separator: "/") + } + + public func baseURL(_ d: FTPDestination) -> String { + let scheme: String + switch d.proto { + case .ftp, .ftpsExplicit: scheme = "ftp" + case .ftpsImplicit: scheme = "ftps" + case .sftp: scheme = "sftp" + } + var dir = FTPUploader.encodePath(d.remoteDirectory) + if !dir.isEmpty { dir += "/" } + // SFTP paths are absolute from root with "/~/" for home; FTP paths relative to login dir. + let prefix = d.proto == .sftp && !d.remoteDirectory.hasPrefix("/") ? "/~/" : "/" + return "\(scheme)://\(d.host):\(d.port)\(prefix)\(dir)" + } + + /// Uploads one file. `remoteName` defaults to the local file name. + public func upload(file: URL, remoteName: String? = nil, to d: FTPDestination, password: String?) async throws { + let name = remoteName ?? file.lastPathComponent + guard let curl = FTPUploader.curlBinary(needsSFTP: d.proto == .sftp) else { throw UploadError.curlMissingSFTP } + let tempName = d.uploadWithTempName ? name + ".part" : name + let url = baseURL(d) + FTPUploader.encodePath(tempName) + + var config: [String] = [] + config.append("user = " + FTPUploader.configQuote("\(d.username):\(password ?? "")")) + var args = ["--silent", "--show-error", "--fail", "--ftp-create-dirs", "--retry", "2", + "--connect-timeout", "20", "-K", "-", "-T", file.path, url] + switch d.proto { + case .ftpsExplicit: args.insert("--ssl-reqd", at: 0) + case .sftp: + if !d.sshKeyPath.isEmpty { args.insert(contentsOf: ["--key", (d.sshKeyPath as NSString).expandingTildeInPath], at: 0) } + default: break + } + if d.allowInsecureTLS { args.insert("--insecure", at: 0) } + if !d.passive && d.proto != .sftp { args.insert(contentsOf: ["--ftp-port", "-"], at: 0) } + if d.uploadWithTempName { + if d.proto == .sftp { + let dir = d.remoteDirectory.hasPrefix("/") ? d.remoteDirectory : "~/" + d.remoteDirectory + let base = dir.hasSuffix("/") ? dir : dir + "/" + args.insert(contentsOf: ["-Q", "-rename \"\(base)\(tempName)\" \"\(base)\(name)\""], at: 0) + } else { + args.insert(contentsOf: ["-Q", "-RNFR \(tempName)", "-Q", "-RNTO \(name)"], at: 0) + } + } + let result = try await FTPUploader.run(curl, args, stdin: config.joined(separator: "\n") + "\n") + if result.status != 0 { + throw UploadError.failed("Upload \(name) → \(d.name) fehlgeschlagen: \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))") + } + } + + /// Checks login + directory listing. + public func testConnection(_ d: FTPDestination, password: String?) async throws { + guard let curl = FTPUploader.curlBinary(needsSFTP: d.proto == .sftp) else { throw UploadError.curlMissingSFTP } + var args = ["--silent", "--show-error", "--fail", "--connect-timeout", "15", "-K", "-", "--list-only", baseURL(d)] + if d.proto == .ftpsExplicit { args.insert("--ssl-reqd", at: 0) } + if d.allowInsecureTLS { args.insert("--insecure", at: 0) } + if d.proto == .sftp, !d.sshKeyPath.isEmpty { args.insert(contentsOf: ["--key", (d.sshKeyPath as NSString).expandingTildeInPath], at: 0) } + let cfg = "user = " + FTPUploader.configQuote("\(d.username):\(password ?? "")") + "\n" + let r = try await FTPUploader.run(curl, args, stdin: cfg) + if r.status != 0 { throw UploadError.failed(r.stderr.isEmpty ? "Verbindung fehlgeschlagen (curl \(r.status))" : r.stderr) } + } + + // MARK: Process helpers + + struct ProcResult { var status: Int32; var stdout: String; var stderr: String } + + static func run(_ exe: String, _ args: [String], stdin: String?) async throws -> ProcResult { + try await withCheckedThrowingContinuation { cont in + DispatchQueue.global(qos: .utility).async { + do { cont.resume(returning: try runSync(exe, args, stdin: stdin)) } catch { cont.resume(throwing: error) } + } + } + } + + static func runSync(_ exe: String, _ args: [String], stdin: String?) throws -> ProcResult { + let p = Process() + p.executableURL = URL(fileURLWithPath: exe) + p.arguments = args + let out = Pipe(), err = Pipe(), inp = Pipe() + p.standardOutput = out + p.standardError = err + p.standardInput = inp + try p.run() + if let stdin { inp.fileHandleForWriting.write(Data(stdin.utf8)) } + try? inp.fileHandleForWriting.close() + // Read both pipes concurrently to avoid dead-locks on large output. + var errData = Data() + let g = DispatchGroup() + g.enter() + DispatchQueue.global().async { errData = err.fileHandleForReading.readDataToEndOfFile(); g.leave() } + let outData = out.fileHandleForReading.readDataToEndOfFile() + g.wait() + p.waitUntilExit() + return ProcResult(status: p.terminationStatus, stdout: String(decoding: outData, as: UTF8.self), + stderr: String(decoding: errData, as: UTF8.self)) + } +} diff --git a/Sources/LichtkastenCore/Upload/ImmichClient.swift b/Sources/LichtkastenCore/Upload/ImmichClient.swift new file mode 100644 index 0000000..c01abe0 --- /dev/null +++ b/Sources/LichtkastenCore/Upload/ImmichClient.swift @@ -0,0 +1,156 @@ +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +public struct ImmichSettings: Codable, Hashable, Sendable { + /// e.g. https://photos.example.com (without /api) + public var serverURL: String + /// Album to add uploads to (created if missing). Empty = no album. + public var albumName: String + public var variant: UploadVariant + public var enabled: Bool + + public init(serverURL: String = "", albumName: String = "", variant: UploadVariant = .jpeg, enabled: Bool = false) { + self.serverURL = serverURL; self.albumName = albumName; self.variant = variant; self.enabled = enabled + } + + public static let keychainAccount = "immich-api-key" +} + +public enum ImmichError: LocalizedError { + case badURL, http(Int, String), decoding + + public var errorDescription: String? { + switch self { + case .badURL: return "Ungültige Immich-Server-URL." + case .http(let code, let body): return "Immich antwortet mit HTTP \(code): \(body.prefix(300))" + case .decoding: return "Unerwartete Antwort vom Immich-Server." + } + } +} + +/// Minimal Immich REST client (API key auth). Uses /api/assets (Immich ≥ 1.118). +public final class ImmichClient: @unchecked Sendable { + let base: URL + let apiKey: String + let session: URLSession + let deviceId = "Lichtkasten-Mac" + private var albumCache: [String: String] = [:] + private let lock = NSLock() + + public init(settings: ImmichSettings, apiKey: String) throws { + var s = settings.serverURL.trimmingCharacters(in: .whitespacesAndNewlines) + while s.hasSuffix("/") { s.removeLast() } + if s.hasSuffix("/api") { s.removeLast(4) } + guard let u = URL(string: s + "/api"), u.scheme?.hasPrefix("http") == true else { throw ImmichError.badURL } + base = u + self.apiKey = apiKey + let cfg = URLSessionConfiguration.default + cfg.timeoutIntervalForRequest = 120 + cfg.timeoutIntervalForResource = 3600 + session = URLSession(configuration: cfg) + } + + private func request(_ path: String, method: String = "GET", json: Any? = nil) throws -> URLRequest { + var r = URLRequest(url: base.appendingPathComponent(path)) + r.httpMethod = method + r.setValue(apiKey, forHTTPHeaderField: "x-api-key") + r.setValue("application/json", forHTTPHeaderField: "Accept") + if let json { + r.httpBody = try JSONSerialization.data(withJSONObject: json) + r.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + return r + } + + private func send(_ r: URLRequest) async throws -> Any? { + let (data, resp) = try await session.data(for: r) + let code = (resp as? HTTPURLResponse)?.statusCode ?? 0 + guard (200..<300).contains(code) else { throw ImmichError.http(code, String(decoding: data, as: UTF8.self)) } + return data.isEmpty ? nil : try? JSONSerialization.jsonObject(with: data) + } + + /// Returns the logged-in user's name (connection test). + public func testConnection() async throws -> String { + let obj = try await send(try request("users/me")) as? [String: Any] + return (obj?["name"] as? String) ?? (obj?["email"] as? String) ?? "OK" + } + + public struct UploadResult: Sendable { public let assetId: String; public let duplicate: Bool } + + /// Uploads one file as multipart/form-data (streamed from a temp file, RAWs can be large). + /// Newer Immich (3.x) dropped deviceAssetId/deviceId; older servers require them → automatic retry. + public func upload(file: URL, captureDate: Date?) async throws -> UploadResult { + do { + return try await upload(file: file, captureDate: captureDate, legacyFields: false) + } catch ImmichError.http(400, let body) where body.contains("deviceAssetId") || body.contains("deviceId") { + return try await upload(file: file, captureDate: captureDate, legacyFields: true) + } + } + + private func upload(file: URL, captureDate: Date?, legacyFields: Bool) async throws -> UploadResult { + let attrs = try FileManager.default.attributesOfItem(atPath: file.path) + let modified = (attrs[.modificationDate] as? Date) ?? Date() + let size = (attrs[.size] as? NSNumber)?.int64Value ?? 0 + let created = captureDate ?? modified + let iso = ISO8601DateFormatter() + iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + + let boundary = "----Lichtkasten\(UUID().uuidString)" + let body = FileManager.default.temporaryDirectory.appendingPathComponent("immich-\(UUID().uuidString).multipart") + FileManager.default.createFile(atPath: body.path, contents: nil) + let h = try FileHandle(forWritingTo: body) + defer { try? FileManager.default.removeItem(at: body) } + + func field(_ name: String, _ value: String) { + h.write(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"\r\n\r\n\(value)\r\n".utf8)) + } + if legacyFields { + field("deviceAssetId", "\(file.lastPathComponent)-\(size)") + field("deviceId", deviceId) + } + field("fileCreatedAt", iso.string(from: created)) + field("fileModifiedAt", iso.string(from: modified)) + field("filename", file.lastPathComponent) + h.write(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"assetData\"; filename=\"\(file.lastPathComponent)\"\r\nContent-Type: application/octet-stream\r\n\r\n".utf8)) + let src = try FileHandle(forReadingFrom: file) + while true { + let chunk = src.readData(ofLength: 4 << 20) + if chunk.isEmpty { break } + h.write(chunk) + } + try src.close() + h.write(Data("\r\n--\(boundary)--\r\n".utf8)) + try h.close() + + var r = try request("assets", method: "POST") + r.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") + let (data, resp) = try await session.upload(for: r, fromFile: body) + let code = (resp as? HTTPURLResponse)?.statusCode ?? 0 + guard (200..<300).contains(code) else { throw ImmichError.http(code, String(decoding: data, as: UTF8.self)) } + guard let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any], let id = obj["id"] as? String else { + throw ImmichError.decoding + } + return UploadResult(assetId: id, duplicate: (obj["status"] as? String) == "duplicate") + } + + /// Finds or creates an album and returns its id. + public func albumId(named name: String) async throws -> String { + lock.lock(); let cached = albumCache[name]; lock.unlock() + if let cached { return cached } + if let list = try await send(try request("albums")) as? [[String: Any]], + let existing = list.first(where: { ($0["albumName"] as? String) == name }), let id = existing["id"] as? String { + lock.lock(); albumCache[name] = id; lock.unlock() + return id + } + guard let created = try await send(try request("albums", method: "POST", json: ["albumName": name])) as? [String: Any], + let id = created["id"] as? String else { throw ImmichError.decoding } + lock.lock(); albumCache[name] = id; lock.unlock() + return id + } + + public func add(assetIds: [String], toAlbum albumId: String) async throws { + _ = try await send(try request("albums/\(albumId)/assets", method: "PUT", json: ["ids": assetIds])) + } +} diff --git a/Tests/LichtkastenCoreTests/CoreTests.swift b/Tests/LichtkastenCoreTests/CoreTests.swift new file mode 100644 index 0000000..36688a8 --- /dev/null +++ b/Tests/LichtkastenCoreTests/CoreTests.swift @@ -0,0 +1,93 @@ +import XCTest +@testable import LichtkastenCore + +final class VariableTests: XCTestCase { + func testExpandsFileAndDateVariables() { + let ctx = VariableContext.make(fileURL: URL(fileURLWithPath: "/x/IMG_0001.CR3"), + exif: ["DateTimeOriginal": "2026:11:03 14:22:01", "Model": "Canon EOS R5"]) + XCTAssertEqual(VariableExpander.expand("{filenamebase} {date} {isodate} {model}", context: ctx), + "IMG_0001 03.11.2026 2026-11-03 Canon EOS R5") + XCTAssertEqual(VariableExpander.expand("{unbekannt}", context: ctx), "{unbekannt}") + } + + func testCodeReplacement() { + let codes = CodeReplacements.load(tabDelimited: "bvb\tBorussia Dortmund\tBVB\n# Kommentar\ns04\tFC Schalke 04\tS04\n") + XCTAssertEqual(codes.expand("\\bvb\\ gegen \\s04#2\\"), "Borussia Dortmund gegen S04") + XCTAssertEqual(codes.expand("Pfad C:\\temp\\x"), "Pfad C:\\temp\\x") + } +} + +final class TemplateTests: XCTestCase { + let pmXMP = """ + + + + Max Müller + {city}, {date} – Fußball + SportFußball + + max@example.de + + + + + """ + + func testImportPMTemplate() throws { + let t = try XMPTemplateIO.parse(data: Data(pmXMP.utf8)) + XCTAssertEqual(t.values.text["city"], "Dortmund") + XCTAssertEqual(t.values.text["credit"], "Agentur XY") + XCTAssertEqual(t.values.text["creator"], "Max Müller") + XCTAssertEqual(t.values.text["caption"], "{city}, {date} – Fußball") + XCTAssertEqual(t.values.lists["keywords"], ["Sport", "Fußball"]) + XCTAssertEqual(t.values.text["ciEmail"], "max@example.de") + XCTAssertEqual(t.extras["\(XMPNamespace.photomechanic)|Foo"], "bar") + } + + func testExportRoundTrip() throws { + let t = try XMPTemplateIO.parse(data: Data(pmXMP.utf8)) + let again = try XMPTemplateIO.parse(data: Data(XMPTemplateIO.export(t).utf8)) + XCTAssertEqual(again.values, t.values) + XCTAssertEqual(again.extras, t.extras) + } + + func testApplyAppendsKeywords() { + var existing = IPTCValues() + existing.lists["keywords"] = ["Sport"] + existing.text["headline"] = "Alt" + let t = IPTCTemplate(name: "t", values: IPTCValues(text: ["headline": "Neu"], lists: ["keywords": ["Sport", "BVB"]])) + let r = t.apply(to: existing) + XCTAssertEqual(r.lists["keywords"], ["Sport", "BVB"]) + XCTAssertEqual(r.text["headline"], "Neu") + } + + func testWriterArgumentsForJPEGAndRAW() throws { + let w = MetadataWriter(exiftool: ExifTool(executable: URL(fileURLWithPath: "/usr/bin/true"))) + var v = IPTCValues() + v.text["city"] = "Dortmund" + v.lists["keywords"] = ["A", "B"] + let fields = [IPTCField.byID["city"]!, IPTCField.byID["keywords"]!] + let jpeg = try w.arguments(values: v, fields: fields, targetKind: .jpeg) + XCTAssertTrue(jpeg.contains("-IPTC:City=Dortmund")) + XCTAssertTrue(jpeg.contains("-XMP-photoshop:City=Dortmund")) + XCTAssertTrue(jpeg.contains("-IPTC:CodedCharacterSet=UTF8")) + XCTAssertEqual(jpeg.filter { $0 == "-IPTC:Keywords=A" || $0 == "-IPTC:Keywords=B" }.count, 2) + let raw = try w.arguments(values: v, fields: fields, targetKind: .raw) + XCTAssertFalse(raw.contains { $0.hasPrefix("-IPTC:") }) + } +} + +final class LightroomJobTests: XCTestCase { + func testResultParsing() { + let r = LightroomJobResult.parse("id=abc\nstatus=done\nimported=2\nexported=/a/b.jpg\nerror=x\n") + XCTAssertEqual(r.id, "abc") + XCTAssertTrue(r.ok) + XCTAssertEqual(r.imported, 2) + XCTAssertEqual(r.exported.map(\.path), ["/a/b.jpg"]) + } +} diff --git a/scripts/build-app.sh b/scripts/build-app.sh new file mode 100755 index 0000000..50e3af2 --- /dev/null +++ b/scripts/build-app.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# Baut Lichtkasten.app (Apple Silicon) nach build/Lichtkasten.app +set -euo pipefail +cd "$(dirname "$0")/.." + +CONFIG="${1:-release}" +swift build -c "$CONFIG" --arch arm64 +BIN="$(swift build -c "$CONFIG" --arch arm64 --show-bin-path)/Lichtkasten" + +APP="build/Lichtkasten.app" +rm -rf "$APP" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp "$BIN" "$APP/Contents/MacOS/Lichtkasten" +cp Resources/Info.plist "$APP/Contents/Info.plist" +cp -R LightroomPlugin/LichtkastenBridge.lrplugin "$APP/Contents/Resources/" +[ -f Resources/AppIcon.icns ] && cp Resources/AppIcon.icns "$APP/Contents/Resources/" + +# Ad-hoc-Signatur (reicht für den eigenen Mac) +codesign --force --deep --sign - "$APP" +echo "✅ Fertig: $APP" +echo " Starten: open $APP" +echo " Installieren: cp -R $APP /Applications/"