SPB Git

Repository Public

AppModel+Capture.swift 11.2 KB 201 lines swift

1// SP Notes iOS2// File: App/AppModel+Capture.swift3// Description: The one creation path of captures (Quick Capture, voice notes, dictation, share hand-off, later Quick Actions and4//              intents): a page written locally at once, in the inbox, with its capture kind, then synchronised like any page5//              under its client-chosen id (so it is never lost offline and never created twice). Also the device-local ledger6//              the page creation carries `inboxAt` and `captureKind` to the server (Core 2.0 final), so a capture is in the inbox everywhere.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesCore1213/// A local file that comes with a capture (photo, scan page, document). The file is copied into the app's storage.14struct CaptureFile: Sendable, Equatable {15    var url: URL16    var filename: String?17    var mime: String?18    init(url: URL, filename: String? = nil, mime: String? = nil) { self.url = url; self.filename = filename; self.mime = mime }19}2021/// A recording that comes with a capture: it becomes an attachment and an `audio` node.22struct VoiceCapture: Sendable, Equatable {23    var fileURL: URL24    /// Seconds.25    var duration: Double26    var recordedAt: Date27    var title: String = ""28    var transcript: [TranscriptSegment] = []29    var transcriptEngine: String?30}3132struct CaptureOutcome: Sendable, Equatable {33    var pageId: String34    /// Files that could not be attached (the capture exists anyway).35    var failedFiles = 036    /// False when a page with this id already existed: nothing was created (a repeated hand-off).37    var created = true38}3940enum CaptureError: LocalizedError, Equatable {41    case empty, invalidLink42    var errorDescription: String? {43        switch self {44        case .empty: return String(localized: "Il n’y a rien à enregistrer.")45        case .invalidLink: return String(localized: "Ce lien n’est pas une adresse http(s) valide.")46        }47    }48}4950/// The capture kinds, in the server's vocabulary (`pages.captureKind`, `POST /api/capture`; Core `CaptureKindName`).51enum CaptureKinds {52    /// The server has no « idea » kind: an idea is a `note` capture (shown with a light-bulb icon).53    static let ideaIcon = "💡"5455    /// What a shared item or a set of picked files is: `photo` when every file is a picture, `file` otherwise.56    static func kind(forFiles files: [CaptureFile]) -> String {57        guard !files.isEmpty else { return CaptureKindName.note }58        let pictures = ["jpg", "jpeg", "png", "heic", "heif", "gif", "webp", "tiff", "tif", "bmp"]59        let allPictures = files.allSatisfy { file in60            if let mime = file.mime { return mime.hasPrefix("image/") }61            return pictures.contains(((file.filename ?? file.url.lastPathComponent) as NSString).pathExtension.lowercased())62        }63        return allPictures ? CaptureKindName.photo : CaptureKindName.file64    }6566    /// The http(s) address in `text`, normalised; nil for anything else (same rule as the server's `safeUrl`).67    static func httpURL(_ text: String?) -> String? {68        guard let text = text?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty, !text.contains(where: \.isWhitespace),69              let components = URLComponents(string: text), let scheme = components.scheme?.lowercased(), scheme == "http" || scheme == "https",70              let host = components.host, !host.isEmpty else { return nil }71        return components.url?.absoluteString72    }7374    /// The first http(s) address found in a text (paste detection of the link mode).75    static func firstLink(in text: String) -> String? {76        for word in text.split(whereSeparator: \.isWhitespace) {77            let candidate = word.trimmingCharacters(in: CharacterSet(charactersIn: "<>()[]«»\"'.,;"))78            if let url = httpURL(candidate) { return url }79        }80        return nil81    }8283    /// The title of a capture nobody named: its first line (cut at 80 characters), else the host of the link, else what it is and when.84    static func title(explicit: String?, kind: String, text: String, url: String?, firstFilename: String?, hasVoice: Bool, date: Date) -> String {85        if let explicit = explicit?.trimmingCharacters(in: .whitespacesAndNewlines), !explicit.isEmpty { return String(explicit.prefix(300)) }86        let firstLine = text.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.first { !$0.isEmpty }87        if kind == CaptureKindName.link, let url, let host = URLComponents(string: url)?.host {88            return host.hasPrefix("www.") ? String(host.dropFirst(4)) : host89        }90        if let firstLine {91            // list and heading markers are not part of a title92            let clean = firstLine.replacingOccurrences(of: #"^(#{1,6}\s+|[-*+]\s+(\[[ xX]\]\s+)?|\d+[.)]\s+|>\s+)"#, with: "", options: .regularExpression)93            let base = clean.isEmpty ? firstLine : clean94            return base.count > 80 ? base.prefix(80).trimmingCharacters(in: .whitespaces) + "…" : base95        }96        let stamp = date.formatted(date: .abbreviated, time: .shortened)97        if hasVoice { return String(localized: "Mémo vocal · \(stamp)") }98        switch kind {99        case CaptureKindName.photo: return String(localized: "Photo · \(stamp)")100        case CaptureKindName.document: return String(localized: "Numérisation · \(stamp)")101        default: return firstFilename ?? String(localized: "Note · \(stamp)")102        }103    }104105    /// The body of a capture as a document (the attachments are appended once they are recorded).106    static func document(kind: String, text: String, url: String?) -> NoteDocument {107        let clean = text.replacingOccurrences(of: "\r\n", with: "\n").trimmingCharacters(in: .whitespacesAndNewlines)108        if kind == CaptureKindName.tasks {109            let lines = clean.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }110            let items = lines.map { line -> String in111                let bare = line.replacingOccurrences(of: #"^[-*+]\s+(\[[ xX]\]\s+)?"#, with: "", options: .regularExpression)112                return "- [ ] " + (bare.isEmpty ? line : bare)113            }114            return NoteDocument(markdown: items.joined(separator: "\n"))115        }116        var document = NoteDocument(markdown: clean)117        if let url {118            var linked = NoteDocument(markdown: "[\(url)](\(url))")119            // the address alone is not repeated under itself120            if clean != url { linked.insert(lines: document.lines, at: linked.lines.count) }121            document = linked122        }123        return document124    }125}126127extension AppModel {128    /// Tests only: answers the requests of every model created afterwards (the fake backend's URL protocol).129    static var testSessionConfiguration: (@Sendable () -> URLSessionConfiguration)?130131    // MARK: the creation path132133    /// Captures something into the inbox. Returns the id of the page.134    @discardableResult135    func capture(_ draft: CaptureDraft) async throws -> String {136        try await capture(draft, title: nil).pageId137    }138139    /// Captures something into the inbox: the page is written locally first (with `inboxAt` and the capture kind) and synchronised140    /// like any page, so this works without a network and a repeated call with the same `id` creates nothing.141    /// - Parameters:142    ///   - draft: kind (`CaptureKindName`), text (Markdown), link.143    ///   - id: a client-chosen page id (a hand-off item's id): the capture is idempotent on it.144    ///   - files / voice: local files copied into the note as attachments; a recording also becomes an `audio` node.145    func capture(_ draft: CaptureDraft, title: String?, icon: String? = nil, id: String? = nil, files: [CaptureFile] = [], voice: VoiceCapture? = nil,146                 at date: Date = Date()) async throws -> CaptureOutcome {147        let text = draft.text ?? ""148        var url: String?149        if draft.kind == CaptureKindName.link {150            guard let link = CaptureKinds.httpURL(draft.url) ?? CaptureKinds.firstLink(in: text) else { throw CaptureError.invalidLink }151            url = link152        } else if let link = CaptureKinds.httpURL(draft.url) {153            url = link154        }155        let hasText = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty156        let hasTitle = !(title ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty157        guard hasText || hasTitle || url != nil || !files.isEmpty || voice != nil else { throw CaptureError.empty }158159        let pageId = id.flatMap { UUID(uuidString: $0)?.uuidString.lowercased() }160        if let pageId, try await store.page(id: pageId) != nil { return CaptureOutcome(pageId: pageId, created: false) }161162        var document = CaptureKinds.document(kind: draft.kind, text: url != nil && draft.url == nil ? text.replacingOccurrences(of: url!, with: "") : text, url: url)163        if document.lines.isEmpty { document = NoteDocument(markdown: "") }164        document.ensureBlockIds()165        let digest = ContentDigest(document: document)166        let pageTitle = CaptureKinds.title(explicit: title, kind: draft.kind, text: text, url: url, firstFilename: files.first.map { $0.filename ?? $0.url.lastPathComponent },167                                           hasVoice: voice != nil, date: date)168        var page = NewPage(id: pageId, section: "notes", title: pageTitle, content: try document.jsonData(), plainText: digest.plainText,169                           wordCount: digest.wordCount, preview: digest.preview, inboxAt: date, captureKind: draft.kind)170        page.icon = icon171        let created = try await store.createPage(page)172        captureDidWrite()173174        // From here the capture exists: a file that cannot be attached is counted, never a reason to fail (or to create it again).175        var atoms: [Line] = []176        var failed = 0177        for file in files {178            do { atoms.append(Line(blockAtom: try await attach(fileAt: file.url, to: created.id, filename: file.filename, mime: file.mime), path: [])) } catch { failed += 1 }179        }180        if let voice {181            do { atoms.append(Line(blockAtom: try await VoiceNoteIO.audioNode(for: voice, app: self, noteId: created.id), path: [])) } catch { failed += 1 }182        }183        if !atoms.isEmpty, let stored = try? await store.page(id: created.id), var saved = try? NoteDocument(json: stored.content) {184            // a capture made only of files does not start with an empty paragraph185            let onlyEmptyParagraph = saved.lines.count == 1 && stored.plainText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty186            saved.insert(lines: atoms, at: onlyEmptyParagraph ? 0 : saved.lines.count)187            _ = try? await save(noteId: created.id, title: stored.title, document: saved)188        }189        return CaptureOutcome(pageId: created.id, failedFiles: failed)190    }191192    private func captureDidWrite() {193        if session == .signedIn { Task { await engine.schedule() } } else { Task { await engine.refreshCounts() } }194    }195196    // MARK: kind and inbox membership197198    /// The capture kind of a page (sent with the page creation since Core 2.0 final: `PageDraft.inboxAt / captureKind`).199    func captureKind(of pageId: String) async -> String? { (try? await store.page(id: pageId))?.captureKind }200}201
Files main
Menu

Theme