diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift index 7695748..f5ab5b2 100644 --- a/Sources/Lichtkasten/Services/AppState.swift +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -144,6 +144,10 @@ final class AppState: ObservableObject { /// First launch: agency FTP profiles (host/user are placeholders – adjust in Settings → FTP). private func seedDefaultsIfNeeded() { // Leon's folder layout: ~/Desktop/BILDER/INPUT (ingest) and ~/Desktop/BILDER/SENT (JPEG export) + if !UserDefaults.standard.bool(forKey: "seededImmichAlbum") { + UserDefaults.standard.set(true, forKey: "seededImmichAlbum") + if settings.immich.albumName.isEmpty { settings.immich.albumName = "{event}" } + } if !UserDefaults.standard.bool(forKey: "seededBILDER") { UserDefaults.standard.set(true, forKey: "seededBILDER") let bilder = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop/BILDER") @@ -889,8 +893,16 @@ final class AppState: ObservableObject { do { try await w.write(values: src.iptc, fields: IPTCField.all, to: jpegItem) } catch { report(error) } } } + // Exported JPEGs carry the IPTC of their RAW (needed for {event} album names, rename patterns …) + let exportedItems: [PhotoItem] = files.compactMap { file in + let base = file.deletingPathExtension().lastPathComponent + guard let src = sources.first(where: { base == $0.baseName || base.hasPrefix($0.baseName + "-") }) else { return nil } + var it = PhotoItem(primary: file) + it.iptc = src.iptc; it.exif = src.exif; it.captureDate = src.captureDate + return it + } for target in job.uploadTargets { - uploads.enqueue(files: files, target: target, sourceItems: sources) + uploads.enqueue(files: files, target: target, sourceItems: exportedItems) } if !job.uploadTargets.isEmpty { openWindow("tasks") } // SENT workflow: show the exported JPEGs for captioning. @@ -901,6 +913,22 @@ final class AppState: ObservableObject { // MARK: Upload + /// Immich album name for an image: the album pattern with variables from its IPTC/EXIF, + /// e.g. "{event}" → "DFB-Pokal Frauen: VfL Wolfsburg - TSG 1899 Hoffenheim". + /// Unresolved variables are dropped; if nothing is left the fallback pattern is used. + func immichAlbum(for item: PhotoItem) -> String { + func resolve(_ pattern: String) -> String { + guard !pattern.isEmpty else { return "" } + let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, iptc: item.iptc, dateFormat: settings.dateFormat) + var s = VariableExpander.expand(pattern, context: ctx, codes: nil) + // drop variables that had no value, tidy separators + while let open = s.firstIndex(of: "{"), let close = s[open...].firstIndex(of: "}") { s.removeSubrange(open...close) } + return s.trimmingCharacters(in: CharacterSet(charactersIn: " -–|·,").union(.whitespaces)) + } + let main = resolve(settings.immich.albumName) + return main.isEmpty ? resolve(settings.immich.albumFallback) : main + } + /// Files to upload for an item, depending on the destination's variant. func uploadFiles(for item: PhotoItem, variant: UploadVariant) -> [URL] { switch variant { diff --git a/Sources/Lichtkasten/Services/UploadQueue.swift b/Sources/Lichtkasten/Services/UploadQueue.swift index e4f89d7..74a1db5 100644 --- a/Sources/Lichtkasten/Services/UploadQueue.swift +++ b/Sources/Lichtkasten/Services/UploadQueue.swift @@ -10,6 +10,8 @@ struct UploadJob: Identifiable { let targetName: String let remoteName: String let captureDate: Date? + /// Immich album for this file (pattern already expanded with the image's IPTC, e.g. "{event}"). + var album = "" var status: Status = .waiting var attempts = 0 var batch: UUID? @@ -31,7 +33,8 @@ final class UploadQueue: ObservableObject { private let maxParallel = 2 private var immichClient: ImmichClient? private var immichAlbumId: String? - private var immichNewAssets: [String] = [] + /// album name → new asset ids + private var immichNewAssets: [String: [String]] = [:] /// Removes waiting jobs of a batch (running transfers finish). func cancelBatch(_ id: UUID?) { @@ -67,6 +70,9 @@ final class UploadQueue: ObservableObject { } var job = UploadJob(file: f, target: target, targetName: name, remoteName: remote, captureDate: src?.captureDate) job.batch = batch + if target == "immich" { + job.album = state.immichAlbum(for: src ?? state.item(f.path) ?? PhotoItem(primary: f)) + } jobs.append(job) } pump() @@ -113,7 +119,8 @@ final class UploadQueue: ObservableObject { 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) } + // Duplicates are added to the album too (e.g. re-upload after captioning). + if !job.album.isEmpty { immichNewAssets[job.album, default: []].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 { @@ -145,16 +152,17 @@ final class UploadQueue: ObservableObject { 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 } + let batches = immichNewAssets + immichNewAssets = [:] Task { - do { - let albumId = try await client.albumId(named: album) - try await client.add(assetIds: ids, toAlbum: albumId) - } catch { - state.report(error) + for (album, ids) in batches { + do { + let albumId = try await client.albumId(named: album) + try await client.add(assetIds: ids, toAlbum: albumId) + state.statusText = "Immich: \(ids.count) Bild(er) im Album „\(album)“" + } catch { + state.report(error) + } } } } diff --git a/Sources/Lichtkasten/Views/SettingsView.swift b/Sources/Lichtkasten/Views/SettingsView.swift index 7bb1937..33d7502 100644 --- a/Sources/Lichtkasten/Views/SettingsView.swift +++ b/Sources/Lichtkasten/Views/SettingsView.swift @@ -158,7 +158,14 @@ struct ImmichSettingsView: View { 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) + TextField("Album", text: $state.settings.immich.albumName, prompt: Text("{event}")) + TextField("Album, wenn kein Ereignis im IPTC", text: $state.settings.immich.albumFallback, prompt: Text("{isodate} {city}")) + Text("Variablen aus IPTC/EXIF pro Bild, z. B. {event}, {headline}, {city}, {sublocation}, {isodate}, {date}, {year4}, {creator}. Fehlende Alben werden angelegt, leer = kein Album.") + .font(.caption).foregroundStyle(.secondary) + if let first = state.selectedItems.first { + LabeledContent("Beispiel (\(first.filename))", value: state.immichAlbum(for: first).isEmpty ? "– kein Album –" : state.immichAlbum(for: first)) + .font(.caption) + } Picker("Dateien", selection: $state.settings.immich.variant) { ForEach(UploadVariant.allCases, id: \.self) { Text($0.rawValue).tag($0) } } diff --git a/Sources/Lichtkasten/Views/UploadWindow.swift b/Sources/Lichtkasten/Views/UploadWindow.swift index be8a8e8..82811cf 100644 --- a/Sources/Lichtkasten/Views/UploadWindow.swift +++ b/Sources/Lichtkasten/Views/UploadWindow.swift @@ -39,7 +39,9 @@ struct UploadWindow: View { } } else if target == "immich" { LabeledContent("Server", value: state.settings.immich.serverURL) - LabeledContent("Album", value: state.settings.immich.albumName.isEmpty ? "–" : state.settings.immich.albumName) + let albums = Set(state.selectedItems.map { state.immichAlbum(for: $0) }.filter { !$0.isEmpty }) + LabeledContent("Album", value: albums.isEmpty ? "– kein Album –" : albums.sorted().joined(separator: ", ")) + TextField("Album-Muster", text: $state.settings.immich.albumName, prompt: Text("{event}")) } LabeledContent("Auswahl", value: "\(state.selectedItems.count) Bild(er) → \(files.count) Datei(en)") if files.count < state.selectedItems.count { diff --git a/Sources/LichtkastenCore/Upload/ImmichClient.swift b/Sources/LichtkastenCore/Upload/ImmichClient.swift index c01abe0..d267971 100644 --- a/Sources/LichtkastenCore/Upload/ImmichClient.swift +++ b/Sources/LichtkastenCore/Upload/ImmichClient.swift @@ -6,8 +6,10 @@ import FoundationNetworking 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. + /// Album pattern with variables, e.g. "{event}" or "{isodate} {event}" (created if missing). Empty = no album. public var albumName: String + /// Used when the pattern resolves to nothing (image without event), e.g. "{isodate} {city}". Empty = no album. + public var albumFallback: String = "{isodate} {city}" public var variant: UploadVariant public var enabled: Bool @@ -16,6 +18,17 @@ public struct ImmichSettings: Codable, Hashable, Sendable { } public static let keychainAccount = "immich-api-key" + + enum CodingKeys: String, CodingKey { case serverURL, albumName, albumFallback, variant, enabled } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + serverURL = (try? c.decode(String.self, forKey: .serverURL)) ?? "" + albumName = (try? c.decode(String.self, forKey: .albumName)) ?? "" + albumFallback = (try? c.decode(String.self, forKey: .albumFallback)) ?? "{isodate} {city}" + variant = (try? c.decode(UploadVariant.self, forKey: .variant)) ?? .jpeg + enabled = (try? c.decode(Bool.self, forKey: .enabled)) ?? false + } } public enum ImmichError: LocalizedError {