Files
lichtkasten/Sources/LichtkastenCore/Metadata/MetadataWriter.swift
T

162 lines
8.1 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
}
/// Writes tag, color class and stars in one go – in every place PM and Lightroom look:
/// xmp:Rating, xmp:Label, photomechanic:Tagged/ColorClass/Prefs and (JPEG/TIFF) IPTC 2:221 Prefs.
public func writeState(of item: PhotoItem) async throws {
let prefs = item.pmPrefsString
for target in item.metadataTargets {
var args = ["-overwrite_original", "-m",
// -1 = rejected in Lightroom – keep it
"-XMP-xmp:Rating=\(max(-1, min(5, item.rating)))",
"-XMP-photomech:Tagged=\(item.tagged ? "Yes" : "No")",
"-XMP-photomech:Prefs=\(prefs)"]
if let l = item.label {
args += ["-XMP-xmp:Label=\(l.xmpValue)", "-XMP-photomech:ColorClass=\(l.pmColorClass)"]
} else {
args += ["-XMP-xmp:Label=", "-XMP-photomech:ColorClass=0"]
}
if target.kind.supportsIIM { args += ["-IPTC:Prefs=\(prefs)"] }
let (_, err) = try await exiftool.execute(args + [target.url.path])
if err.contains("Error:") { throw ExifToolError.failed(err) }
}
}
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 if field.id == "dateCreated" {
args += Self.dateArguments(values.text[field.id] ?? "", writeIIM: writeIIM)
} else {
let value = values.text[field.id] ?? ""
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
}
/// "2026-11-02" or "2026-11-02 14:22:01[+01:00]" → XMP DateCreated (full) + IIM DateCreated/TimeCreated.
static func dateArguments(_ raw: String, writeIIM: Bool) -> [String] {
let v = raw.trimmingCharacters(in: .whitespaces)
if v.isEmpty {
return ["-XMP-photoshop:DateCreated="] + (writeIIM ? ["-IPTC:DateCreated=", "-IPTC:TimeCreated="] : [])
}
let normalized = v.replacingOccurrences(of: "T", with: " ")
let datePart = String(normalized.prefix(10)).replacingOccurrences(of: "-", with: ":")
guard datePart.count == 10, datePart.filter({ $0 == ":" }).count == 2 else { return [] } // invalid → skip
let timePart = normalized.count > 11 ? String(normalized.dropFirst(11)) : ""
var args = ["-XMP-photoshop:DateCreated=\(datePart)\(timePart.isEmpty ? "" : " " + timePart)"]
if writeIIM {
args.append("-IPTC:DateCreated=\(datePart)")
args.append("-IPTC:TimeCreated=\(timePart)")
}
return args
}
/// Capture time from EXIF as "yyyy-MM-dd HH:mm:ss+hh:mm" (camera offset, else the Mac's offset at that date).
public static func captureDateValue(exif: [String: String]) -> String? {
guard let raw = exif["DateTimeOriginal"] ?? exif["CreateDate"], raw.count >= 19 else { return nil }
let clock = String(raw.prefix(19))
let datePart = String(clock.prefix(10)).replacingOccurrences(of: ":", with: "-")
let timePart = String(clock.suffix(8))
var offset = exif["OffsetTimeOriginal"] ?? ""
if offset.count != 6, let d = ExifDate.parse(clock) {
let secs = TimeZone.current.secondsFromGMT(for: d)
offset = String(format: "%@%02d:%02d", secs < 0 ? "-" : "+", abs(secs) / 3600, (abs(secs) % 3600) / 60)
}
return "\(datePart) \(timePart)\(offset)"
}
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 = template.fieldsToWrite
for (i, item) in items.enumerated() {
var merged = template.apply(to: item.iptc)
if template.dateFromCapture, fields.contains(where: { $0.id == "dateCreated" }) {
merged.text["dateCreated"] = Self.captureDateValue(exif: item.exif) ?? merged.text["dateCreated"]
}
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
}
}