SPB Git

Repository Public

AttachmentCache.swift 6.5 KB 118 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Attachments/AttachmentCache.swift4//  Description: Downloads attachment bytes once and keeps them in a protected on-disk cache (images in chat, Quick Look, offline).5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Foundation11import ImageIO12import UIKit13import UniformTypeIdentifiers1415actor AttachmentCache {16    private let api: ChatAPI17    private let directory: URL?18    private var inFlight: [String: Task<Data, Error>] = [:]19    private let thumbnails = NSCache<NSString, UIImage>()20    private static let maxBytes = 300 * 1024 * 10242122    init(api: ChatAPI, directory: URL?) {23        self.api = api24        self.directory = directory25        thumbnails.countLimit = 12026        if let directory {27            try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.protectionKey: FileProtectionType.completeUnlessOpen])28        }29    }3031    private func path(_ id: String) -> URL? {32        guard id.range(of: #"^[A-Za-z0-9_-]{1,80}$"#, options: .regularExpression) != nil else { return nil }33        return directory?.appendingPathComponent(id)34    }3536    /// Bytes of an attachment: disk cache first, then the server. Concurrent requests for the same file share one download.37    func data(for id: String) async throws -> Data {38        if let p = path(id), let d = try? Data(contentsOf: p) { return d }39        if let t = inFlight[id] { return try await t.value }40        let api = api41        let task = Task { try await api.attachmentData(id) }42        inFlight[id] = task43        defer { inFlight[id] = nil }44        let d = try await task.value45        if let p = path(id) { try? d.write(to: p, options: [.atomic, .completeFileProtectionUnlessOpen]); trimIfNeeded() }46        return d47    }4849    /// A decoded, downsampled image (never the full-resolution bitmap: a 12 MP photo would cost ~48 MB of memory).50    func thumbnail(for id: String, maxPixel: CGFloat) async -> UIImage? {51        let key = "\(id)-\(Int(maxPixel))" as NSString52        if let img = thumbnails.object(forKey: key) { return img }53        guard let d = try? await data(for: id), let img = ImageTools.downsample(d, maxPixel: maxPixel) else { return nil }54        thumbnails.setObject(img, forKey: key)55        return img56    }5758    /// A file URL with the right extension for Quick Look and the share sheet (temporary directory, removed by `wipe`).59    func fileURL(for id: String, filename: String) async throws -> URL {60        let d = try await data(for: id)61        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spchat-preview/\(id)", isDirectory: true)62        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)63        let safe = filename.replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "..", with: "_")64        let url = dir.appendingPathComponent(safe.isEmpty ? "fichier" : safe)65        try d.write(to: url, options: [.atomic, .completeFileProtectionUnlessOpen])66        return url67    }6869    private func trimIfNeeded() {70        guard let directory, let items = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.fileSizeKey, .contentAccessDateKey]) else { return }71        var entries = items.compactMap { u -> (URL, Int, Date)? in72            guard let v = try? u.resourceValues(forKeys: [.fileSizeKey, .contentAccessDateKey]) else { return nil }73            return (u, v.fileSize ?? 0, v.contentAccessDate ?? .distantPast)74        }75        var total = entries.reduce(0) { $0 + $1.1 }76        guard total > Self.maxBytes else { return }77        entries.sort { $0.2 < $1.2 }78        for e in entries where total > Self.maxBytes * 3 / 4 { try? FileManager.default.removeItem(at: e.0); total -= e.1 }79    }8081    func wipe() {82        thumbnails.removeAllObjects()83        if let directory { try? FileManager.default.removeItem(at: directory); try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.protectionKey: FileProtectionType.completeUnlessOpen]) }84        try? FileManager.default.removeItem(at: FileManager.default.temporaryDirectory.appendingPathComponent("spchat-preview", isDirectory: true))85    }86}8788enum ImageTools {89    /// Decodes directly at the target size with ImageIO (EXIF orientation applied).90    static func downsample(_ data: Data, maxPixel: CGFloat) -> UIImage? {91        let options: [CFString: Any] = [kCGImageSourceShouldCache: false]92        guard let src = CGImageSourceCreateWithData(data as CFData, options as CFDictionary) else { return nil }93        let thumb: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceShouldCacheImmediately: true, kCGImageSourceThumbnailMaxPixelSize: maxPixel]94        guard let cg = CGImageSourceCreateThumbnailAtIndex(src, 0, thumb as CFDictionary) else { return nil }95        return UIImage(cgImage: cg)96    }9798    /// Prepares a photo for upload: orientation applied, longest side ≤ 2048 px, JPEG. A 6–12 MB capture becomes a few99    /// hundred KB, and HEIC becomes a JPEG every provider can read. GIFs (animations) and small images are left untouched.100    static func prepareForUpload(_ data: Data, filename: String, mime: String, compress: Bool) -> (data: Data, filename: String, mime: String) {101        let isHEIC = mime.contains("hei") || filename.lowercased().hasSuffix(".heic") || filename.lowercased().hasSuffix(".heif")102        guard mime.hasPrefix("image/") || isHEIC, mime != "image/gif" else { return (data, filename, mime) }103        guard isHEIC || (compress && data.count > 1_200_000) else { return (data, filename, mime) }104        guard let img = downsample(data, maxPixel: 2048) else { return (data, filename, mime) }105        let format = UIGraphicsImageRendererFormat(); format.scale = 1; format.opaque = true106        let flattened = UIGraphicsImageRenderer(size: img.size, format: format).image { ctx in107            UIColor.white.setFill(); ctx.fill(CGRect(origin: .zero, size: img.size)); img.draw(at: .zero)108        }109        guard let jpeg = flattened.jpegData(compressionQuality: 0.85), isHEIC || jpeg.count < data.count else { return (data, filename, mime) }110        let base = (filename as NSString).deletingPathExtension111        return (jpeg, (base.isEmpty ? "photo" : base) + ".jpg", "image/jpeg")112    }113114    static func mime(forFilename name: String) -> String {115        UTType(filenameExtension: (name as NSString).pathExtension)?.preferredMIMEType ?? "application/octet-stream"116    }117}118
Files main
Menu

Theme