Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Notes/Exporter.swift3// Description: Export of notes to open formats (Markdown, plain text, HTML file, RTF, PDF, ZIP archive with attachments), printing, and import of Markdown, text and RTF files — all local, no network needed.4import SwiftUI5import UniformTypeIdentifiers6import SPNotesDocument7import SPNotesEditor8import SPNotesStore9import SPNotesSync10import SPNotesAPI1112enum ExportFormat: String, CaseIterable, Identifiable {13 case markdown, text, html, rtf, pdf, zip14 var id: String { rawValue }15 var label: String { switch self { case .markdown: "Markdown (.md)"; case .text: "Texte brut (.txt)"; case .html: "Page HTML (.html)"; case .rtf: "Texte enrichi (.rtf)"; case .pdf: "PDF"; case .zip: "Archive ZIP (Markdown + fichiers)" } }16 var ext: String { switch self { case .markdown: "md"; case .text: "txt"; case .html: "html"; case .rtf: "rtf"; case .pdf: "pdf"; case .zip: "zip" } }17 var type: UTType { switch self { case .markdown: UTType(filenameExtension: "md") ?? .plainText; case .text: .plainText; case .html: .html; case .rtf: .rtf; case .pdf: .pdf; case .zip: .zip } }18}1920final class ExportResources: AtomResources {21 let env: AppEnvironment22 var paths: [String: String] = [:]23 init(env: AppEnvironment) { self.env = env }24 func image(for src: String) -> NSImage? { paths[src].flatMap { NSImage(contentsOfFile: $0) } }25}2627struct Exporter {28 let env: AppEnvironment2930 static func fileName(_ title: String) -> String {31 let cleaned = title.components(separatedBy: CharacterSet(charactersIn: "/\\:*?\"<>|\0").union(.controlCharacters)).joined(separator: " ").trimmingCharacters(in: .whitespaces)32 return cleaned.isEmpty ? "Sans titre" : String(cleaned.prefix(80))33 }34 private func title(_ p: PageRecord) -> String { p.title.isEmpty || p.title == "Untitled" ? "Sans titre" : p.title }3536 /// Bytes of one note in a single-file format.37 func data(for page: PageRecord, format: ExportFormat) async -> Data? {38 guard let doc = try? NoteDocument(json: page.content) else { return nil }39 switch format {40 case .markdown: return Data(markdown(page, doc, fileLinks: [:]).utf8)41 case .text: return Data((title(page) + "\n\n" + doc.plainText() + "\n").utf8)42 case .html: return Data(doc.html(title: title(page)).utf8)43 case .rtf:44 let text = ExportComposer.attributedString(title: title(page), document: doc, resources: nil, keepAttachments: false)45 return try? text.data(from: NSRange(location: 0, length: text.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf])46 case .pdf:47 let tmp = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".pdf"); defer { try? FileManager.default.removeItem(at: tmp) }48 let text = ExportComposer.attributedString(title: title(page), document: doc, resources: await resources(for: doc), keepAttachments: true)49 guard ExportComposer.pdf(text, to: tmp) else { return nil }50 return try? Data(contentsOf: tmp)51 case .zip: return nil52 }53 }5455 private func resources(for doc: NoteDocument) async -> ExportResources {56 let r = ExportResources(env: env)57 for src in doc.attachmentReferences() { if let id = ImageCache.attachmentId(src) ?? (UUID(uuidString: src) != nil ? src : nil), let rec = try? await env.store.attachment(id: id), let rel = rec.localPath { r.paths["/api/files/" + id] = env.files.url(relativePath: rel).path } }58 return r59 }6061 /// Markdown with a small front matter (id, tags, dates): enough to import the note elsewhere, or back.62 private func markdown(_ p: PageRecord, _ doc: NoteDocument, fileLinks: [String: String]) -> String {63 var md = doc.markdown()64 for (src, rel) in fileLinks { md = md.replacingOccurrences(of: "](\(src))", with: "](\(rel))") }65 let iso = ISO8601DateFormatter()66 var fm = "---\ntitle: \(yaml(title(p)))\nid: \(p.id)\n"67 if !p.tags.isEmpty { fm += "tags: [\(p.tags.map(yaml).joined(separator: ", "))]\n" }68 fm += "created: \(iso.string(from: p.createdAt))\nupdated: \(iso.string(from: p.updatedAt))\n---\n\n"69 return fm + "# " + title(p) + "\n\n" + md70 }71 private func yaml(_ s: String) -> String { s.range(of: #"^[\p{L}\p{N} _.-]+$"#, options: .regularExpression) != nil && !s.hasPrefix("-") ? s : "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }7273 /// Asks where to save, then writes. One note → one file (or a ZIP); several notes → always a ZIP.74 func export(noteIds: [String], format: ExportFormat) async {75 var pages: [PageRecord] = []76 for id in noteIds { await env.existingSession(id)?.saveNow(reason: nil); if let p = try? await env.store.page(id: id) { pages.append(p) } }77 guard let first = pages.first else { return }78 let asZip = format == .zip || pages.count > 179 let panel = NSSavePanel()80 panel.nameFieldStringValue = (pages.count == 1 ? Self.fileName(title(first)) : "Notes SP Notes") + "." + (asZip ? "zip" : format.ext)81 panel.allowedContentTypes = [asZip ? .zip : format.type]; panel.canCreateDirectories = true82 guard await panel.begin() == .OK, let dest = panel.url else { return }83 do {84 if asZip { try await writeZip(pages, inner: format == .zip ? .markdown : format, to: dest) }85 else { guard let d = await data(for: first, format: format) else { throw CocoaError(.fileWriteUnknown) }; try d.write(to: dest, options: .atomic) }86 env.toasts.show(pages.count == 1 ? "Note exportée" : "\(pages.count) notes exportées", symbol: "square.and.arrow.up")87 } catch { env.toasts.show("L'export a échoué : \(error.localizedDescription)", isError: true) }88 }8990 /// Whole library (every live note, sub-notes in folders named after their parent) as one ZIP.91 func exportLibrary() async {92 let all = (try? await env.store.summaries(list: .all, limit: 100_000)) ?? []93 await export(noteIds: all.map(\.id), format: .zip)94 }9596 func writeZip(_ pages: [PageRecord], inner: ExportFormat, to dest: URL) async throws {97 let fm = FileManager.default98 let root = fm.temporaryDirectory.appendingPathComponent("spnotes-export-\(UUID().uuidString)", isDirectory: true).appendingPathComponent("SP Notes", isDirectory: true)99 try fm.createDirectory(at: root.appendingPathComponent("fichiers", isDirectory: true), withIntermediateDirectories: true)100 defer { try? fm.removeItem(at: root.deletingLastPathComponent()) }101 var used = Set<String>(); var missing: [String] = []102 for p in pages {103 guard let doc = try? NoteDocument(json: p.content) else { continue }104 var links: [String: String] = [:]105 for ref in doc.attachmentReferences() {106 guard let id = ImageCache.attachmentId(ref) ?? (UUID(uuidString: ref) != nil ? ref.lowercased() : nil), let rec = try? await env.store.attachment(id: id) else { continue }107 let src = "/api/files/" + id108 if let rel = rec.localPath, fm.fileExists(atPath: env.files.url(relativePath: rel).path) {109 let name = id.prefix(8) + "-" + AttachmentService.sanitizedName(rec.filename)110 let target = root.appendingPathComponent("fichiers").appendingPathComponent(String(name))111 if !fm.fileExists(atPath: target.path) { try? fm.copyItem(at: env.files.url(relativePath: rel), to: target) }112 links[src] = "fichiers/" + (String(name).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? String(name))113 } else { missing.append("\(title(p)) : \(rec.filename)") }114 }115 var name = Self.fileName(title(p)); var n = 2116 while !used.insert(name.lowercased()).inserted { name = Self.fileName(title(p)) + " \(n)"; n += 1 }117 let data: Data? = inner == .markdown ? Data(markdown(p, doc, fileLinks: links).utf8) : await self.data(for: p, format: inner)118 try data?.write(to: root.appendingPathComponent(name + "." + inner.ext))119 }120 if !missing.isEmpty { try? Data(("Fichiers absents de ce Mac au moment de l'export (non inclus) :\n" + missing.joined(separator: "\n") + "\n").utf8).write(to: root.appendingPathComponent("FICHIERS-MANQUANTS.txt")) }121 // NSFileCoordinator produces a standard ZIP of a folder without any external tool122 var coordError: NSError?; var moveError: Error?123 NSFileCoordinator().coordinate(readingItemAt: root, options: [.forUploading], error: &coordError) { zipped in124 do { if fm.fileExists(atPath: dest.path) { try fm.removeItem(at: dest) }; try fm.copyItem(at: zipped, to: dest) } catch { moveError = error }125 }126 if let e = coordError ?? moveError { throw e }127 }128129 func print(noteId: String) async {130 guard let p = try? await env.store.page(id: noteId), let doc = try? NoteDocument(json: p.content) else { return }131 let text = ExportComposer.attributedString(title: title(p), document: doc, resources: await resources(for: doc), keepAttachments: true)132 let op = ExportComposer.printView(text)133 if let w = NSApp.keyWindow { op.runModal(for: w, delegate: nil, didRun: nil, contextInfo: nil) } else { op.run() }134 }135136 // MARK: Import137138 static let importTypes: [UTType] = [UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText, .plainText, .rtf]139140 /// One note per file. Markdown front matter (`title`, `tags`) is honoured; the first heading is the title otherwise.141 func importFiles(_ urls: [URL]) async -> [String] {142 var created: [String] = []143 for url in urls {144 let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } }145 guard let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size < 8_000_000, let data = try? Data(contentsOf: url) else { env.toasts.show("« \(url.lastPathComponent) » n'a pas pu être lu (8 Mo au plus).", isError: true); continue }146 var title = url.deletingPathExtension().lastPathComponent; var tags: [String] = []; var doc: NoteDocument147 if url.pathExtension.lowercased() == "rtf", let rich = NSAttributedString(rtf: data, documentAttributes: nil) { doc = NoteDocument(lines: NoteFragment.lines(fromForeign: rich)) }148 else {149 guard var text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else { continue }150 if text.hasPrefix("---\n"), let end = text.range(of: "\n---", range: text.index(text.startIndex, offsetBy: 4)..<text.endIndex) {151 for line in text[text.index(text.startIndex, offsetBy: 4)..<end.lowerBound].split(separator: "\n") {152 let parts = line.split(separator: ":", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }153 guard parts.count == 2 else { continue }154 let v = parts[1].trimmingCharacters(in: CharacterSet(charactersIn: "\""))155 if parts[0] == "title", !v.isEmpty { title = v }156 if parts[0] == "tags" { tags = v.trimmingCharacters(in: CharacterSet(charactersIn: "[]")).split(separator: ",").map { $0.trimmingCharacters(in: CharacterSet(charactersIn: " \"'")) }.filter { !$0.isEmpty } }157 }158 text = String(text[end.upperBound...]).trimmingCharacters(in: .newlines)159 }160 if ["md", "markdown"].contains(url.pathExtension.lowercased()) {161 // a leading « # Title » equal to the title is the title, not body text162 if let m = text.range(of: #"^#\s+(.+)\n"#, options: .regularExpression) { let h = text[m].dropFirst().trimmingCharacters(in: .whitespacesAndNewlines); if url.pathExtension.lowercased() == "md", title == url.deletingPathExtension().lastPathComponent || h == title { title = h; text.removeSubrange(m) } }163 doc = NoteDocument(markdown: text)164 } else { doc = NoteDocument(lines: text.components(separatedBy: "\n").map { Line.paragraph(text: $0) }) }165 }166 if let id = await env.library.newNote(title: title, content: doc, tags: tags) { created.append(id) }167 }168 if !created.isEmpty { env.toasts.show(created.count == 1 ? "1 note importée" : "\(created.count) notes importées", symbol: "square.and.arrow.down") }169 return created170 }171}172