feature: sent-PDF history (10) + image retention (30) with pruning per Ben's 2026-09-02 ruling
This commit is contained in:
@@ -0,0 +1,446 @@
|
||||
import Foundation
|
||||
|
||||
/// Retention ruling (2026-09-02). Ben's instruction is the authority that
|
||||
/// supersedes the earlier D-11 never-delete rule FOR THIS STORE only:
|
||||
///
|
||||
/// "the last 10 files are saved, and the past 30 images, and cleared up
|
||||
/// afterwards. user should be able to select from those and send again."
|
||||
///
|
||||
/// App-managed copies live under `AppSupportPaths.root/history/`. Pruning
|
||||
/// unlinks files under `history/pdfs/` and archived capture PNGs beyond the
|
||||
/// newest 30. It never deletes a user file, never touches the outbox PDF, and
|
||||
/// never touches the open spool session (D-11 still applies there).
|
||||
|
||||
/// One sent-PDF copy retained for re-send. The file at `fileURL` is the
|
||||
/// app-managed copy under `history/pdfs/`, not the user's original.
|
||||
public struct HistoryEntry: Codable, Sendable, Equatable, Identifiable {
|
||||
public let id: UUID
|
||||
public let fileName: String
|
||||
public let fileURL: URL
|
||||
public let originalFileName: String
|
||||
public let sessionID: UUID?
|
||||
public let pageCount: Int
|
||||
public let sentAt: Date
|
||||
|
||||
public init(
|
||||
id: UUID,
|
||||
fileName: String,
|
||||
fileURL: URL,
|
||||
originalFileName: String,
|
||||
sessionID: UUID?,
|
||||
pageCount: Int,
|
||||
sentAt: Date
|
||||
) {
|
||||
self.id = id
|
||||
self.fileName = fileName
|
||||
self.fileURL = fileURL
|
||||
self.originalFileName = originalFileName
|
||||
self.sessionID = sessionID
|
||||
self.pageCount = pageCount
|
||||
self.sentAt = sentAt
|
||||
}
|
||||
}
|
||||
|
||||
/// A capture PNG on disk under an archived session, listed for re-send.
|
||||
/// `path` is the real file; HistoryStore never copies images.
|
||||
public struct ImageRef: Sendable, Equatable {
|
||||
public let path: URL
|
||||
public let capturedAt: Date
|
||||
public let sessionID: UUID
|
||||
|
||||
public init(path: URL, capturedAt: Date, sessionID: UUID) {
|
||||
self.path = path
|
||||
self.capturedAt = capturedAt
|
||||
self.sessionID = sessionID
|
||||
}
|
||||
}
|
||||
|
||||
public actor HistoryStore {
|
||||
public static let pdfRetentionCount = 10
|
||||
public static let imageRetentionCount = 30
|
||||
|
||||
private let paths: AppSupportPaths
|
||||
private let historyRoot: URL
|
||||
private let pdfsDirectory: URL
|
||||
private let manifestURL: URL
|
||||
private var entries: [HistoryEntry]
|
||||
|
||||
public init(paths: AppSupportPaths) throws {
|
||||
self.paths = paths
|
||||
self.historyRoot = paths.root.appendingPathComponent("history", isDirectory: true)
|
||||
self.pdfsDirectory = historyRoot.appendingPathComponent("pdfs", isDirectory: true)
|
||||
self.manifestURL = historyRoot.appendingPathComponent("history.json")
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: historyRoot, withIntermediateDirectories: true)
|
||||
try FileManager.default.createDirectory(at: pdfsDirectory, withIntermediateDirectories: true)
|
||||
} catch {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: historyRoot.path,
|
||||
underlying: error.localizedDescription
|
||||
)
|
||||
}
|
||||
self.entries = try Self.loadEntries(from: manifestURL, pdfsDirectory: pdfsDirectory)
|
||||
}
|
||||
|
||||
/// Copies `sourceURL` into `history/pdfs/` (never moves or writes the
|
||||
/// user's file), appends an entry, then keeps the 10 newest PDF copies.
|
||||
public func recordSentPDF(
|
||||
sourceURL: URL,
|
||||
sessionID: UUID?,
|
||||
pageCount: Int,
|
||||
sentAt: Date
|
||||
) throws -> HistoryEntry {
|
||||
let fm = FileManager.default
|
||||
guard fm.fileExists(atPath: sourceURL.path) else {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: sourceURL.path,
|
||||
underlying: "source PDF does not exist"
|
||||
)
|
||||
}
|
||||
let data: Data
|
||||
do {
|
||||
data = try Data(contentsOf: sourceURL)
|
||||
} catch {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: sourceURL.path,
|
||||
underlying: error.localizedDescription
|
||||
)
|
||||
}
|
||||
|
||||
let id = UUID()
|
||||
let fileName = "\(DubaiTime.fileStamp(sentAt))-\(id.uuidString.lowercased()).pdf"
|
||||
let destURL = pdfsDirectory.appendingPathComponent(fileName)
|
||||
try AtomicFile.write(data, to: destURL)
|
||||
|
||||
let entry = HistoryEntry(
|
||||
id: id,
|
||||
fileName: fileName,
|
||||
fileURL: destURL,
|
||||
originalFileName: sourceURL.lastPathComponent,
|
||||
sessionID: sessionID,
|
||||
pageCount: pageCount,
|
||||
sentAt: sentAt
|
||||
)
|
||||
entries.append(entry)
|
||||
try prunePDFEntries()
|
||||
return entry
|
||||
}
|
||||
|
||||
/// Newest first, at most `pdfRetentionCount`.
|
||||
public func listPDFs() -> [HistoryEntry] {
|
||||
Array(sortedPDFs().prefix(Self.pdfRetentionCount))
|
||||
}
|
||||
|
||||
/// The newest capture PNGs across `archive/` sessions (including
|
||||
/// `removed/`). Does not copy files and does not look at the open spool.
|
||||
public func listImages(limit: Int = 30) throws -> [ImageRef] {
|
||||
let images = try collectArchivedImages()
|
||||
return images.prefix(max(limit, 0)).map(\.ref)
|
||||
}
|
||||
|
||||
/// Across archived sessions only: keep the 30 newest PNGs total (including
|
||||
/// `removed/`); delete older PNGs, drop them from `session.json`, and
|
||||
/// remove a session directory left with zero PNGs. Never touches spool/.
|
||||
public func pruneImages() throws {
|
||||
let fm = FileManager.default
|
||||
let images = try collectArchivedImages()
|
||||
let keepCount = Self.imageRetentionCount
|
||||
let doomed = Array(images.dropFirst(keepCount))
|
||||
guard !doomed.isEmpty else { return }
|
||||
|
||||
var remainingBySession: [UUID: CaptureSession] = [:]
|
||||
var dirBySession: [UUID: URL] = [:]
|
||||
for item in images {
|
||||
remainingBySession[item.session.id] = item.session
|
||||
dirBySession[item.session.id] = item.sessionDir
|
||||
}
|
||||
|
||||
var droppedIDs: [UUID: Set<UUID>] = [:]
|
||||
for item in doomed {
|
||||
try deleteIfPrunableImage(item.ref.path)
|
||||
if let captureID = item.captureID {
|
||||
droppedIDs[item.session.id, default: []].insert(captureID)
|
||||
}
|
||||
}
|
||||
|
||||
for (sessionID, ids) in droppedIDs {
|
||||
guard var session = remainingBySession[sessionID] else { continue }
|
||||
for id in ids {
|
||||
session = session.removing(captureID: id)
|
||||
}
|
||||
remainingBySession[sessionID] = session
|
||||
}
|
||||
|
||||
let touchedIDs = Set(doomed.map(\.session.id))
|
||||
for sessionID in touchedIDs {
|
||||
guard let sessionDir = dirBySession[sessionID] else { continue }
|
||||
guard isUnderArchive(sessionDir), !isUnderSpool(sessionDir) else { continue }
|
||||
|
||||
if pngsRemaining(in: sessionDir).isEmpty {
|
||||
if fm.fileExists(atPath: sessionDir.path) {
|
||||
try fm.removeItem(at: sessionDir)
|
||||
Log.spool.warning("Pruned \(sessionDir.path, privacy: .public)")
|
||||
}
|
||||
try AtomicFile.fsyncDirectory(at: paths.archive)
|
||||
continue
|
||||
}
|
||||
|
||||
if let session = remainingBySession[sessionID], droppedIDs[sessionID] != nil {
|
||||
try AtomicFile.writeJSON(
|
||||
session,
|
||||
to: sessionDir.appendingPathComponent("session.json")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PDF retention
|
||||
|
||||
private func prunePDFEntries() throws {
|
||||
let sorted = sortedPDFs()
|
||||
let kept = Array(sorted.prefix(Self.pdfRetentionCount))
|
||||
let discarded = sorted.dropFirst(Self.pdfRetentionCount)
|
||||
for entry in discarded {
|
||||
let url = pdfsDirectory.appendingPathComponent(entry.fileName)
|
||||
try deleteIfAppManagedPDF(url)
|
||||
}
|
||||
entries = kept
|
||||
try persistEntries()
|
||||
}
|
||||
|
||||
private func sortedPDFs() -> [HistoryEntry] {
|
||||
entries.sorted { lhs, rhs in
|
||||
if lhs.sentAt != rhs.sentAt { return lhs.sentAt > rhs.sentAt }
|
||||
return lhs.id.uuidString > rhs.id.uuidString
|
||||
}
|
||||
}
|
||||
|
||||
private func persistEntries() throws {
|
||||
try AtomicFile.writeJSON(entries, to: manifestURL)
|
||||
}
|
||||
|
||||
private func deleteIfAppManagedPDF(_ url: URL) throws {
|
||||
guard isUnderPDFs(url) else { return }
|
||||
let fm = FileManager.default
|
||||
guard fm.fileExists(atPath: url.path) else { return }
|
||||
do {
|
||||
try fm.removeItem(at: url)
|
||||
} catch {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: url.path,
|
||||
underlying: error.localizedDescription
|
||||
)
|
||||
}
|
||||
Log.spool.warning("Pruned \(url.path, privacy: .public)")
|
||||
try AtomicFile.fsyncDirectory(at: pdfsDirectory)
|
||||
}
|
||||
|
||||
// MARK: - Archived images
|
||||
|
||||
private struct ArchivedImage {
|
||||
let ref: ImageRef
|
||||
let session: CaptureSession
|
||||
let sessionDir: URL
|
||||
let captureID: UUID?
|
||||
}
|
||||
|
||||
private func collectArchivedImages() throws -> [ArchivedImage] {
|
||||
let dirs = try archivedSessionDirectories()
|
||||
var collected: [ArchivedImage] = []
|
||||
for dir in dirs {
|
||||
let sessionID = UUID(uuidString: dir.lastPathComponent) ?? UUID()
|
||||
let session = (try? loadSession(at: dir, id: sessionID))
|
||||
?? CaptureSession(
|
||||
id: sessionID,
|
||||
createdAt: fileDate(dir) ?? Date(),
|
||||
state: .archived,
|
||||
captures: [],
|
||||
pdfFileName: nil
|
||||
)
|
||||
var referenced = Set<String>()
|
||||
for capture in session.captures {
|
||||
let url = dir.appendingPathComponent(capture.fileName)
|
||||
guard FileManager.default.fileExists(atPath: url.path) else { continue }
|
||||
referenced.insert(capture.fileName)
|
||||
collected.append(
|
||||
ArchivedImage(
|
||||
ref: ImageRef(path: url, capturedAt: capture.capturedAt, sessionID: session.id),
|
||||
session: session,
|
||||
sessionDir: dir,
|
||||
captureID: capture.id
|
||||
)
|
||||
)
|
||||
}
|
||||
let removedDir = dir.appendingPathComponent("removed", isDirectory: true)
|
||||
for url in pngFiles(in: dir) where !referenced.contains(url.lastPathComponent) {
|
||||
collected.append(
|
||||
ArchivedImage(
|
||||
ref: ImageRef(
|
||||
path: url,
|
||||
capturedAt: fileDate(url) ?? .distantPast,
|
||||
sessionID: session.id
|
||||
),
|
||||
session: session,
|
||||
sessionDir: dir,
|
||||
captureID: nil
|
||||
)
|
||||
)
|
||||
}
|
||||
for url in pngFiles(in: removedDir) {
|
||||
collected.append(
|
||||
ArchivedImage(
|
||||
ref: ImageRef(
|
||||
path: url,
|
||||
capturedAt: fileDate(url) ?? .distantPast,
|
||||
sessionID: session.id
|
||||
),
|
||||
session: session,
|
||||
sessionDir: dir,
|
||||
captureID: nil
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
return collected.sorted { lhs, rhs in
|
||||
if lhs.ref.capturedAt != rhs.ref.capturedAt {
|
||||
return lhs.ref.capturedAt > rhs.ref.capturedAt
|
||||
}
|
||||
return lhs.ref.path.path > rhs.ref.path.path
|
||||
}
|
||||
}
|
||||
|
||||
private func archivedSessionDirectories() throws -> [URL] {
|
||||
let fm = FileManager.default
|
||||
let entries: [URL]
|
||||
do {
|
||||
entries = try fm.contentsOfDirectory(
|
||||
at: paths.archive,
|
||||
includingPropertiesForKeys: [.isDirectoryKey],
|
||||
options: []
|
||||
)
|
||||
} catch {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: paths.archive.path,
|
||||
underlying: error.localizedDescription
|
||||
)
|
||||
}
|
||||
return entries.filter { url in
|
||||
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
|
||||
return isDirectory && UUID(uuidString: url.lastPathComponent) != nil
|
||||
}
|
||||
}
|
||||
|
||||
private func loadSession(at dir: URL, id: UUID) throws -> CaptureSession {
|
||||
let url = dir.appendingPathComponent("session.json")
|
||||
let data = try Data(contentsOf: url)
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .iso8601
|
||||
let session = try decoder.decode(CaptureSession.self, from: data)
|
||||
guard session.id == id else {
|
||||
throw ShotdeckError.manifestCorrupt(path: url.path)
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
private func pngFiles(in dir: URL) -> [URL] {
|
||||
let fm = FileManager.default
|
||||
guard fm.fileExists(atPath: dir.path) else { return [] }
|
||||
let entries = (try? fm.contentsOfDirectory(
|
||||
at: dir,
|
||||
includingPropertiesForKeys: [.isDirectoryKey],
|
||||
options: []
|
||||
)) ?? []
|
||||
return entries.filter { url in
|
||||
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
|
||||
return !isDirectory && url.pathExtension.lowercased() == "png"
|
||||
}
|
||||
}
|
||||
|
||||
private func pngsRemaining(in sessionDir: URL) -> [URL] {
|
||||
pngFiles(in: sessionDir)
|
||||
+ pngFiles(in: sessionDir.appendingPathComponent("removed", isDirectory: true))
|
||||
}
|
||||
|
||||
private func deleteIfPrunableImage(_ url: URL) throws {
|
||||
guard isUnderArchive(url), !isUnderSpool(url) else { return }
|
||||
let fm = FileManager.default
|
||||
guard fm.fileExists(atPath: url.path) else { return }
|
||||
do {
|
||||
try fm.removeItem(at: url)
|
||||
} catch {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: url.path,
|
||||
underlying: error.localizedDescription
|
||||
)
|
||||
}
|
||||
Log.spool.warning("Pruned \(url.path, privacy: .public)")
|
||||
try AtomicFile.fsyncDirectory(at: url.deletingLastPathComponent())
|
||||
}
|
||||
|
||||
private func fileDate(_ url: URL) -> Date? {
|
||||
let values = try? url.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
|
||||
return values?.creationDate ?? values?.contentModificationDate
|
||||
}
|
||||
|
||||
// MARK: - Path guards
|
||||
|
||||
private func isUnderPDFs(_ url: URL) -> Bool {
|
||||
isUnderDirectory(url, parent: pdfsDirectory)
|
||||
}
|
||||
|
||||
private func isUnderArchive(_ url: URL) -> Bool {
|
||||
isUnderDirectory(url, parent: paths.archive)
|
||||
}
|
||||
|
||||
private func isUnderSpool(_ url: URL) -> Bool {
|
||||
isUnderDirectory(url, parent: paths.spool)
|
||||
}
|
||||
|
||||
private func isUnderDirectory(_ url: URL, parent: URL) -> Bool {
|
||||
let parentPath = parent.standardizedFileURL.path
|
||||
let path = url.standardizedFileURL.path
|
||||
if path == parentPath { return true }
|
||||
let prefix = parentPath.hasSuffix("/") ? parentPath : parentPath + "/"
|
||||
return path.hasPrefix(prefix)
|
||||
}
|
||||
|
||||
// MARK: - Manifest load
|
||||
|
||||
private static func loadEntries(from url: URL, pdfsDirectory: URL) throws -> [HistoryEntry] {
|
||||
let fm = FileManager.default
|
||||
guard fm.fileExists(atPath: url.path) else { return [] }
|
||||
let data: Data
|
||||
do {
|
||||
data = try Data(contentsOf: url)
|
||||
} catch {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: url.path,
|
||||
underlying: error.localizedDescription
|
||||
)
|
||||
}
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .iso8601
|
||||
do {
|
||||
let decoded = try decoder.decode([HistoryEntry].self, from: data)
|
||||
return decoded.map { entry in
|
||||
HistoryEntry(
|
||||
id: entry.id,
|
||||
fileName: entry.fileName,
|
||||
fileURL: pdfsDirectory.appendingPathComponent(entry.fileName),
|
||||
originalFileName: entry.originalFileName,
|
||||
sessionID: entry.sessionID,
|
||||
pageCount: entry.pageCount,
|
||||
sentAt: entry.sentAt
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
let corruptURL = url.deletingLastPathComponent()
|
||||
.appendingPathComponent("history.json.corrupt-\(DubaiTime.fileStamp(Date()))")
|
||||
try? fm.moveItem(at: url, to: corruptURL)
|
||||
Log.spool.error(
|
||||
"history.json could not be decoded; moved to \(corruptURL.path, privacy: .public): \(error.localizedDescription, privacy: .public)"
|
||||
)
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user