Kartenimport, Metadaten und Versand absichern
This commit is contained in:
1 parent
be6bd49da5
commit
427b6fa7b0
18 files changed
+643
-193
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
/// PM Ingest "Filter Files": in-camera protected (locked) photos.
|
||||
@@ -110,24 +111,43 @@ public enum IngestService {
|
||||
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")
|
||||
return d.appendingPathComponent("ingest-history-v2.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)"
|
||||
private struct HistoryKey: Codable {
|
||||
let destinations: [URL]
|
||||
let folderPattern: String
|
||||
let preserveStructure: Bool
|
||||
let sourceFolder: String
|
||||
let renamePattern: String?
|
||||
let files: [String]
|
||||
}
|
||||
|
||||
static func loadHistory() -> Set<String> {
|
||||
guard let d = try? Data(contentsOf: historyURL), let s = try? JSONDecoder().decode(Set<String>.self, from: d) else { return [] }
|
||||
return s
|
||||
private struct ImportedGroup: Codable {
|
||||
let folders: [URL]
|
||||
let name: String
|
||||
}
|
||||
|
||||
static func saveHistory(_ s: Set<String>) {
|
||||
if let d = try? JSONEncoder().encode(s) { try? d.write(to: historyURL, options: .atomic) }
|
||||
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).
|
||||
@@ -144,31 +164,73 @@ public enum IngestService {
|
||||
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.") }
|
||||
|
||||
// 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)))
|
||||
}
|
||||
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.")
|
||||
}
|
||||
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() : []
|
||||
|
||||
// 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
|
||||
if settings.incremental {
|
||||
let before = entries.count
|
||||
entries = entries.filter { !history.contains(historyKey($0.item.primary)) }
|
||||
skipped = before - entries.count
|
||||
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 …"))
|
||||
|
||||
@@ -186,90 +248,89 @@ public enum IngestService {
|
||||
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
|
||||
}
|
||||
let total = entries.reduce(0) { $0 + $1.files.filter { $0.pathExtension.lowercased() != "xmp" }.count }
|
||||
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
|
||||
// also after a cancel/error the next number is handed back, so the next ingest continues there
|
||||
defer {
|
||||
if settings.incremental { saveHistory(history) }
|
||||
if historyChanged, let historyFile { try? saveHistory(history, at: historyFile) }
|
||||
if settings.sequenceEnabled { onSequence?(seq) }
|
||||
}
|
||||
for e in entries {
|
||||
for entry 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 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)
|
||||
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)
|
||||
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 !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 !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 src.pathExtension.lowercased() != "xmp" {
|
||||
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 settings.incremental { history.insert(historyKey(item.primary)) }
|
||||
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)
|
||||
@@ -291,27 +352,49 @@ public enum IngestService {
|
||||
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.
|
||||
/// 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) {
|
||||
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)
|
||||
uniqueName(base, files: files, in: [folder], skipDuplicates: skipDuplicates)
|
||||
}
|
||||
|
||||
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
|
||||
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
|
||||
}
|
||||
let sa = size(a)
|
||||
return sa != nil && sa == size(b)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user