SPB Git

Repository Public MIT

Attachments.swift 10.4 KB 203 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Chat/Attachments.swift10// Module           : Chat11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import SwiftUI90import ImageIO91import UniformTypeIdentifiers92import CryptoKit93import AstraCore94import AstraPersistence95#if canImport(PDFKit)96import PDFKit97#endif98#if canImport(UIKit)99import UIKit100#endif101102/// Turns files the person picked into attachment drafts. Everything here is bounded: file size, pixel count, extracted text.103public enum AttachmentImporter {104    public static let maxFileBytes = 20 * 1024 * 1024105    public static let maxImagePixel = 1568106    public static let maxExtractedCharacters = 120_000107108    public enum ImportError: Error, LocalizedError {109        case tooLarge(String), unreadable(String), unsupported(String)110        public var errorDescription: String? {111            switch self {112            case .tooLarge(let name): "“\(name)” is larger than 20 MB."113            case .unreadable(let name): "“\(name)” could not be read."114            case .unsupported(let name): "“\(name)” is not a supported file type. Images, PDFs and text files can be attached."115            }116        }117    }118119    /// Reads a document the person chose in the Files picker. The security-scoped access is held only for the read.120    public static func draft(fromFile url: URL) async throws -> AttachmentDraft {121        try await Task.detached(priority: .userInitiated) {122            let scoped = url.startAccessingSecurityScopedResource()123            defer { if scoped { url.stopAccessingSecurityScopedResource() } }124            let name = url.lastPathComponent125            let values = try? url.resourceValues(forKeys: [.fileSizeKey, .contentTypeKey, .isRegularFileKey])126            guard values?.isRegularFile ?? true else { throw ImportError.unsupported(name) }127            if let size = values?.fileSize, size > maxFileBytes { throw ImportError.tooLarge(name) }128            guard let data = try? Data(contentsOf: url, options: .mappedIfSafe) else { throw ImportError.unreadable(name) }129            guard data.count <= maxFileBytes else { throw ImportError.tooLarge(name) }130            let type = values?.contentType ?? UTType(filenameExtension: url.pathExtension) ?? .data131            return try draft(data: data, name: name, type: type)132        }.value133    }134135    /// Builds a draft from bytes already in memory (photo picker, paste).136    public static func draft(data: Data, name: String, type: UTType) throws -> AttachmentDraft {137        guard data.count <= maxFileBytes else { throw ImportError.tooLarge(name) }138        if type.conforms(to: .image) {139            guard let jpeg = downscaledJPEG(data, maxPixel: maxImagePixel) else { throw ImportError.unreadable(name) }140            let base = (name as NSString).deletingPathExtension141            return AttachmentDraft(kind: .image, filename: (base.isEmpty ? "image" : base) + ".jpg", mimeType: "image/jpeg", data: jpeg)142        }143        if type.conforms(to: .pdf) {144            #if canImport(PDFKit)145            guard let doc = PDFDocument(data: data), !doc.isLocked else { throw ImportError.unreadable(name) }146            var text = ""147            for i in 0..<min(doc.pageCount, 400) {148                if let page = doc.page(at: i)?.string { text += page + "\n\n" }149                if text.count > maxExtractedCharacters { break }150            }151            return AttachmentDraft(kind: .pdf, filename: name, mimeType: "application/pdf", data: data, extractedText: clip(text))152            #else153            throw ImportError.unsupported(name)154            #endif155        }156        if type.conforms(to: .text) || type.conforms(to: .sourceCode) || type.conforms(to: .json) || type.conforms(to: .xml) || type.conforms(to: .commaSeparatedText)157            || ["md", "markdown", "txt", "csv", "json", "yaml", "yml", "toml", "log", "swift", "py", "js", "ts", "tex", "html", "css", "sql", "sh", "rs", "go", "java", "c", "h", "cpp"].contains((name as NSString).pathExtension.lowercased()) {158            guard let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else { throw ImportError.unreadable(name) }159            return AttachmentDraft(kind: .text, filename: name, mimeType: "text/plain", data: data, extractedText: clip(text))160        }161        throw ImportError.unsupported(name)162    }163164    static func clip(_ text: String) -> String {165        let t = text.trimmingCharacters(in: .whitespacesAndNewlines)166        guard t.count > maxExtractedCharacters else { return t }167        return String(t.prefix(maxExtractedCharacters)) + "\n\n[The rest of this file was left out: it exceeds \(maxExtractedCharacters) characters.]"168    }169170    /// Decodes with ImageIO at the target size (never the full bitmap), applies the orientation and re-encodes as JPEG,171    /// which also drops location and camera metadata.172    public static func downscaledJPEG(_ data: Data, maxPixel: Int, quality: Double = 0.82) -> Data? {173        guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil }174        let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true,175                                        kCGImageSourceThumbnailMaxPixelSize: maxPixel, kCGImageSourceShouldCacheImmediately: true]176        guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }177        let out = NSMutableData()178        guard let dest = CGImageDestinationCreateWithData(out, UTType.jpeg.identifier as CFString, 1, nil) else { return nil }179        CGImageDestinationAddImage(dest, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)180        return CGImageDestinationFinalize(dest) ? out as Data : nil181    }182}183184enum ImageLoader {185    static func thumbnail(url: URL, maxPixel: Int) async -> Image? {186        await Task.detached(priority: .utility) { () -> Image? in187            guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil }188            let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true,189                                            kCGImageSourceThumbnailMaxPixelSize: maxPixel]190            guard let cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }191            return Image(decorative: cg, scale: 1)192        }.value193    }194195    static func thumbnail(data: Data, maxPixel: Int) -> Image? {196        guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }197        let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true,198                                        kCGImageSourceThumbnailMaxPixelSize: maxPixel]199        guard let cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }200        return Image(decorative: cg, scale: 1)201    }202}203
Files main
Menu

Theme