SPB Git

Repository Public

AttachmentStore.swift 2.5 KB 48 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatConversations/Sources/AttachmentStore.swift3// Description: Content-addressed storage of message attachments inside the app's attachments directory.4import CryptoKit5import Foundation6import LocalChatCore78public struct AttachmentStore: Sendable {9    public let directory: URL1011    public init(directory: URL) {12        self.directory = directory13        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)14    }15    public init(paths: AppPaths) { self.init(directory: paths.attachments) }1617    /// Copies `data` under its SHA-256 name (identical files are stored once) and returns the attachment record.18    public func store(data: Data, fileName: String, mimeType: String, kind: Attachment.Kind, extractedText: String? = nil) throws -> Attachment {19        let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()20        let ext = (fileName as NSString).pathExtension.lowercased().filter { $0.isLetter || $0.isNumber }21        let stored = ext.isEmpty ? hash : "\(hash).\(ext)"22        let url = directory.appendingPathComponent(stored)23        if !FileManager.default.fileExists(atPath: url.path) {24            #if os(iOS)25            try data.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])26            #else27            try data.write(to: url, options: .atomic)28            #endif29        }30        return Attachment(kind: kind, fileName: fileName, mimeType: mimeType, byteCount: data.count, storedName: stored, extractedText: extractedText)31    }3233    public func url(for attachment: Attachment) -> URL { directory.appendingPathComponent((attachment.storedName as NSString).lastPathComponent) }34    public func data(for attachment: Attachment) -> Data? { try? Data(contentsOf: url(for: attachment)) }35    public func delete(_ attachment: Attachment) { try? FileManager.default.removeItem(at: url(for: attachment)) }3637    /// Deletes stored files no live message references. Returns how many files were removed.38    @discardableResult39    public func removeOrphans(referenced: Set<String>) -> Int {40        let files = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []41        var removed = 042        for name in files where !referenced.contains(name) && !name.hasPrefix(".") {43            if (try? FileManager.default.removeItem(at: directory.appendingPathComponent(name))) != nil { removed += 1 }44        }45        return removed46    }47}48
Files main
Menu

Theme