Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/MediaBlocks/FeatureAttachmentLoader.swift3// Description: How the media views (canvas cards, drawing, PDF) read and write attachment bytes. The files belong to the4// host app (its attachments directory and the sync engine), so the views only see this small injectable5// value: attachment id → data, and data → new attachment id. `standard` builds the usual one from the6// repositories and the app's file locator.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesAPI12import SPNotesStore13import SPNotesSync14import SwiftUI1516public struct FeatureAttachmentLoader: Sendable {17 public typealias Load = @Sendable (_ attachmentId: String) async throws -> Data18 public typealias Upload = @Sendable (_ data: Data, _ filename: String, _ mimeType: String, _ pageId: String?) async throws -> String1920 private let loadBody: Load21 private let uploadBody: Upload?2223 public init(load: @escaping Load, upload: Upload? = nil) {24 loadBody = load25 uploadBody = upload26 }2728 /// False when this loader cannot create attachments (the editors then disable their « Enregistrer »).29 public var canUpload: Bool { uploadBody != nil }3031 public func data(id: String) async throws -> Data { try await loadBody(id) }3233 /// Stores `data` as a new attachment and returns its id.34 public func upload(_ data: Data, filename: String, mimeType: String, pageId: String?) async throws -> String {35 guard let uploadBody else { throw FeatureFailure(kind: .unsupported, message: L("L'envoi de fichiers n'est pas disponible ici.")) }36 return try await uploadBody(data, filename, mimeType, pageId)37 }3839 /// No file access at all: every read fails calmly (previews without a host).40 public static let unavailable = FeatureAttachmentLoader(load: { _ in41 throw FeatureFailure(kind: .notCached, message: L("Ce fichier n'est pas disponible sur cet appareil."))42 })4344 /// The usual loader: the local copy when the device has the file, else a download from the server (kept in a45 /// temporary file only: the engine owns the offline copies). Uploads go straight to the server (online only).46 public static func standard(repositories: NotesRepositories, files: any AttachmentFileLocating) -> FeatureAttachmentLoader {47 let context = repositories.context48 return FeatureAttachmentLoader(load: { id in49 if let record = try? await context.store.attachment(id: id), let path = record.localPath,50 let data = try? Data(contentsOf: files.url(relativePath: path)) { return data }51 let destination = FileManager.default.temporaryDirectory.appendingPathComponent("spn-attachment-\(UUID().uuidString)")52 defer { try? FileManager.default.removeItem(at: destination) }53 do {54 _ = try await context.api.downloadFile(id: id, to: destination)55 return try Data(contentsOf: destination)56 } catch { throw FeatureFailure(error) }57 }, upload: { data, filename, mimeType, pageId in58 let source = FileManager.default.temporaryDirectory.appendingPathComponent("spn-upload-\(UUID().uuidString)-\(filename)")59 defer { try? FileManager.default.removeItem(at: source) }60 do {61 try data.write(to: source)62 let id = NotesAPI.newID()63 _ = try await context.api.uploadAttachment(fileURL: source, id: id, pageID: pageId, filename: filename, mimeType: mimeType)64 return id65 } catch { throw FeatureFailure(error) }66 })67 }68}6970private struct FeatureAttachmentLoaderKey: EnvironmentKey { static let defaultValue = FeatureAttachmentLoader.unavailable }7172public extension EnvironmentValues {73 /// The attachment access of the media views below (default: unavailable).74 var featureAttachmentLoader: FeatureAttachmentLoader {75 get { self[FeatureAttachmentLoaderKey.self] }76 set { self[FeatureAttachmentLoaderKey.self] = newValue }77 }78}7980public extension View {81 func featureAttachmentLoader(_ loader: FeatureAttachmentLoader) -> some View { environment(\.featureAttachmentLoader, loader) }82}83