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(_ 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.json") } /// Incremental ingest key: original name + size + capture/mod date (survives card re-insert). static func historyKey(_ url: URL) -> String { let a = try? FileManager.default.attributesOfItem(atPath: url.path) let size = (a?[.size] as? NSNumber)?.int64Value ?? 0 let m = Int((a?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0) return "\(url.lastPathComponent)|\(size)|\(m)" } static func loadHistory() -> Set { guard let d = try? Data(contentsOf: historyURL), let s = try? JSONDecoder().decode(Set.self, from: d) else { return [] } return s } static func saveHistory(_ s: Set) { if let d = try? JSONEncoder().encode(s) { try? d.write(to: historyURL, 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, 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.") } // 1. scan + filters var entries: [(item: PhotoItem, root: URL, locked: Bool)] = [] for s in sources { let ro = volumeIsReadOnly(s) for item in try FolderScanner.scan(folder: s, recursive: true) { entries.append((item, s, isLocked(item.primary, volumeReadOnly: ro))) } } entries = entries.filter { e in switch settings.lockedFilter { case .all: break case .lockedOnly: if !e.locked { return false } case .unlockedOnly: if e.locked { return false } } return true } var history = settings.incremental ? loadHistory() : [] var skipped = 0 if settings.incremental { let before = entries.count entries = entries.filter { !history.contains(historyKey($0.item.primary)) } skipped = before - entries.count } 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..() var copied: [URL] = [] var lockedCopies: [URL] = [] var seq = settings.startSequence let total = entries.reduce(0) { total, e in let n = 1 + e.item.companions.count return total + n } var done = 0 let destRoots = [settings.primaryDestination] + (settings.secondaryEnabled && !settings.backupDestination.isEmpty ? [settings.backupDestination] : []) progress(IngestProgress(done: 0, total: total, currentFile: "Starte …")) // also after a cancel/error: what was copied is not copied again next time defer { if settings.incremental { saveHistory(history) } } for e in entries { try Task.checkCancellation() let item = e.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) var baseName = item.baseName if settings.renameEnabled, !settings.renamePattern.isEmpty { baseName = VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-") } // Card structure (DCIM/100NZ8_1) below the destination if requested let rel = settings.preserveStructure ? item.primary.deletingLastPathComponent().path.replacingOccurrences(of: e.root.path, with: "") .trimmingCharacters(in: CharacterSet(charactersIn: "/")) : "" var rawFiles = [item.primary] + item.companions switch settings.rawFilter { case .all: break case .rawOnly: rawFiles = rawFiles.filter { FileKind(url: $0).isRawLike } case .nonRawOnly: rawFiles = rawFiles.filter { !FileKind(url: $0).isRawLike } } guard !rawFiles.isEmpty else { continue } if settings.sequenceEnabled { seq += 1 } // only photos that are really copied get a number var files = rawFiles if item.kind.usesSidecar, fm.fileExists(atPath: item.sidecarURL.path), rawFiles.contains(item.primary) { files.append(item.sidecarURL) } // Name for this photo in every destination: an existing file is never deleted. Same name + same size // = already copied (skip); same name, other photo (second body, second card) → "-1", "-2" … var targetName = baseName var skipGroup = false if let primaryFolder = destRoots.first.map({ root -> URL in var f = URL(fileURLWithPath: root) if !sub.isEmpty { f.appendPathComponent(sub, isDirectory: true) } if !rel.isEmpty { f.appendPathComponent(rel, isDirectory: true) } return f }) { (targetName, skipGroup) = uniqueName(baseName, files: files, in: primaryFolder, skipDuplicates: settings.skipDuplicates) } for destRoot in destRoots { var folder = URL(fileURLWithPath: destRoot) if !sub.isEmpty { folder.appendPathComponent(sub, isDirectory: true) } if !rel.isEmpty { folder.appendPathComponent(rel, isDirectory: true) } try fm.createDirectory(at: folder, withIntermediateDirectories: true) let isPrimary = destRoot == settings.primaryDestination if isPrimary, usedFolders.insert(folder).inserted { onFolder?(folder) } for (n, src) in files.enumerated() { let dest = folder.appendingPathComponent(targetName).appendingPathExtension(src.pathExtension) if skipGroup || fm.fileExists(atPath: dest.path) { // already there (duplicate, or the backup already has it) – never overwrite if isPrimary, n == 0, src.pathExtension.lowercased() != "xmp" { done += 1 } continue } try copy(src, to: dest) if isPrimary { if n == 0 { copied.append(dest) if e.locked { lockedCopies.append(dest) } } if src.pathExtension.lowercased() != "xmp" { done += 1 progress(IngestProgress(done: done, total: total, currentFile: src.lastPathComponent)) } } } } if settings.incremental { history.insert(historyKey(item.primary)) } } 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.. 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 } /// Base name that collides with no other photo in `folder`. If the photo itself is already there /// (same name and size of its main file) and duplicates are skipped, `skip` is true. static func uniqueName(_ base: String, files: [URL], in folder: URL, skipDuplicates: Bool) -> (name: String, skip: Bool) { let fm = FileManager.default func dest(_ name: String, _ src: URL) -> URL { folder.appendingPathComponent(name).appendingPathExtension(src.pathExtension) } if let main = files.first, fm.fileExists(atPath: dest(base, main).path) { if skipDuplicates, sameSize(main, dest(base, main)) { return (base, true) } } else if !files.contains(where: { fm.fileExists(atPath: dest(base, $0).path) }) { return (base, false) } var n = 1 while files.contains(where: { fm.fileExists(atPath: dest("\(base)-\(n)", $0).path) }) { n += 1 } return ("\(base)-\(n)", false) } 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) } }