Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Attachments/AttachmentService.swift3// Description: Local side of attachments: validation and import of files and pasted images into the app's storage, lookup, opening with Quick Look, disk usage and eviction.4import SwiftUI5import UniformTypeIdentifiers6import QuickLookUI7import SPNotesStore8import SPNotesAPI910struct ImportedAttachment { let id: String; let src: String; let name: String; let size: Int; let mime: String; let isImage: Bool }1112enum AttachmentError: LocalizedError {13 case tooLarge(String), blocked(String), unreadable(String)14 var errorDescription: String? {15 switch self {16 case .tooLarge(let n): "« \(n) » dépasse 200 Mo, la limite du serveur."17 case .blocked(let n): "« \(n) » : ce type de fichier (programme, page web, script) n'est pas accepté."18 case .unreadable(let n): "« \(n) » n'a pas pu être lu."19 }20 }21}2223struct AttachmentService {24 let env: AppEnvironment25 static let maxSize: Int64 = 200 * 1024 * 102426 static let blockedTypes: [UTType] = [.html, .javaScript, .executable, .unixExecutable, .shellScript, .application, .applicationBundle, .diskImage]27 static let blockedExtensions: Set<String> = ["exe", "msi", "bat", "cmd", "com", "scr", "sh", "command", "html", "htm", "js", "mjs", "app", "pkg", "dmg", "jar"]2829 static func validate(_ url: URL) throws -> (size: Int64, type: UTType, mime: String) {30 let name = url.lastPathComponent31 guard let values = try? url.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey, .contentTypeKey]), values.isRegularFile == true, let size = values.fileSize else { throw AttachmentError.unreadable(name) }32 if Int64(size) > maxSize { throw AttachmentError.tooLarge(name) }33 let type = values.contentType ?? UTType(filenameExtension: url.pathExtension) ?? .data34 if blockedExtensions.contains(url.pathExtension.lowercased()) || blockedTypes.contains(where: { type.conforms(to: $0) }) { throw AttachmentError.blocked(name) }35 return (Int64(size), type, type.preferredMIMEType ?? "application/octet-stream")36 }3738 /// Copies a file into the app's storage and registers it for upload. The id is chosen here, so the note can39 /// reference `/api/files/<id>` at once, online or not.40 func importFile(_ url: URL, pageId: String) async throws -> ImportedAttachment {41 let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } }42 let v = try Self.validate(url)43 let id = NotesAPI.newID()44 let name = Self.sanitizedName(url.lastPathComponent)45 let rel = env.files.relativePath(id: id, filename: name)46 let dest = env.files.url(relativePath: rel)47 do { try FileManager.default.copyItem(at: url, to: dest) } catch { throw AttachmentError.unreadable(name) }48 let files = env.files49 let sha = await Task.detached { AttachmentFiles.sha256(of: files.url(relativePath: rel)) }.value50 try await env.store.addLocalAttachment(id: id, pageId: pageId, filename: name, mime: v.mime, size: v.size, sha256: sha, localPath: rel)51 let src = NotesAPI.filePath(id: id)52 ImageCache.shared.register(src: src, path: dest.path)53 env.syncMonitor.localChange()54 return ImportedAttachment(id: id, src: src, name: name, size: Int(v.size), mime: v.mime, isImage: v.type.conforms(to: .image))55 }5657 func importImage(_ image: NSImage, pageId: String) async throws -> ImportedAttachment {58 guard let tiff = image.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff), let png = rep.representation(using: .png, properties: [:]) else { throw AttachmentError.unreadable("image") }59 let stamp = Date().formatted(.iso8601.year().month().day().time(includingFractionalSeconds: false).timeSeparator(.omitted).dateSeparator(.dash))60 let tmp = FileManager.default.temporaryDirectory.appendingPathComponent("Image \(stamp).png")61 try png.write(to: tmp, options: .atomic); defer { try? FileManager.default.removeItem(at: tmp) }62 return try await importFile(tmp, pageId: pageId)63 }6465 /// File name without path separators or control characters, never empty, never hidden.66 static func sanitizedName(_ name: String) -> String {67 var n = name.components(separatedBy: CharacterSet(charactersIn: "/\\:\0").union(.controlCharacters)).joined(separator: "-").trimmingCharacters(in: .whitespaces)68 while n.hasPrefix(".") { n.removeFirst() }69 return n.isEmpty ? "fichier" : String(n.prefix(200))70 }7172 /// Local URL of an attachment, downloading it first when it is only on the server.73 func localURL(attachmentId id: String) async throws -> URL {74 if let rec = try await env.store.attachment(id: id), let rel = rec.localPath {75 let url = env.files.url(relativePath: rel)76 if FileManager.default.fileExists(atPath: url.path) { try? await env.store.touchAttachment(id: id); return url }77 }78 return try await env.syncMonitor.download(attachmentId: id)79 }8081 /// Opens with Quick Look. Files are shown under their real name from a temporary copy.82 func preview(attachmentId id: String, name: String?) async {83 do {84 let url = try await localURL(attachmentId: id)85 var shown = url86 if let name, !name.isEmpty {87 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-preview-\(id)", isDirectory: true)88 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)89 let copy = dir.appendingPathComponent(Self.sanitizedName(name))90 if !FileManager.default.fileExists(atPath: copy.path) { try? FileManager.default.copyItem(at: url, to: copy) }91 if FileManager.default.fileExists(atPath: copy.path) { shown = copy }92 }93 QuickLook.shared.show(shown)94 } catch { env.toasts.show(env.connectivity.reachable ? "Ce fichier n'a pas pu être téléchargé." : "Ce fichier n'est pas sur ce Mac et le réseau est indisponible.", isError: true) }95 }9697 func saveCopy(attachmentId id: String, name: String) async {98 guard let url = try? await localURL(attachmentId: id) else { env.toasts.show("Ce fichier n'est pas disponible hors ligne.", isError: true); return }99 let panel = NSSavePanel(); panel.nameFieldStringValue = Self.sanitizedName(name)100 guard await panel.begin() == .OK, let dest = panel.url else { return }101 do { if FileManager.default.fileExists(atPath: dest.path) { try FileManager.default.removeItem(at: dest) }; try FileManager.default.copyItem(at: url, to: dest) } catch { env.toasts.error(error) }102 }103104 /// Bytes used by attachment files on this Mac.105 func diskUsage() -> Int64 {106 let urls = (try? FileManager.default.contentsOfDirectory(at: env.files.directory, includingPropertiesForKeys: [.fileSizeKey])) ?? []107 return urls.reduce(0) { $0 + Int64((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }108 }109110 /// Frees space: removes local copies of files that the server holds and that are not marked « keep offline ».111 func evict() async -> Int {112 var freed = 0113 while let batch = try? await env.store.evictionCandidates(limit: 50), !batch.isEmpty {114 for a in batch { if let rel = a.localPath { env.files.remove(relativePath: rel) }; try? await env.store.markAttachmentEvicted(id: a.id); freed += 1 }115 if batch.count < 50 { break }116 }117 ImageCache.shared.clear()118 return freed119 }120}121122/// Quick Look panel driven from SwiftUI code.123final class QuickLook: NSObject, QLPreviewPanelDataSource {124 static let shared = QuickLook()125 private var urls: [URL] = []126 func show(_ url: URL) {127 urls = [url]128 guard let panel = QLPreviewPanel.shared() else { return }129 panel.dataSource = self; panel.reloadData(); panel.makeKeyAndOrderFront(nil)130 }131 nonisolated func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int { MainActor.assumeIsolated { urls.count } }132 nonisolated func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> QLPreviewItem! { MainActor.assumeIsolated { urls[index] as NSURL } }133}134