SPB Git

Repository Public

AttachmentService.swift 6.5 KB 110 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Attachments/AttachmentService.swift3// Description: Imports files (validation on real bytes, HEIC conversion, photo downscaling), uploads them, and serves cached attachment bytes and thumbnails.4import AppKit5import ImageIO6import UniformTypeIdentifiers7import SPChatCore89/// A file being added to the composer.10struct PendingAttachment: Identifiable, Equatable {11    enum State: Equatable { case uploading(Double), ready(Attachment), failed(String) }12    let id = UUID()13    var filename: String14    var mime: String15    var size: Int16    var state: State17    var attachment: Attachment? { if case .ready(let a) = state { return a }; return nil }18}1920final class AttachmentService {21    private let api: APIClient22    private let directory: URL23    private let images = NSCache<NSString, NSImage>()2425    init(api: APIClient, cacheDirectory: URL) {26        self.api = api; directory = cacheDirectory27        images.countLimit = 20028        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)29    }3031    /// Reads and checks a file chosen or dropped by the owner. Runs off the main actor (files can be tens of MB).32    nonisolated static func prepare(url: URL, maxUploadMb: Int, compressImages: Bool) async -> Result<UploadFile, FileValidator.Rejection> {33        let name = FileValidator.sanitizedName(url.lastPathComponent)34        let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } }35        guard let data = try? Data(contentsOf: url, options: .mappedIfSafe) else { return .failure(.unreadable(name)) }36        return prepare(data: Data(data), filename: name, maxUploadMb: maxUploadMb, compressImages: compressImages)37    }3839    nonisolated static func prepare(data: Data, filename: String, maxUploadMb: Int, compressImages: Bool) -> Result<UploadFile, FileValidator.Rejection> {40        let name = FileValidator.sanitizedName(filename)41        if data.isEmpty { return .failure(.empty(name)) }42        guard let mime = FileValidator.sniffMime(data, filename: name) else { return .failure(.unsupported(name)) }43        var out = UploadFile(filename: name, mime: mime, data: data)44        // HEIC is not accepted by the server, and large photos are reduced like the web client does (2048 px, JPEG)45        if mime == "image/heic" || (compressImages && ["image/jpeg", "image/png", "image/webp"].contains(mime) && data.count > 1_200_000) {46            if let jpeg = jpegData(from: data, maxSide: 2048, quality: 0.85), mime == "image/heic" || jpeg.count < data.count {47                out = UploadFile(filename: (name as NSString).deletingPathExtension + ".jpg", mime: "image/jpeg", data: jpeg)48            } else if mime == "image/heic" { return .failure(.unsupported(name)) }49        }50        if out.data.count > maxUploadMb * 1024 * 1024 { return .failure(.tooLarge(name, limitMb: maxUploadMb)) }51        return .success(out)52    }5354    /// Decodes with the EXIF orientation applied, scales and re-encodes as JPEG on a white background.55    nonisolated static func jpegData(from data: Data, maxSide: CGFloat, quality: CGFloat) -> Data? {56        guard let src = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }57        let opts: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: maxSide]58        guard let cg = CGImageSourceCreateThumbnailAtIndex(src, 0, opts as CFDictionary) else { return nil }59        guard let ctx = CGContext(data: nil, width: cg.width, height: cg.height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }60        ctx.setFillColor(.white); ctx.fill(CGRect(x: 0, y: 0, width: cg.width, height: cg.height)); ctx.draw(cg, in: CGRect(x: 0, y: 0, width: cg.width, height: cg.height))61        guard let flat = ctx.makeImage() else { return nil }62        let out = NSMutableData()63        guard let dest = CGImageDestinationCreateWithData(out, UTType.jpeg.identifier as CFString, 1, nil) else { return nil }64        CGImageDestinationAddImage(dest, flat, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)65        return CGImageDestinationFinalize(dest) ? out as Data : nil66    }6768    func upload(_ file: UploadFile, conversationId: String?, projectId: String? = nil, progress: @escaping @Sendable (Double) -> Void) async throws -> Attachment {69        guard let a = try await api.uploadAttachments([file], conversationId: conversationId, projectId: projectId, progress: progress).first else { throw APIError(.decoding, message: "Le serveur n'a renvoyé aucun fichier.") }70        return a71    }7273    // MARK: Cached bytes7475    private func cacheURL(_ id: String) -> URL { directory.appendingPathComponent(id.replacingOccurrences(of: "/", with: "_")) }7677    /// Bytes of an attachment, from the local cache when possible (works offline for files already seen).78    func data(for attachmentId: String) async throws -> Data {79        let url = cacheURL(attachmentId)80        if let d = try? Data(contentsOf: url) { return d }81        let file = try await api.attachmentData(attachmentId)82        try? file.data.write(to: url, options: .atomic)83        return file.data84    }8586    func image(for attachmentId: String) async -> NSImage? {87        if let hit = images.object(forKey: attachmentId as NSString) { return hit }88        guard let d = try? await data(for: attachmentId), let img = NSImage(data: d) else { return nil }89        images.setObject(img, forKey: attachmentId as NSString)90        return img91    }9293    /// A readable copy with the original file name, for Quick Look, "Open" and drag-out.94    func exportedFile(attachmentId: String, filename: String) async throws -> URL {95        let d = try await data(for: attachmentId)96        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("SPChat-\(attachmentId)", isDirectory: true)97        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)98        let url = dir.appendingPathComponent(FileValidator.sanitizedName(filename))99        try d.write(to: url, options: .atomic)100        return url101    }102103    /// Sign-out: nothing of the owner's files stays on disk.104    func purge() {105        images.removeAllObjects()106        try? FileManager.default.removeItem(at: directory)107        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)108    }109}110
Files main
Menu

Theme