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,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