401 lines
20 KiB
Swift
401 lines
20 KiB
Swift
import CryptoKit
|
||
import Foundation
|
||
|
||
/// PM Ingest "Filter Files": in-camera protected (locked) photos.
|
||
public enum LockedFilter: String, Codable, CaseIterable, Sendable {
|
||
case all = "Gesperrte und nicht gesperrte Fotos kopieren"
|
||
case lockedOnly = "Nur gesperrte (geschützte) Fotos kopieren"
|
||
case unlockedOnly = "Nur nicht gesperrte Fotos kopieren"
|
||
}
|
||
|
||
public enum RawFilter: String, Codable, CaseIterable, Sendable {
|
||
case all = "RAW und nicht-RAW kopieren"
|
||
case rawOnly = "Nur RAW kopieren"
|
||
case nonRawOnly = "Nur nicht-RAW (JPEG …) kopieren"
|
||
}
|
||
|
||
/// Ingest settings in Photo Mechanic's structure.
|
||
public struct IngestSettings: Codable, Hashable, Sendable {
|
||
public var primaryDestination: String = ""
|
||
public var secondaryEnabled = false
|
||
public var backupDestination: String = ""
|
||
/// "Copy photos into folder with name", e.g. "{day0}.{month0}.{year4} - Wolfsburg (F) - Hoffenheim (F)".
|
||
public var folderPattern: String = "{day0}.{month0}.{year4} - "
|
||
/// Keep the card's folder structure (DCIM/100NZ8 …) below the destination folder.
|
||
public var preserveStructure = false
|
||
public var renameEnabled = true
|
||
/// Rename pattern without extension, e.g. "@leon.tonhaeuser-{seqn}".
|
||
public var renamePattern: String = "{filenamebase}"
|
||
public var sequenceEnabled = true
|
||
public var startSequence: Int = 1
|
||
public var incremental = true
|
||
public var lockedFilter: LockedFilter = .all
|
||
public var rawFilter: RawFilter = .all
|
||
/// Write the PM tag for photos that were protected in the camera.
|
||
public var tagLockedPhotos = true
|
||
public var applyTemplate = false
|
||
public var templateID: UUID?
|
||
public var openAfterIngest = true
|
||
/// PM "Open Contact Sheets in background": add the tab without switching to it.
|
||
public var openInBackground = false
|
||
public var unmountAfter = true
|
||
public var skipDuplicates = true
|
||
|
||
public init() {}
|
||
|
||
enum CodingKeys: String, CodingKey {
|
||
case primaryDestination, secondaryEnabled, backupDestination, folderPattern, preserveStructure, renameEnabled,
|
||
renamePattern, sequenceEnabled, startSequence, incremental, lockedFilter, rawFilter, tagLockedPhotos,
|
||
applyTemplate, templateID, openAfterIngest, openInBackground, unmountAfter, skipDuplicates
|
||
}
|
||
|
||
/// Tolerant decoding: new options never reset existing settings.
|
||
public init(from decoder: Decoder) throws {
|
||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||
let d = IngestSettings()
|
||
func v<T: Decodable>(_ k: CodingKeys, _ def: T) -> T { (try? c.decode(T.self, forKey: k)) ?? def }
|
||
primaryDestination = v(.primaryDestination, d.primaryDestination)
|
||
backupDestination = v(.backupDestination, d.backupDestination)
|
||
secondaryEnabled = v(.secondaryEnabled, !backupDestination.isEmpty)
|
||
folderPattern = v(.folderPattern, d.folderPattern)
|
||
preserveStructure = v(.preserveStructure, d.preserveStructure)
|
||
renamePattern = v(.renamePattern, d.renamePattern)
|
||
renameEnabled = v(.renameEnabled, !renamePattern.isEmpty)
|
||
sequenceEnabled = v(.sequenceEnabled, d.sequenceEnabled)
|
||
startSequence = v(.startSequence, d.startSequence)
|
||
incremental = v(.incremental, d.incremental)
|
||
lockedFilter = v(.lockedFilter, d.lockedFilter)
|
||
rawFilter = v(.rawFilter, d.rawFilter)
|
||
tagLockedPhotos = v(.tagLockedPhotos, d.tagLockedPhotos)
|
||
templateID = try? c.decode(UUID.self, forKey: .templateID)
|
||
applyTemplate = v(.applyTemplate, templateID != nil)
|
||
openAfterIngest = v(.openAfterIngest, d.openAfterIngest)
|
||
openInBackground = v(.openInBackground, d.openInBackground)
|
||
unmountAfter = v(.unmountAfter, d.unmountAfter)
|
||
skipDuplicates = v(.skipDuplicates, d.skipDuplicates)
|
||
}
|
||
}
|
||
|
||
public struct IngestProgress: Sendable {
|
||
public var done: Int
|
||
public var total: Int
|
||
public var currentFile: String
|
||
}
|
||
|
||
public struct IngestResult: Sendable {
|
||
public var folders: [URL]
|
||
/// Copied primary files (in the primary destination).
|
||
public var copied: [URL]
|
||
/// Copied files that were locked (protected) on the card.
|
||
public var lockedCopies: [URL]
|
||
public var nextSequence: Int
|
||
public var skipped: Int
|
||
}
|
||
|
||
public enum IngestService {
|
||
// MARK: Locked / incremental helpers
|
||
|
||
/// A photo protected in the camera shows up as read-only / locked (FAT read-only attribute).
|
||
public static func isLocked(_ url: URL, volumeReadOnly: Bool) -> Bool {
|
||
let fm = FileManager.default
|
||
if let attrs = try? fm.attributesOfItem(atPath: url.path), (attrs[.immutable] as? Bool) == true { return true }
|
||
if volumeReadOnly { return false } // SD write-protect switch: everything looks read-only
|
||
return !fm.isWritableFile(atPath: url.path)
|
||
}
|
||
|
||
static func volumeIsReadOnly(_ url: URL) -> Bool {
|
||
(try? url.resourceValues(forKeys: [.volumeIsReadOnlyKey]).volumeIsReadOnly) == true
|
||
}
|
||
|
||
static var historyURL: URL {
|
||
let d = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
||
.appendingPathComponent("Lichtkasten", isDirectory: true)
|
||
try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)
|
||
return d.appendingPathComponent("ingest-history-v2.json")
|
||
}
|
||
|
||
private struct HistoryKey: Codable {
|
||
let destinations: [URL]
|
||
let folderPattern: String
|
||
let preserveStructure: Bool
|
||
let sourceFolder: String
|
||
let renamePattern: String?
|
||
let files: [String]
|
||
}
|
||
|
||
private struct ImportedGroup: Codable {
|
||
let folders: [URL]
|
||
let name: String
|
||
}
|
||
|
||
private static func sourceFingerprint(_ url: URL) throws -> String {
|
||
let handle = try FileHandle(forReadingFrom: url)
|
||
defer { try? handle.close() }
|
||
var hash = SHA256()
|
||
while let chunk = try handle.read(upToCount: 1024 * 1024), !chunk.isEmpty {
|
||
try Task.checkCancellation()
|
||
hash.update(data: chunk)
|
||
}
|
||
let digest = Data(hash.finalize()).base64EncodedString()
|
||
return "\(url.lastPathComponent)|\(digest)"
|
||
}
|
||
|
||
private static func loadHistory(at url: URL) -> [String: ImportedGroup] {
|
||
guard let d = try? Data(contentsOf: url),
|
||
let history = try? JSONDecoder().decode([String: ImportedGroup].self, from: d) else { return [:] }
|
||
return history
|
||
}
|
||
|
||
private static func saveHistory(_ history: [String: ImportedGroup], at url: URL) throws {
|
||
try JSONEncoder().encode(history).write(to: url, options: .atomic)
|
||
}
|
||
|
||
/// Copy + make the copy writable again (otherwise locked files stay locked and metadata can't be written).
|
||
static func copy(_ src: URL, to dest: URL) throws {
|
||
let fm = FileManager.default
|
||
try fm.copyItem(at: src, to: dest)
|
||
try? fm.setAttributes([.immutable: false, .posixPermissions: 0o644], ofItemAtPath: dest.path)
|
||
}
|
||
|
||
// MARK: Run
|
||
|
||
/// Copies the photos (and their XMP sidecars) from `sources` like PM's Ingest.
|
||
public static func run(sources: [URL], settings: IngestSettings, exiftool: ExifTool,
|
||
onFolder: (@Sendable (URL) -> Void)? = nil,
|
||
onSequence: (@Sendable (Int) -> Void)? = nil,
|
||
progress: @escaping @Sendable (IngestProgress) -> Void) async throws -> IngestResult {
|
||
try await run(sources: sources, settings: settings, exiftool: exiftool,
|
||
historyFile: settings.incremental ? historyURL : nil,
|
||
onFolder: onFolder, onSequence: onSequence, progress: progress)
|
||
}
|
||
|
||
static func run(sources: [URL], settings: IngestSettings, exiftool: ExifTool, historyFile: URL?,
|
||
onFolder: (@Sendable (URL) -> Void)? = nil,
|
||
onSequence: (@Sendable (Int) -> Void)? = nil,
|
||
progress: @escaping @Sendable (IngestProgress) -> Void) async throws -> IngestResult {
|
||
let fm = FileManager.default
|
||
guard !settings.primaryDestination.isEmpty else { throw UploadError.failed("Kein Ziel für den Ingest gewählt.") }
|
||
|
||
let destRoots = ([settings.primaryDestination] +
|
||
(settings.secondaryEnabled && !settings.backupDestination.isEmpty ? [settings.backupDestination] : []))
|
||
.map { URL(fileURLWithPath: $0, isDirectory: true).resolvingSymlinksInPath().standardizedFileURL }
|
||
guard Set(destRoots).count == destRoots.count else {
|
||
throw UploadError.failed("Hauptziel und Backup-Ziel müssen verschieden sein.")
|
||
}
|
||
|
||
// A history entry proves which full group was copied to these destinations.
|
||
var history = historyFile.map { loadHistory(at: $0) } ?? [:]
|
||
var historyChanged = false
|
||
var skipped = 0
|
||
let keyEncoder = JSONEncoder()
|
||
keyEncoder.outputFormatting = [.sortedKeys]
|
||
typealias Entry = (item: PhotoItem, relativeFolder: String, locked: Bool, files: [URL], historyKey: String?)
|
||
var entries: [Entry] = []
|
||
progress(IngestProgress(done: 0, total: 0, currentFile: "Prüfe Quelldateien …"))
|
||
for source in sources {
|
||
let readOnly = volumeIsReadOnly(source)
|
||
for item in try FolderScanner.scan(folder: source, recursive: true) {
|
||
try Task.checkCancellation()
|
||
let locked = isLocked(item.primary, volumeReadOnly: readOnly)
|
||
if settings.lockedFilter == .lockedOnly && !locked { continue }
|
||
if settings.lockedFilter == .unlockedOnly && locked { continue }
|
||
|
||
var files = [item.primary] + item.companions
|
||
switch settings.rawFilter {
|
||
case .all: break
|
||
case .rawOnly: files = files.filter { FileKind(url: $0).isRawLike }
|
||
case .nonRawOnly: files = files.filter { !FileKind(url: $0).isRawLike }
|
||
}
|
||
guard !files.isEmpty else { continue }
|
||
if item.kind.usesSidecar, files.contains(item.primary), fm.fileExists(atPath: item.sidecarURL.path) {
|
||
files.append(item.sidecarURL)
|
||
}
|
||
|
||
let relative = settings.preserveStructure
|
||
? item.primary.deletingLastPathComponent().pathComponents
|
||
.dropFirst(source.pathComponents.count).joined(separator: "/")
|
||
: ""
|
||
var historyKey: String?
|
||
if historyFile != nil {
|
||
let key = HistoryKey(destinations: destRoots, folderPattern: settings.folderPattern,
|
||
preserveStructure: settings.preserveStructure, sourceFolder: relative,
|
||
renamePattern: settings.renameEnabled ? settings.renamePattern : nil,
|
||
files: try files.map(sourceFingerprint).sorted())
|
||
let encoded = try keyEncoder.encode(key)
|
||
historyKey = Data(SHA256.hash(data: encoded)).base64EncodedString()
|
||
if let historyKey, let group = history[historyKey],
|
||
reusable(group, files: files, requireAll: true) {
|
||
skipped += 1
|
||
continue
|
||
}
|
||
}
|
||
entries.append((item, relative, locked, files, historyKey))
|
||
}
|
||
}
|
||
progress(IngestProgress(done: 0, total: entries.count, currentFile: "Lese Aufnahmezeiten …"))
|
||
|
||
// 2. capture dates (for folder/rename variables and the order of {seqn})
|
||
for chunkStart in stride(from: 0, to: entries.count, by: 200) {
|
||
try Task.checkCancellation()
|
||
let range = chunkStart..<min(chunkStart + 200, entries.count)
|
||
let meta = try await exiftool.readMetadata(files: entries[range].map { $0.item.primary })
|
||
for i in range { entries[i].item.apply(fileMeta: meta[entries[i].item.primary.path] ?? [:], sidecarMeta: nil) }
|
||
}
|
||
entries.sort { ($0.item.captureDate ?? $0.item.modified, $0.item.filename) < ($1.item.captureDate ?? $1.item.modified, $1.item.filename) }
|
||
|
||
// 3. copy
|
||
var usedFolders = Set<URL>()
|
||
var copied: [URL] = []
|
||
var lockedCopies: [URL] = []
|
||
var seq = settings.startSequence
|
||
let total = entries.reduce(0) { $0 + $1.files.filter { $0.pathExtension.lowercased() != "xmp" }.count }
|
||
var done = 0
|
||
|
||
progress(IngestProgress(done: 0, total: total, currentFile: "Starte …"))
|
||
defer {
|
||
if historyChanged, let historyFile { try? saveHistory(history, at: historyFile) }
|
||
if settings.sequenceEnabled { onSequence?(seq) }
|
||
}
|
||
for entry in entries {
|
||
try Task.checkCancellation()
|
||
let item = entry.item
|
||
let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif,
|
||
sequence: settings.sequenceEnabled ? seq : nil, iptc: item.iptc)
|
||
let sub = VariableExpander.expand(settings.folderPattern, context: ctx)
|
||
.replacingOccurrences(of: ":", with: "-")
|
||
.trimmingCharacters(in: .whitespaces)
|
||
let baseName = settings.renameEnabled && !settings.renamePattern.isEmpty
|
||
? VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-")
|
||
: item.baseName
|
||
let folders = destRoots.map { root in
|
||
var folder = root
|
||
if !sub.isEmpty { folder.appendPathComponent(sub, isDirectory: true) }
|
||
if !entry.relativeFolder.isEmpty { folder.appendPathComponent(entry.relativeFolder, isDirectory: true) }
|
||
return folder
|
||
}
|
||
|
||
// Reuse the recorded name when restoring a missing copy, including a sequence-based name.
|
||
let previous = entry.historyKey.flatMap { history[$0] }
|
||
let targets = previous?.folders ?? folders
|
||
let canRestore = previous.map { reusable($0, files: entry.files, requireAll: false) } ?? false
|
||
let name: String
|
||
if let previous, canRestore {
|
||
name = previous.name
|
||
} else {
|
||
name = uniqueName(previous?.name ?? baseName, files: entry.files, in: targets,
|
||
skipDuplicates: settings.skipDuplicates).name
|
||
}
|
||
var newCopies: [URL] = []
|
||
var newPrimary: URL?
|
||
do {
|
||
for (folderIndex, folder) in targets.enumerated() {
|
||
try fm.createDirectory(at: folder, withIntermediateDirectories: true)
|
||
if folderIndex == 0, usedFolders.insert(folder).inserted { onFolder?(folder) }
|
||
for (fileIndex, src) in entry.files.enumerated() {
|
||
try Task.checkCancellation()
|
||
let dest = destination(for: src, name: name, in: folder)
|
||
if fm.fileExists(atPath: dest.path) {
|
||
if !(canRestore && folderIndex == 0) && !fm.contentsEqual(atPath: src.path, andPath: dest.path) {
|
||
throw UploadError.failed("Die Zieldatei wurde zwischenzeitlich geändert: \(dest.path)")
|
||
}
|
||
guard (try dest.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true else {
|
||
throw UploadError.failed("Die Zieldatei ist keine reguläre Datei: \(dest.path)")
|
||
}
|
||
} else {
|
||
try copy(src, to: dest)
|
||
newCopies.append(dest)
|
||
if folderIndex == 0 && fileIndex == 0 { newPrimary = dest }
|
||
}
|
||
if folderIndex == 0 && src.pathExtension.lowercased() != "xmp" {
|
||
done += 1
|
||
progress(IngestProgress(done: done, total: total, currentFile: src.lastPathComponent))
|
||
}
|
||
}
|
||
}
|
||
} catch {
|
||
// A group can be retried with its original name after a failure.
|
||
for file in newCopies.reversed() { try? fm.removeItem(at: file) }
|
||
throw error
|
||
}
|
||
if let newPrimary {
|
||
copied.append(newPrimary)
|
||
if entry.locked { lockedCopies.append(newPrimary) }
|
||
}
|
||
if settings.sequenceEnabled && previous == nil { seq += 1 }
|
||
if newCopies.isEmpty { skipped += 1 }
|
||
if let key = entry.historyKey {
|
||
history[key] = ImportedGroup(folders: targets, name: name)
|
||
historyChanged = true
|
||
}
|
||
}
|
||
if historyChanged, let historyFile {
|
||
try saveHistory(history, at: historyFile)
|
||
historyChanged = false
|
||
}
|
||
return IngestResult(folders: Array(usedFolders).sorted { $0.path < $1.path }, copied: copied,
|
||
lockedCopies: lockedCopies, nextSequence: seq, skipped: skipped)
|
||
}
|
||
|
||
/// Ejects a memory card via `diskutil eject` (more reliable than NSWorkspace, reports who blocks it).
|
||
/// Retries a few times – right after an ingest Spotlight (mds) or QuickLook often still hold the card.
|
||
/// Returns nil on success, otherwise the error text.
|
||
public static func eject(volume: URL, attempts: Int = 4) async -> String? {
|
||
var last = ""
|
||
for attempt in 0..<attempts {
|
||
if attempt > 0 { try? await Task.sleep(nanoseconds: 2_000_000_000) }
|
||
if let r = try? await FTPUploader.run("/usr/sbin/diskutil", ["eject", volume.path], stdin: nil) {
|
||
if r.status == 0 { return nil }
|
||
last = (r.stderr + r.stdout).trimmingCharacters(in: .whitespacesAndNewlines)
|
||
}
|
||
if !FileManager.default.fileExists(atPath: volume.path) { return nil } // already gone
|
||
}
|
||
return last.isEmpty ? "diskutil eject fehlgeschlagen" : last
|
||
}
|
||
|
||
/// A shared name across destinations that either has no collision or can resume a partial copy.
|
||
static func uniqueName(_ base: String, files: [URL], in folder: URL, skipDuplicates: Bool) -> (name: String, skip: Bool) {
|
||
uniqueName(base, files: files, in: [folder], skipDuplicates: skipDuplicates)
|
||
}
|
||
|
||
private static func uniqueName(_ base: String, files: [URL], in folders: [URL], skipDuplicates: Bool) -> (name: String, skip: Bool) {
|
||
let fm = FileManager.default
|
||
var suffix = 0
|
||
while true {
|
||
let name = suffix == 0 ? base : "\(base)-\(suffix)"
|
||
var missing = false
|
||
var conflict = false
|
||
for folder in folders {
|
||
for src in files {
|
||
let dest = destination(for: src, name: name, in: folder)
|
||
if !fm.fileExists(atPath: dest.path) {
|
||
missing = true
|
||
} else if !skipDuplicates || !fm.contentsEqual(atPath: src.path, andPath: dest.path) {
|
||
conflict = true
|
||
break
|
||
}
|
||
}
|
||
if conflict { break }
|
||
}
|
||
if !conflict { return (name, !missing) }
|
||
suffix += 1
|
||
}
|
||
}
|
||
|
||
private static func reusable(_ group: ImportedGroup, files: [URL], requireAll: Bool) -> Bool {
|
||
let fm = FileManager.default
|
||
return group.folders.enumerated().allSatisfy { index, folder in
|
||
files.allSatisfy { source in
|
||
let dest = destination(for: source, name: group.name, in: folder)
|
||
guard fm.fileExists(atPath: dest.path) else { return !requireAll }
|
||
guard (try? dest.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { return false }
|
||
// IPTC changes can legitimately modify the main copy after ingest.
|
||
return index == 0 || fm.contentsEqual(atPath: source.path, andPath: dest.path)
|
||
}
|
||
}
|
||
}
|
||
|
||
private static func destination(for source: URL, name: String, in folder: URL) -> URL {
|
||
folder.appendingPathComponent(name).appendingPathExtension(source.pathExtension)
|
||
}
|
||
}
|