Lichtkasten v0.1: Culling, IPTC (PM-kompatibel), Vorlagen, FTP/Immich, Lightroom-Bridge

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
This commit is contained in:
Lichtkasten DevandClaude Opus 5.5 committed 2026-11-03 22:40:28 +00:00
commit e13cbf416d
37 files changed
+4431

No files matched your search

@@ -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<URL>()
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)
}
}
@@ -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<String> = [
"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 }
}
}
@@ -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[..<eq]), v = String(line[line.index(after: eq)...])
switch k {
case "id": r.id = v
case "status": r.ok = v == "done"
case "imported": r.imported = Int(v) ?? 0
case "exported": r.exported.append(URL(fileURLWithPath: v))
case "error": r.errors.append(v)
default: break
}
}
return r
}
}
public enum LightroomBridge {
public static var root: URL {
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("Lichtkasten/LRBridge", isDirectory: true)
}
public static var inbox: URL { root.appendingPathComponent("inbox", isDirectory: true) }
public static var outbox: URL { root.appendingPathComponent("outbox", isDirectory: true) }
public static var heartbeat: URL { root.appendingPathComponent("heartbeat") }
/// Lightroom Classic loads every *.lrplugin in this folder automatically.
public static var lightroomModulesFolder: URL {
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("Adobe/Lightroom/Modules", isDirectory: true)
}
public static let lightroomBundleIDs = ["com.adobe.LightroomClassicCC7"]
public static func prepareFolders() throws {
for d in [inbox, outbox] { try FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) }
}
/// Writes the job atomically (tmp + rename) so the plugin never reads half a file.
public static func submit(_ job: LightroomJob) throws {
try prepareFolders()
let tmp = inbox.appendingPathComponent(job.id + ".tmp")
try Data(job.serialized().utf8).write(to: tmp)
let final = inbox.appendingPathComponent(job.id + ".job")
try? FileManager.default.removeItem(at: final)
try FileManager.default.moveItem(at: tmp, to: final)
}
/// Collects finished results and removes them from the outbox.
public static func collectResults() -> [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)
}
}
@@ -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..<out.endIndex)
break
}
}
// stderr arrives asynchronously; give it a moment.
Thread.sleep(forTimeInterval: 0.005)
stderrLock.lock(); let err = String(decoding: stderrBuffer, as: UTF8.self); stderrLock.unlock()
return (String(decoding: out, as: UTF8.self), err)
}
/// Writes a (possibly multi-line) value to a temp file so it can be passed as `-TAG<=file`.
public func writeValueFile(_ value: String) throws -> 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
}
}
}
@@ -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)
}
}
@@ -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
}
}
@@ -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
}
}
@@ -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[..<hash])
column = n
}
let key = caseSensitive ? name : name.lowercased()
let row = caseSensitive ? table.first(where: { $0.key == key })?.value : table[key]
guard let row, column >= 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)..<close])
if !code.isEmpty, !code.contains(" "), let rep = lookup(code) {
out += rep
i = text.index(after: close)
continue
}
}
out.append(ch)
i = text.index(after: i)
}
return out
}
}
public enum VariableExpander {
/// Expands `{variable}` tokens. Unknown variables are left untouched so the user notices them.
public static func expand(_ text: String, context: VariableContext, codes: CodeReplacements? = nil) -> 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[..<open]
guard let close = rest[open...].firstIndex(of: "}") else { break }
let name = rest[rest.index(after: open)..<close].lowercased()
if let v = context.values[name] {
out += v
} else {
out += rest[open...close]
}
rest = rest[rest.index(after: close)...]
}
out += rest
s = out
return s
}
public static func expand(_ values: IPTCValues, context: VariableContext, codes: CodeReplacements?) -> 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"),
]
}
@@ -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: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
}
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]))</\(q)>")
continue
}
switch field.xmpContainer {
case .simple:
simpleAttrs.append(" \(q)=\"\(esc(vals[0]))\"")
case .alt:
elements.append(" <\(q)>\n <rdf:Alt>\n <rdf:li xml:lang=\"x-default\">\(esc(vals[0]))</rdf:li>\n </rdf:Alt>\n </\(q)>")
case .seq, .bag:
let tag = field.xmpContainer == .seq ? "rdf:Seq" : "rdf:Bag"
let lis = vals.map { " <rdf:li>\(esc($0))</rdf:li>" }.joined(separator: "\n")
elements.append(" <\(q)>\n <\(tag)>\n\(lis)\n </\(tag)>\n </\(q)>")
}
}
if !contact.isEmpty {
elements.append(" <Iptc4xmpCore:CreatorContactInfo rdf:parseType=\"Resource\">\n\(contact.joined(separator: "\n"))\n </Iptc4xmpCore:CreatorContactInfo>")
}
// 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 { " <rdf:li>\(esc($0))</rdf:li>" }.joined(separator: "\n")
elements.append(" <\(prefix):\(parts[1])>\n <rdf:Bag>\n\(lis)\n </rdf:Bag>\n </\(prefix):\(parts[1])>")
}
}
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 """
<?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Lichtkasten">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about=""
\(nsDecl.joined(separator: "\n"))\(simpleAttrs.isEmpty ? "" : "\n" + simpleAttrs.joined(separator: "\n"))>
\(elements.joined(separator: "\n"))
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>
"""
}
}
/// 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]))
}
}
}
@@ -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 "<name>.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))
}
}
@@ -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]))
}
}