Round 2 of adversarial review confirmed defects 2,3,4,5,7 fixed and raised three new ones; all three are fixed here, plus the guard-message nit. NEW-1 (the FAIL driver): the OneDrive send path overwrote the truthful status from handleDidShareItems with its own success text, silently dropping an archive failure and any state-refresh problem. The seam now takes the caller's success summary and composes ONE truthful message: summary (the share itself did complete) + archive error if any + refresh problems if any. Both callers (AirDrop delegate, OneDrive) pass their summary; the OneDrive text is never clobbered. NEW-2: if the replacement open session could not be created after the archive rename (disk full), the store kept reporting the already-archived session as the open one. SpoolStore now has a truth guard (ensureOpenSession): the open session is verified to really exist on disk and be in state .open before any read/mutate; a stale one is replaced by a genuinely fresh session, or the call fails loudly. Never a lie. NEW-3: archivedSessions() read the folder tie-break dates AFTER reconciliation, so a healed same-second session could bump its own modification date and outrank a genuinely newer peer. The dates are now read BEFORE reconciling. Nit: the startNewSession guard now reports "A new session is already being started." when the refusal is about a concurrent session start, not a send. Also added REDLINE_SELFTEST_PHASE=sendtruth (mirroring the existing =onedrive escape hatch) so the SEND-TRUTH selftest can run without the picker chain's display-dependent REGION-PERSIST phase. Evidence: 136 swift tests pass (2 new: OneDrive summary survives archiving; stale open session never returned as current). REDLINE_SELFTEST_PHASE=sendtruth -> SEND-TRUTH PASS. REDLINE_SELFTEST_PHASE=onedrive -> ONEDRIVE-SELFTEST PASS against the real OneDrive sync root.
551 lines
27 KiB
Swift
551 lines
27 KiB
Swift
import Foundation
|
|
import ImageIO
|
|
import CoreGraphics
|
|
import Darwin
|
|
|
|
public actor SpoolStore {
|
|
/// How many archived sessions (past submissions) are kept on disk. Ben's
|
|
/// retention rule (2026-10-11): "by default, retain the past 10 sessions" —
|
|
/// older session folders are removed from `archive/` once this is exceeded.
|
|
/// Any PDF a pruned session produced is not touched: it lives in the outbox
|
|
/// (or the OneDrive folder) it was sent to.
|
|
public static let defaultRetainedSessionCount = 10
|
|
|
|
private let paths: AppSupportPaths
|
|
private var openSession: CaptureSession
|
|
|
|
public init(paths: AppSupportPaths) throws {
|
|
self.paths = paths
|
|
let fm = FileManager.default
|
|
try Self.supersedeSpoolArchiveOverlaps(paths: paths, fileManager: fm)
|
|
try Self.finishInterruptedArchives(paths: paths, fileManager: fm)
|
|
let remainingIDs = try Self.listUUIDDirectories(in: paths.spool, fileManager: fm)
|
|
if remainingIDs.isEmpty {
|
|
self.openSession = try Self.createFreshSession(paths: paths)
|
|
} else {
|
|
var candidates: [CaptureSession] = []
|
|
for id in remainingIDs {
|
|
let dir = paths.sessionDirectory(id)
|
|
candidates.append(
|
|
try Self.reconcileSessionDirectory(
|
|
at: dir, id: id, assumedStateIfRebuilt: .open, fileManager: fm))
|
|
}
|
|
self.openSession = Self.pickNewest(first: candidates[0], rest: Array(candidates.dropFirst()))
|
|
}
|
|
}
|
|
|
|
/// The session currently accepting captures. Cheap accessor — all reconciliation already
|
|
/// happened once, inside init. A truth guard: if the stored session is no longer really
|
|
/// open on disk (its directory was archived away and the replacement session could not
|
|
/// be created — e.g. disk full), a fresh session is minted, or the call fails loudly.
|
|
/// It never returns an already-archived session as the open one.
|
|
public func currentSession() throws -> CaptureSession {
|
|
try ensureOpenSession()
|
|
}
|
|
|
|
/// Mint-or-verify the open session: returns the session that is REALLY open on disk,
|
|
/// creating a fresh one when the stored one is stale (archived away mid-run). Throws
|
|
/// loudly when no new session can be created either — never substitutes a lie.
|
|
private func ensureOpenSession() throws -> CaptureSession {
|
|
let dir = paths.sessionDirectory(openSession.id)
|
|
if openSession.state == .open && FileManager.default.fileExists(atPath: dir.path) {
|
|
return openSession
|
|
}
|
|
let staleID = openSession.id.uuidString
|
|
Log.spool.error(
|
|
"The stored open session \(staleID, privacy: .public) is not really open on disk; starting a fresh one.")
|
|
let fresh = try Self.createFreshSession(paths: paths)
|
|
openSession = fresh
|
|
return fresh
|
|
}
|
|
|
|
/// Writes `pngData` to disk and fsyncs it BEFORE the manifest is touched, then updates and
|
|
/// durably writes the manifest. Order is non-negotiable: image durable -> manifest durable
|
|
/// -> return. Uses AtomicFile.write/writeJSON for both writes — never Data.write(to:).
|
|
public func append(
|
|
pngData: Data, pixelWidth: Int, pixelHeight: Int,
|
|
scale: CGFloat, capturedAt: Date
|
|
) throws -> Capture {
|
|
let open = try ensureOpenSession()
|
|
let captureID = UUID()
|
|
let sequence = open.nextSequence
|
|
let fileName = "\(String(format: "%03d", sequence))-\(Self.hexSuffix(captureID)).png"
|
|
let sessionDir = paths.sessionDirectory(open.id)
|
|
let fileURL = sessionDir.appendingPathComponent(fileName)
|
|
try AtomicFile.write(pngData, to: fileURL)
|
|
let capture = Capture(
|
|
id: captureID, sequence: sequence, fileName: fileName,
|
|
pixelWidth: pixelWidth, pixelHeight: pixelHeight,
|
|
scale: scale, capturedAt: capturedAt)
|
|
let updated = open.appending(capture)
|
|
try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json"))
|
|
openSession = updated
|
|
return capture
|
|
}
|
|
|
|
/// D-11: moves the capture's PNG into `<sessionDir>/removed/` (created lazily) and drops
|
|
/// its manifest entry. NEVER unlinks/deletes a user PNG on this path. Throws (no
|
|
/// filesystem change) if `captureID` is not present in the open session.
|
|
/// (Session retention is the one place that removes files: when a session falls
|
|
/// outside the newest `defaultRetainedSessionCount`, its WHOLE folder — including
|
|
/// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11),
|
|
/// not this remove path.)
|
|
public func remove(captureID: UUID) throws -> CaptureSession {
|
|
let open = try ensureOpenSession()
|
|
guard let capture = open.captures.first(where: { $0.id == captureID }) else {
|
|
throw ShotdeckError.spoolWriteFailed(
|
|
path: paths.sessionDirectory(open.id).path,
|
|
underlying: "capture \(captureID) is not in the open session")
|
|
}
|
|
let sessionDir = paths.sessionDirectory(open.id)
|
|
let removedDir = sessionDir.appendingPathComponent("removed", isDirectory: true)
|
|
do {
|
|
try FileManager.default.createDirectory(at: removedDir, withIntermediateDirectories: true)
|
|
} catch {
|
|
throw ShotdeckError.spoolWriteFailed(path: removedDir.path, underlying: error.localizedDescription)
|
|
}
|
|
let sourceURL = sessionDir.appendingPathComponent(capture.fileName)
|
|
let destURL = removedDir.appendingPathComponent(capture.fileName)
|
|
guard rename(sourceURL.path, destURL.path) == 0 else {
|
|
throw ShotdeckError.spoolWriteFailed(
|
|
path: destURL.path,
|
|
underlying: "could not move the capture into removed/: \(String(cString: strerror(errno)))")
|
|
}
|
|
try AtomicFile.fsyncDirectory(at: removedDir)
|
|
let updated = openSession.removing(captureID: captureID)
|
|
try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json"))
|
|
openSession = updated
|
|
return updated
|
|
}
|
|
|
|
/// Closes the open session (must be non-empty), moves its directory under archive/, records
|
|
/// pdfFileName, starts a fresh empty open session, and applies session retention.
|
|
/// Returns the archived one.
|
|
public func archiveCurrent(pdfFileName: String) throws -> CaptureSession {
|
|
let open = try ensureOpenSession()
|
|
guard !open.isEmpty else {
|
|
throw ShotdeckError.spoolWriteFailed(
|
|
path: paths.sessionDirectory(open.id).path,
|
|
underlying: "cannot archive an empty session")
|
|
}
|
|
let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName))
|
|
openSession = try Self.createFreshSession(paths: paths)
|
|
applyRetention()
|
|
return archived
|
|
}
|
|
|
|
/// Closes the open session — sent or not — and keeps its captures as a past
|
|
/// session under archive/, then starts a fresh empty open session. Unlike
|
|
/// `archiveCurrent(pdfFileName:)` this never requires a PDF: the archived session
|
|
/// keeps whatever pdfFileName it already has (nil when it was never sent, which
|
|
/// the Past submissions list shows as "Not sent"). An empty open session is
|
|
/// simply replaced — there is nothing to keep. Returns the archived session, or
|
|
/// nil when the open session was empty.
|
|
public func closeCurrentSession() throws -> CaptureSession? {
|
|
let open = try ensureOpenSession()
|
|
guard !open.isEmpty else {
|
|
openSession = try Self.createFreshSession(paths: paths)
|
|
return nil
|
|
}
|
|
let archived = try moveOpenSessionToArchive(
|
|
open.markArchived(pdfFileName: open.pdfFileName))
|
|
openSession = try Self.createFreshSession(paths: paths)
|
|
applyRetention()
|
|
return archived
|
|
}
|
|
|
|
/// Keeps the newest `limit` archived sessions and removes the rest of the session
|
|
/// folders from archive/ (the single folder all sessions live in). Returns the
|
|
/// removed ids. Only UUID session folders directly under archive/ are ever
|
|
/// touched — never spool/, never anything else. This is the requested retention
|
|
/// policy (Ben, 2026-10-11: "retain the past 10 sessions"): a session folder
|
|
/// dropped here is gone for good, while any PDF it produced stays in the
|
|
/// outbox/OneDrive folder it was sent to.
|
|
public func pruneArchivedSessions(keeping limit: Int) throws -> [UUID] {
|
|
let sessions = try archivedSessions()
|
|
guard sessions.count > limit else { return [] }
|
|
var removed: [UUID] = []
|
|
for session in sessions.dropFirst(limit) {
|
|
let dir = paths.archiveDirectory(session.id)
|
|
do {
|
|
try FileManager.default.removeItem(at: dir)
|
|
} catch {
|
|
throw ShotdeckError.spoolWriteFailed(
|
|
path: dir.path,
|
|
underlying: "could not remove an expired session: \(error.localizedDescription)")
|
|
}
|
|
removed.append(session.id)
|
|
}
|
|
try AtomicFile.fsyncDirectory(at: paths.archive)
|
|
return removed
|
|
}
|
|
|
|
/// The retention policy every archive path funnels through, so it can never be
|
|
/// forgotten: sessions over the default count are pruned. A retention failure is
|
|
/// logged loudly (with the exact path) and never thrown — the archive it follows
|
|
/// already succeeded, and converting a completed send into a reported failure
|
|
/// would be a lie (the safe direction of a failed prune is keeping too much, never
|
|
/// losing data). The visible symptom of a failed prune is simply more than 10
|
|
/// sessions in the Past submissions list.
|
|
private func applyRetention() {
|
|
do {
|
|
let removed = try pruneArchivedSessions(keeping: Self.defaultRetainedSessionCount)
|
|
if !removed.isEmpty {
|
|
Log.spool.warning(
|
|
"Session retention: removed \(removed.count, privacy: .public) archived session(s) beyond the newest \(Self.defaultRetainedSessionCount, privacy: .public).")
|
|
}
|
|
} catch {
|
|
Log.spool.error(
|
|
"Session retention failed — past sessions were kept beyond \(Self.defaultRetainedSessionCount, privacy: .public): \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)")
|
|
}
|
|
}
|
|
|
|
/// Writes the archived manifest, then renames the whole session directory from
|
|
/// spool/ into archive/ in one atomic operation.
|
|
private func moveOpenSessionToArchive(_ archived: CaptureSession) throws -> CaptureSession {
|
|
let sessionDir = paths.sessionDirectory(archived.id)
|
|
try AtomicFile.writeJSON(archived, to: sessionDir.appendingPathComponent("session.json"))
|
|
let archiveDir = paths.archiveDirectory(archived.id)
|
|
guard rename(sessionDir.path, archiveDir.path) == 0 else {
|
|
throw ShotdeckError.spoolWriteFailed(
|
|
path: sessionDir.path,
|
|
underlying: "could not move the session into archive/: \(String(cString: strerror(errno)))")
|
|
}
|
|
try AtomicFile.fsyncDirectory(at: paths.archive)
|
|
return archived
|
|
}
|
|
|
|
/// Abandons the open session only if it is empty (mints a new id/dir/manifest); throws,
|
|
/// with no filesystem change, if the open session has captures.
|
|
public func startNewSession() throws -> CaptureSession {
|
|
let open = try ensureOpenSession()
|
|
guard open.isEmpty else {
|
|
throw ShotdeckError.spoolWriteFailed(
|
|
path: paths.sessionDirectory(open.id).path,
|
|
underlying: "cannot start a new session: \(open.captures.count) capture(s) present in the open session")
|
|
}
|
|
let fresh = try Self.createFreshSession(paths: paths)
|
|
openSession = fresh
|
|
return fresh
|
|
}
|
|
|
|
/// Absolute URL of a capture's PNG, in whichever top-level directory its session lives
|
|
/// (spool/ if session.state == .open, archive/ if .archived).
|
|
public func imageURL(for capture: Capture, in session: CaptureSession) -> URL {
|
|
let dir = session.state == .open ? paths.sessionDirectory(session.id) : paths.archiveDirectory(session.id)
|
|
return dir.appendingPathComponent(capture.fileName)
|
|
}
|
|
|
|
/// Archived sessions, newest first. Lazily reconciles each archive/ directory
|
|
/// the same way init reconciles spool/ candidates (orphan recovery, missing-drop, corrupt
|
|
/// rebuild) — an archived session's manifest can degrade too and must self-heal without
|
|
/// ever losing a PNG.
|
|
///
|
|
/// Order: manifest `createdAt` first (whole-second ISO8601 — the manifest format is
|
|
/// pinned in AtomicFileTests), then the session folder's creation date and content
|
|
/// modification date to break ties at real resolution (two sessions closed in the
|
|
/// same second would otherwise order, and therefore prune, arbitrarily by UUID —
|
|
/// and on a volume that reports no creation date the modification date still keeps
|
|
/// retention on real order), then the id as the final deterministic tie-break.
|
|
/// The folder dates are tie-break refinements only — the manifest `createdAt` stays
|
|
/// the authoritative timestamp; if a volume reports neither date the tie-break
|
|
/// degrades to the id.
|
|
public func archivedSessions() throws -> [CaptureSession] {
|
|
let ids = try Self.listUUIDDirectories(in: paths.archive, fileManager: .default)
|
|
var keyed: [(session: CaptureSession, folderCreatedAt: Date, folderModifiedAt: Date)] = []
|
|
for id in ids {
|
|
let dir = paths.archiveDirectory(id)
|
|
// Read the folder dates BEFORE reconciling: reconciliation can rewrite
|
|
// session.json and bump the folder's modification date to "now", which
|
|
// would let a healed older session outrank a genuinely newer same-second
|
|
// peer in the tie-break below.
|
|
let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
|
|
let session = try Self.reconcileSessionDirectory(
|
|
at: dir, id: id, assumedStateIfRebuilt: .archived, fileManager: .default)
|
|
// The manifest `createdAt` is the authoritative timestamp; the folder dates
|
|
// only refine ties between same-second sessions.
|
|
let folderCreatedAt = values?.creationDate ?? session.createdAt
|
|
let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt
|
|
keyed.append((session, folderCreatedAt, folderModifiedAt))
|
|
}
|
|
return keyed
|
|
.sorted { lhs, rhs in
|
|
(lhs.session.createdAt, lhs.folderCreatedAt, lhs.folderModifiedAt, lhs.session.id.uuidString)
|
|
> (rhs.session.createdAt, rhs.folderCreatedAt, rhs.folderModifiedAt, rhs.session.id.uuidString)
|
|
}
|
|
.map(\.session)
|
|
}
|
|
|
|
// MARK: - Reconciliation (static so they can run inside init)
|
|
|
|
private static func listUUIDDirectories(in parent: URL, fileManager: FileManager) throws -> [UUID] {
|
|
let entries: [URL]
|
|
do {
|
|
entries = try fileManager.contentsOfDirectory(
|
|
at: parent,
|
|
includingPropertiesForKeys: [.isDirectoryKey],
|
|
options: [])
|
|
} catch {
|
|
throw ShotdeckError.spoolWriteFailed(path: parent.path, underlying: error.localizedDescription)
|
|
}
|
|
var ids: [UUID] = []
|
|
for url in entries {
|
|
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
|
|
guard isDirectory else { continue }
|
|
if let id = UUID(uuidString: url.lastPathComponent) {
|
|
ids.append(id)
|
|
}
|
|
}
|
|
return ids
|
|
}
|
|
|
|
private static func supersedeSpoolArchiveOverlaps(paths: AppSupportPaths, fileManager: FileManager) throws {
|
|
let spoolIDs = Set(try listUUIDDirectories(in: paths.spool, fileManager: fileManager))
|
|
let archiveIDs = Set(try listUUIDDirectories(in: paths.archive, fileManager: fileManager))
|
|
for id in spoolIDs.intersection(archiveIDs) {
|
|
let spoolDir = paths.sessionDirectory(id)
|
|
let supersededDir = paths.spool.appendingPathComponent(
|
|
"\(id.uuidString).superseded-\(DubaiTime.fileStamp(Date()))", isDirectory: true)
|
|
guard rename(spoolDir.path, supersededDir.path) == 0 else {
|
|
throw ShotdeckError.spoolWriteFailed(
|
|
path: spoolDir.path,
|
|
underlying: "could not supersede a duplicate spool copy: \(String(cString: strerror(errno)))")
|
|
}
|
|
try AtomicFile.fsyncDirectory(at: paths.spool)
|
|
Log.spool.warning("Found session \(id.uuidString, privacy: .public) in both spool/ and archive/; kept the archive copy and superseded the spool copy — nothing was deleted.")
|
|
}
|
|
}
|
|
|
|
private static func finishInterruptedArchives(paths: AppSupportPaths, fileManager: FileManager) throws {
|
|
for id in try listUUIDDirectories(in: paths.spool, fileManager: fileManager) {
|
|
let spoolDir = paths.sessionDirectory(id)
|
|
let manifestURL = spoolDir.appendingPathComponent("session.json")
|
|
guard let data = try? Data(contentsOf: manifestURL),
|
|
let decoded = try? decodeSession(from: data),
|
|
decoded.id == id, decoded.state == .archived
|
|
else { continue }
|
|
let archiveDir = paths.archiveDirectory(id)
|
|
guard rename(spoolDir.path, archiveDir.path) == 0 else {
|
|
throw ShotdeckError.spoolWriteFailed(
|
|
path: spoolDir.path,
|
|
underlying: "could not complete an interrupted archive move: \(String(cString: strerror(errno)))")
|
|
}
|
|
try AtomicFile.fsyncDirectory(at: paths.archive)
|
|
Log.spool.warning("Completed an archive move for \(id.uuidString, privacy: .public) that was interrupted before this launch.")
|
|
}
|
|
}
|
|
|
|
private static func reconcileSessionDirectory(
|
|
at dir: URL,
|
|
id: UUID,
|
|
assumedStateIfRebuilt: SessionState,
|
|
fileManager: FileManager
|
|
) throws -> CaptureSession {
|
|
let manifestURL = dir.appendingPathComponent("session.json")
|
|
let decoded: CaptureSession?
|
|
if let data = try? Data(contentsOf: manifestURL),
|
|
let session = try? decodeSession(from: data),
|
|
session.id == id {
|
|
decoded = session
|
|
} else {
|
|
decoded = nil
|
|
}
|
|
|
|
guard let session = decoded else {
|
|
return try rebuildManifest(
|
|
at: dir,
|
|
id: id,
|
|
assumedState: assumedStateIfRebuilt,
|
|
fileManager: fileManager)
|
|
}
|
|
|
|
var present: [Capture] = []
|
|
var missingCount = 0
|
|
for capture in session.captures {
|
|
let fileURL = dir.appendingPathComponent(capture.fileName)
|
|
if fileManager.fileExists(atPath: fileURL.path) {
|
|
present.append(capture)
|
|
} else {
|
|
missingCount += 1
|
|
}
|
|
}
|
|
let referenced = Set(session.captures.map(\.fileName))
|
|
let pngs = try listCapturePNGs(in: dir, fileManager: fileManager)
|
|
var recoveredOrphans: [Capture] = []
|
|
for pngURL in pngs where !referenced.contains(pngURL.lastPathComponent) {
|
|
if let recovered = recoverCapture(from: pngURL, fileManager: fileManager) {
|
|
recoveredOrphans.append(recovered)
|
|
} else {
|
|
Log.spool.error("Could not decode orphan PNG at \(pngURL.path, privacy: .public); leaving it on disk.")
|
|
}
|
|
}
|
|
let deletedTmp = deleteStrayTmpFiles(in: dir, fileManager: fileManager)
|
|
if missingCount == 0 && recoveredOrphans.isEmpty && !deletedTmp {
|
|
return session
|
|
}
|
|
let finalCaptures = (present + recoveredOrphans).sorted { $0.sequence < $1.sequence }
|
|
let updated = CaptureSession(
|
|
id: session.id,
|
|
createdAt: session.createdAt,
|
|
state: session.state,
|
|
captures: finalCaptures,
|
|
pdfFileName: session.pdfFileName)
|
|
try AtomicFile.writeJSON(updated, to: manifestURL)
|
|
Log.spool.warning("Reconciled session \(id.uuidString, privacy: .public): dropped \(missingCount) missing PNG(s), recovered \(recoveredOrphans.count) orphan(s).")
|
|
return updated
|
|
}
|
|
|
|
private static func rebuildManifest(
|
|
at dir: URL,
|
|
id: UUID,
|
|
assumedState: SessionState,
|
|
fileManager: FileManager
|
|
) throws -> CaptureSession {
|
|
let manifestURL = dir.appendingPathComponent("session.json")
|
|
if fileManager.fileExists(atPath: manifestURL.path) {
|
|
let corruptURL = dir.appendingPathComponent(
|
|
"session.json.corrupt-\(DubaiTime.fileStamp(Date()))")
|
|
do {
|
|
try fileManager.moveItem(at: manifestURL, to: corruptURL)
|
|
} catch {
|
|
throw ShotdeckError.spoolWriteFailed(
|
|
path: manifestURL.path,
|
|
underlying: "could not quarantine a corrupt manifest: \(error.localizedDescription)")
|
|
}
|
|
}
|
|
|
|
var recovered: [Capture] = []
|
|
for pngURL in try listCapturePNGs(in: dir, fileManager: fileManager) {
|
|
if let capture = recoverCapture(from: pngURL, fileManager: fileManager) {
|
|
recovered.append(capture)
|
|
} else {
|
|
Log.spool.error("Could not decode PNG at \(pngURL.path, privacy: .public) while rebuilding the manifest; leaving it on disk.")
|
|
}
|
|
}
|
|
_ = deleteStrayTmpFiles(in: dir, fileManager: fileManager)
|
|
recovered.sort { $0.sequence < $1.sequence }
|
|
|
|
let createdAt: Date
|
|
if let earliest = recovered.map(\.capturedAt).min() {
|
|
createdAt = earliest
|
|
} else {
|
|
createdAt = (try? dir.resourceValues(forKeys: [.creationDateKey]))?.creationDate ?? Date()
|
|
}
|
|
|
|
let rebuilt = CaptureSession(
|
|
id: id,
|
|
createdAt: createdAt,
|
|
state: assumedState,
|
|
captures: recovered,
|
|
pdfFileName: nil)
|
|
try AtomicFile.writeJSON(rebuilt, to: dir.appendingPathComponent("session.json"))
|
|
Log.spool.warning("Rebuilt manifest for \(id.uuidString, privacy: .public) from \(recovered.count) recovered PNG(s).")
|
|
if assumedState == .archived {
|
|
Log.spool.warning("Rebuilt an archived session \(id.uuidString, privacy: .public) from PNGs; pdfFileName could not be recovered.")
|
|
}
|
|
return rebuilt
|
|
}
|
|
|
|
private static func recoverCapture(from fileURL: URL, fileManager: FileManager) -> Capture? {
|
|
guard fileManager.fileExists(atPath: fileURL.path) else { return nil }
|
|
guard let source = CGImageSourceCreateWithURL(fileURL as CFURL, nil),
|
|
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as NSDictionary?,
|
|
let width = (properties[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue,
|
|
let height = (properties[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue
|
|
else { return nil }
|
|
let name = fileURL.lastPathComponent
|
|
let sequence = Int(name.prefix(3)) ?? 1
|
|
let capturedAt = (try? fileURL.resourceValues(forKeys: [.creationDateKey]))?.creationDate ?? Date()
|
|
return Capture(
|
|
id: UUID(),
|
|
sequence: sequence,
|
|
fileName: name,
|
|
pixelWidth: width,
|
|
pixelHeight: height,
|
|
scale: 1.0,
|
|
capturedAt: capturedAt)
|
|
}
|
|
|
|
private static func pickNewest(first: CaptureSession, rest: [CaptureSession]) -> CaptureSession {
|
|
rest.reduce(first) { current, candidate in
|
|
let currentKey = (current.createdAt, current.id.uuidString)
|
|
let candidateKey = (candidate.createdAt, candidate.id.uuidString)
|
|
return candidateKey > currentKey ? candidate : current
|
|
}
|
|
}
|
|
|
|
private static func createFreshSession(paths: AppSupportPaths) throws -> CaptureSession {
|
|
let id = UUID()
|
|
let createdAt = Date()
|
|
let dir = paths.sessionDirectory(id)
|
|
do {
|
|
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
|
} catch {
|
|
throw ShotdeckError.spoolWriteFailed(path: dir.path, underlying: error.localizedDescription)
|
|
}
|
|
let session = CaptureSession(id: id, createdAt: createdAt, state: .open, captures: [], pdfFileName: nil)
|
|
try AtomicFile.writeJSON(session, to: dir.appendingPathComponent("session.json"))
|
|
return session
|
|
}
|
|
|
|
private static func hexSuffix(_ id: UUID) -> String {
|
|
String(id.uuidString.replacingOccurrences(of: "-", with: "").prefix(8)).uppercased()
|
|
}
|
|
|
|
private static func decodeSession(from data: Data) throws -> CaptureSession {
|
|
let decoder = JSONDecoder()
|
|
decoder.dateDecodingStrategy = .iso8601
|
|
return try decoder.decode(CaptureSession.self, from: data)
|
|
}
|
|
|
|
private static func isCapturePNGName(_ name: String) -> Bool {
|
|
guard name.hasSuffix(".png") else { return false }
|
|
let stem = String(name.dropLast(4))
|
|
let parts = stem.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false)
|
|
guard parts.count == 2,
|
|
parts[0].count == 3,
|
|
parts[0].allSatisfy(\.isNumber),
|
|
parts[1].count == 8,
|
|
parts[1].allSatisfy(\.isHexDigit)
|
|
else { return false }
|
|
return true
|
|
}
|
|
|
|
private static func listCapturePNGs(in dir: URL, fileManager: FileManager) throws -> [URL] {
|
|
let entries: [URL]
|
|
do {
|
|
entries = try fileManager.contentsOfDirectory(
|
|
at: dir,
|
|
includingPropertiesForKeys: [.isDirectoryKey],
|
|
options: [])
|
|
} catch {
|
|
throw ShotdeckError.spoolWriteFailed(path: dir.path, underlying: error.localizedDescription)
|
|
}
|
|
return entries.filter { url in
|
|
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
|
|
guard !isDirectory else { return false }
|
|
return isCapturePNGName(url.lastPathComponent)
|
|
}
|
|
}
|
|
|
|
private static func deleteStrayTmpFiles(in dir: URL, fileManager: FileManager) -> Bool {
|
|
let entries = (try? fileManager.contentsOfDirectory(
|
|
at: dir,
|
|
includingPropertiesForKeys: [.isDirectoryKey],
|
|
options: [])) ?? []
|
|
var deleted = false
|
|
for url in entries {
|
|
guard url.lastPathComponent.hasSuffix(".tmp") else { continue }
|
|
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
|
|
guard !isDirectory else { continue }
|
|
do {
|
|
try fileManager.removeItem(at: url)
|
|
deleted = true
|
|
} catch {
|
|
Log.spool.error("Could not remove stray temp file at \(url.path, privacy: .public): \(error.localizedDescription, privacy: .public)")
|
|
}
|
|
}
|
|
return deleted
|
|
}
|
|
}
|