Files
lichtkasten/Sources/LichtkastenCore/Ingest/IngestService.swift
T

92 lines
4.5 KiB
Swift

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,
onFolder: (@Sendable (URL) -> Void)? = nil,
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) }
progress(IngestProgress(done: 0, total: items.count, currentFile: "Lese Aufnahmedaten …"))
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
progress(IngestProgress(done: 0, total: total, currentFile: "Starte …"))
for item in items {
try Task.checkCancellation()
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).inserted { onFolder?(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)
}
}