SPB Git

Repository Public

DeepLink.swift 7.8 KB 166 lines swift

1// SP Notes iOS2// File: Shared/DeepLink.swift3// Description: The links understood by the app (widgets, notifications, shortcuts and other apps use them):4//              `spnotes://note/<id>[?block=<blockId>]`, `spnotes://new[?kind=tasks][&text=…]`, `spnotes://search?q=…`,5//              `spnotes://tasks`, `spnotes://inbox`, `spnotes://today`, `spnotes://capture[?kind=…]`, and the web address of a page6//              `https://note.spboucher.ai/p/<id>[#<blockId>]` (universal links, the day the entitlement exists). Parsing is strict:7//              an unknown or malformed link is refused rather than guessed.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213enum DeepLink: Equatable, Sendable {14    /// What a new note starts with.15    enum NewKind: String, Sendable, CaseIterable {16        case note17        case tasks18    }1920    /// What a capture starts as (the names of the server's capture kinds, plus the document scanner).21    enum CaptureKind: String, Sendable, CaseIterable {22        case note, tasks, link, photo, file, audio, scan, dictation, idea, text23    }2425    /// A note, optionally at one of its blocks (2.0).26    case note(String, blockId: String? = nil)27    case new(kind: NewKind, text: String?)28    case search(String)29    case tasks30    case inbox31    case today32    case capture(kind: CaptureKind?)3334    static let scheme = "spnotes"35    /// The host of the web app: its page addresses are understood as links to notes.36    static let webHost = "note.spboucher.ai"37    static var newNote: DeepLink { .new(kind: .note, text: nil) }3839    /// Accepts `spnotes://note/<id>`, `spnotes:///note/<id>` and `spnotes:note/<id>` (same for the other actions), and the web40    /// address of a page.41    init?(url: URL) {42        if let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http" {43            guard let link = Self.web(url) else { return nil }44            self = link45            return46        }47        guard url.scheme?.lowercased() == Self.scheme, let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }48        var parts = components.path.split(separator: "/").map(String.init)49        if let host = components.host, !host.isEmpty { parts.insert(host, at: 0) }50        guard let action = parts.first?.lowercased() else { return nil }51        func query(_ name: String) -> String? {52            let value = components.queryItems?.first { $0.name == name }?.value?.trimmingCharacters(in: .whitespacesAndNewlines)53            return value?.isEmpty == false ? value : nil54        }55        /// True when the parameter is absent; false when it is present but empty (a malformed link).56        func absent(_ name: String) -> Bool { components.queryItems?.contains { $0.name == name } != true }57        switch action {58        case "note":59            guard parts.count == 2, Self.isValidNoteID(parts[1]) else { return nil }60            var block: String?61            if !absent("block") {62                guard let value = query("block"), Self.isValidBlockID(value) else { return nil }63                block = value64            }65            self = .note(parts[1].lowercased(), blockId: block)66        case "new":67            guard parts.count == 1 else { return nil }68            var kind = NewKind.note69            if let name = query("kind") {70                guard let parsed = NewKind(rawValue: name.lowercased()) else { return nil }71                kind = parsed72            }73            self = .new(kind: kind, text: query("text"))74        case "search":75            guard parts.count == 1 else { return nil }76            self = .search(query("q") ?? "")77        case "tasks":78            guard parts.count == 1 else { return nil }79            self = .tasks80        case "inbox":81            guard parts.count == 1 else { return nil }82            self = .inbox83        case "today":84            guard parts.count == 1 else { return nil }85            self = .today86        case "capture":87            guard parts.count == 1 else { return nil }88            var kind: CaptureKind?89            if !absent("kind") {90                guard let name = query("kind"), let parsed = CaptureKind(rawValue: name.lowercased()) else { return nil }91                kind = parsed92            }93            self = .capture(kind: kind)94        default:95            return nil96        }97    }9899    /// `https://note.spboucher.ai/p/<id>[#<blockId>]` → the note (at the block). Only that host, only that path shape.100    static func web(_ url: URL) -> DeepLink? {101        guard url.scheme?.lowercased() == "https", let components = URLComponents(url: url, resolvingAgainstBaseURL: false),102              components.host?.lowercased() == webHost, components.port == nil, components.user == nil else { return nil }103        let parts = components.path.split(separator: "/", omittingEmptySubsequences: true).map(String.init)104        guard parts.count == 2, parts[0] == "p", isValidNoteID(parts[1]), parts[1].count == 36 else { return nil }105        var block: String?106        if let fragment = components.fragment, !fragment.isEmpty {107            guard isValidBlockID(fragment) else { return nil }108            block = fragment109        }110        return .note(parts[1].lowercased(), blockId: block)111    }112113    /// The web address of a page (Handoff to a browser, drags to other apps, sharing).114    static func webURL(noteId: String, blockId: String? = nil) -> URL {115        var components = URLComponents()116        components.scheme = "https"117        components.host = webHost118        components.path = "/p/" + noteId119        if let blockId, !blockId.isEmpty { components.fragment = blockId }120        return components.url ?? URL(string: "https://\(webHost)")!121    }122123    var url: URL {124        var components = URLComponents()125        components.scheme = Self.scheme126        switch self {127        case .note(let id, let blockId):128            components.host = "note"129            components.path = "/" + id130            if let blockId, !blockId.isEmpty { components.queryItems = [URLQueryItem(name: "block", value: blockId)] }131        case .new(let kind, let text):132            components.host = "new"133            var items: [URLQueryItem] = []134            if kind != .note { items.append(URLQueryItem(name: "kind", value: kind.rawValue)) }135            if let text, !text.isEmpty { items.append(URLQueryItem(name: "text", value: text)) }136            if !items.isEmpty { components.queryItems = items }137        case .search(let query):138            components.host = "search"139            if !query.isEmpty { components.queryItems = [URLQueryItem(name: "q", value: query)] }140        case .tasks: components.host = "tasks"141        case .inbox: components.host = "inbox"142        case .today: components.host = "today"143        case .capture(let kind):144            components.host = "capture"145            if let kind { components.queryItems = [URLQueryItem(name: "kind", value: kind.rawValue)] }146        }147        // The components above are always valid; the fallback only satisfies the type.148        return components.url ?? URL(string: "\(Self.scheme)://new")!149    }150151    /// Note ids are lowercase UUID strings; anything that is not made of hexadecimal digits and hyphens is refused.152    static func isValidNoteID(_ text: String) -> Bool {153        !text.isEmpty && text.count <= 64 && text.unicodeScalars.allSatisfy { CharacterSet.noteID.contains($0) }154    }155156    /// Block ids are short URL-safe identifiers (10 characters for the ones the editors create; UUIDs exist too).157    static func isValidBlockID(_ text: String) -> Bool {158        !text.isEmpty && text.count <= 64 && text.unicodeScalars.allSatisfy { CharacterSet.blockID.contains($0) }159    }160}161162private extension CharacterSet {163    static let noteID = CharacterSet(charactersIn: "0123456789abcdefABCDEF-")164    static let blockID = CharacterSet(charactersIn: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")165}166
Files main
Menu

Theme