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:
37 files changed
+4431
No files matched your search
@@ -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: "&").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]))</\(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]))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user