SPB Git

Repository Public License

NetscapeBookmarks.swift 20.3 KB 430 lines swift

1import Foundation23/// A bookmark or folder read from, or to be written to, a Netscape bookmark file.4public struct BookmarkFileNode: Sendable, Hashable {5    public enum Kind: Sendable, Hashable { case folder, link }67    public var kind: Kind8    public var title: String9    public var url: URL?10    public var addedAt: Date?11    public var modifiedAt: Date?12    public var tags: [String]13    public var isFavorite: Bool14    /// The browser's bookmarks bar (`PERSONAL_TOOLBAR_FOLDER="true"`).15    public var isToolbarFolder: Bool16    public var children: [BookmarkFileNode]1718    public init(kind: Kind, title: String, url: URL? = nil, addedAt: Date? = nil, modifiedAt: Date? = nil,19                tags: [String] = [], isFavorite: Bool = false, isToolbarFolder: Bool = false,20                children: [BookmarkFileNode] = []) {21        self.kind = kind; self.title = title; self.url = url; self.addedAt = addedAt; self.modifiedAt = modifiedAt22        self.tags = tags; self.isFavorite = isFavorite; self.isToolbarFolder = isToolbarFolder23        self.children = children24    }2526    public static func folder(_ title: String, _ children: [BookmarkFileNode] = []) -> BookmarkFileNode {27        BookmarkFileNode(kind: .folder, title: title, children: children)28    }2930    public static func link(_ title: String, _ url: URL, tags: [String] = [], isFavorite: Bool = false) -> BookmarkFileNode {31        BookmarkFileNode(kind: .link, title: title, url: url, tags: tags, isFavorite: isFavorite)32    }33}3435/// Reader and writer for the "Netscape bookmark file" HTML that Safari, Chrome, Firefox, Edge and Brave export.36///37/// The format is tag soup, not HTML: `<DT>` and `<p>` are never closed, attribute case and quoting vary, Safari38/// omits the outer `<DL>`, Chrome embeds multi-kilobyte `ICON="data:…"` attributes. The reader is therefore a39/// forgiving scanner driven by the five tags that carry structure (`H3`, `DL`, `/DL`, `A`, `/A`); everything40/// else is skipped. It never throws: unreadable input yields an empty result.41public enum NetscapeBookmarks {42    public struct ParseResult: Sendable, Hashable {43        public var roots: [BookmarkFileNode]44        /// Links dropped because their URL is missing, unparsable or not `http`, `https`, `ftp` or `file`45        /// (bookmarklets, Firefox `place:` queries, browser-internal pages).46        public var skippedLinks: Int4748        public var linkCount: Int { Self.count(roots, .link) }49        public var folderCount: Int { Self.count(roots, .folder) }5051        private static func count(_ nodes: [BookmarkFileNode], _ kind: BookmarkFileNode.Kind) -> Int {52            nodes.reduce(0) { $0 + ($1.kind == kind ? 1 : 0) + count($1.children, kind) }53        }54    }5556    public static let importableSchemes: Set<String> = ["http", "https", "ftp", "file"]5758    /// Folder nesting kept on import. No browser produces anything close; the bound keeps a hostile file from59    /// building a tree deep enough to exhaust the stack of whoever walks it recursively.60    public static let maximumDepth = 646162    // MARK: - Reading6364    /// Decodes the file (UTF-8, UTF-16 with a byte-order mark, or Windows-1252 as a last resort) and parses it.65    public static func parse(data: Data) -> ParseResult {66        if data.starts(with: [0xFF, 0xFE]) || data.starts(with: [0xFE, 0xFF]),67           let text = String(data: data, encoding: .utf16) {68            return parse(text)69        }70        if let text = String(data: data, encoding: .utf8) { return parse(text) }71        if let text = String(data: data, encoding: .windowsCP1252) { return parse(text) }72        return parse(String(decoding: data, as: UTF8.self))73    }7475    public static func parse(_ html: String) -> ParseResult {76        var parser = Parser(bytes: Array(html.utf8))77        return parser.run()78    }7980    private struct Frame {81        var folder: BookmarkFileNode?82        var children: [BookmarkFileNode] = []83    }8485    private struct Parser {86        let bytes: [UInt8]87        var position = 088        var stack: [Frame] = [Frame()]89        /// A folder whose `<H3>` was read and whose `<DL>` has not started yet.90        var pendingFolder: BookmarkFileNode?91        /// The `<A>` or `<H3>` whose text is being collected.92        var open: BookmarkFileNode?93        var text: [UInt8] = []94        var skipped = 09596        init(bytes: [UInt8]) { self.bytes = bytes }9798        mutating func run() -> ParseResult {99            while position < bytes.count {100                if bytes[position] == UInt8(ascii: "<") {101                    readTag()102                } else {103                    if open != nil { text.append(bytes[position]) }104                    position += 1105                }106            }107            closeOpenElement()108            flushPendingFolder()109            while stack.count > 1 { popFrame() }110            return ParseResult(roots: stack[0].children, skippedLinks: skipped)111        }112113        private mutating func readTag() {114            // Comments and declarations carry no structure.115            if matches("<!--") {116                position = find("-->", from: position + 4).map { $0 + 3 } ?? bytes.count117                return118            }119            // Find the closing '>' while honouring quotes (ICON data URLs and titles may contain '>').120            var index = position + 1121            var quote: UInt8?122            while index < bytes.count {123                let byte = bytes[index]124                if let current = quote {125                    if byte == current { quote = nil }126                } else if byte == UInt8(ascii: "\"") || byte == UInt8(ascii: "'") {127                    // A quote only opens an attribute value right after '='; an apostrophe elsewhere is noise.128                    if index > 0, bytes[index - 1] == UInt8(ascii: "=") { quote = byte }129                } else if byte == UInt8(ascii: ">") {130                    break131                }132                index += 1133            }134            if index >= bytes.count, quote != nil {135                // An attribute value that never closes would swallow the rest of the file: fall back to the136                // first '>' and let the attribute parser cope with the truncated value.137                index = position + 1138                while index < bytes.count, bytes[index] != UInt8(ascii: ">") { index += 1 }139            }140            let inner = Array(bytes[(position + 1)..<min(index, bytes.count)])141            position = min(index + 1, bytes.count)142            handleTag(inner)143        }144145        private mutating func handleTag(_ inner: [UInt8]) {146            var cursor = 0147            let isClosing = inner.first == UInt8(ascii: "/")148            if isClosing { cursor = 1 }149            let nameStart = cursor150            while cursor < inner.count, Self.isNameByte(inner[cursor]) { cursor += 1 }151            let name = String(decoding: inner[nameStart..<cursor], as: UTF8.self).uppercased()152153            switch (name, isClosing) {154            case ("A", false):155                closeOpenElement()156                flushPendingFolder()157                let attributes = Self.attributes(inner, from: cursor)158                var node = BookmarkFileNode(kind: .link, title: "")159                node.url = attributes["HREF"].flatMap(Self.importableURL)160                // A link without a usable URL still has to consume its text, so keep it open and drop it later.161                node.addedAt = attributes["ADD_DATE"].flatMap(Self.date)162                node.modifiedAt = attributes["LAST_MODIFIED"].flatMap(Self.date)163                node.tags = (attributes["TAGS"] ?? "").split(separator: ",")164                    .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }165                node.isFavorite = attributes["ORIX_FAVORITE"]?.lowercased() == "true"166                open = node167                text.removeAll(keepingCapacity: true)168            case ("H3", false):169                closeOpenElement()170                flushPendingFolder()171                let attributes = Self.attributes(inner, from: cursor)172                var node = BookmarkFileNode(kind: .folder, title: "")173                node.addedAt = attributes["ADD_DATE"].flatMap(Self.date)174                node.modifiedAt = attributes["LAST_MODIFIED"].flatMap(Self.date)175                node.isToolbarFolder = attributes["PERSONAL_TOOLBAR_FOLDER"]?.lowercased() == "true"176                node.isFavorite = attributes["ORIX_FAVORITE"]?.lowercased() == "true"177                open = node178                text.removeAll(keepingCapacity: true)179            case ("A", true), ("H3", true):180                closeOpenElement()181            case ("DL", false):182                closeOpenElement()183                if stack.count > NetscapeBookmarks.maximumDepth {184                    // Deeper lists are flattened into the deepest allowed folder: the heading stays as an empty185                    // folder and a transparent frame keeps the </DL> balance.186                    flushPendingFolder()187                }188                stack.append(Frame(folder: pendingFolder))189                pendingFolder = nil190            case ("DL", true):191                closeOpenElement()192                flushPendingFolder()193                // An unbalanced </DL> must not pop the root.194                if stack.count > 1 { popFrame() }195            case ("DT", _), ("DD", _), ("HR", _), ("H1", _), ("TITLE", _):196                // Block boundaries: an unclosed <A> or <H3> ends here. <DD> starts a description we do not keep.197                closeOpenElement()198            default:199                break   // <p>, <META>, inline formatting inside a title…200            }201        }202203        private mutating func closeOpenElement() {204            guard var node = open else { return }205            open = nil206            node.title = Self.decodeEntities(String(decoding: text, as: UTF8.self))207                .split(whereSeparator: \.isWhitespace).joined(separator: " ")208            text.removeAll(keepingCapacity: true)209            switch node.kind {210            case .folder:211                pendingFolder = node212            case .link:213                guard let url = node.url else { skipped += 1; return }214                if node.title.isEmpty { node.title = url.host() ?? url.absoluteString }215                stack[stack.count - 1].children.append(node)216            }217        }218219        /// A folder heading that is not followed by a `<DL>` is an empty folder.220        private mutating func flushPendingFolder() {221            guard let folder = pendingFolder else { return }222            pendingFolder = nil223            stack[stack.count - 1].children.append(folder)224        }225226        private mutating func popFrame() {227            let frame = stack.removeLast()228            if var folder = frame.folder {229                folder.children = frame.children230                if folder.isToolbarFolder {231                    // Items directly on the bookmarks bar are what the user sees every day: favourites.232                    for index in folder.children.indices where folder.children[index].kind == .link {233                        folder.children[index].isFavorite = true234                    }235                }236                stack[stack.count - 1].children.append(folder)237            } else {238                // A <DL> without a heading (the outer list of the file) is transparent.239                stack[stack.count - 1].children.append(contentsOf: frame.children)240            }241        }242243        private func matches(_ literal: String) -> Bool {244            let pattern = Array(literal.utf8)245            guard position + pattern.count <= bytes.count else { return false }246            return bytes[position..<(position + pattern.count)].elementsEqual(pattern)247        }248249        private func find(_ literal: String, from start: Int) -> Int? {250            let pattern = Array(literal.utf8)251            guard !pattern.isEmpty, start < bytes.count, bytes.count >= pattern.count else { return nil }252            var index = start253            while index + pattern.count <= bytes.count {254                if bytes[index] == pattern[0], bytes[index..<(index + pattern.count)].elementsEqual(pattern) {255                    return index256                }257                index += 1258            }259            return nil260        }261262        private static func isNameByte(_ byte: UInt8) -> Bool {263            (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x5A) || (byte >= 0x61 && byte <= 0x7A)264                || byte == UInt8(ascii: "_") || byte == UInt8(ascii: "-") || byte == UInt8(ascii: ":")265        }266267        private static func isSpace(_ byte: UInt8) -> Bool { byte == 0x20 || (byte >= 0x09 && byte <= 0x0D) }268269        /// Attribute names upper-cased; values entity-decoded. Handles `"…"`, `'…'`, bare values and flags.270        private static func attributes(_ inner: [UInt8], from start: Int) -> [String: String] {271            var result: [String: String] = [:]272            var cursor = start273            while cursor < inner.count {274                while cursor < inner.count, isSpace(inner[cursor]) || inner[cursor] == UInt8(ascii: "/") { cursor += 1 }275                let nameStart = cursor276                while cursor < inner.count, isNameByte(inner[cursor]) { cursor += 1 }277                guard cursor > nameStart else { cursor += 1; continue }278                let name = String(decoding: inner[nameStart..<cursor], as: UTF8.self).uppercased()279                while cursor < inner.count, isSpace(inner[cursor]) { cursor += 1 }280                guard cursor < inner.count, inner[cursor] == UInt8(ascii: "=") else {281                    result[name] = result[name] ?? ""282                    continue283                }284                cursor += 1285                while cursor < inner.count, isSpace(inner[cursor]) { cursor += 1 }286                guard cursor < inner.count else { result[name] = ""; break }287                let valueStart: Int, valueEnd: Int288                if inner[cursor] == UInt8(ascii: "\"") || inner[cursor] == UInt8(ascii: "'") {289                    let quote = inner[cursor]290                    cursor += 1291                    valueStart = cursor292                    while cursor < inner.count, inner[cursor] != quote { cursor += 1 }293                    valueEnd = cursor294                    cursor = min(cursor + 1, inner.count)295                } else {296                    valueStart = cursor297                    while cursor < inner.count, !isSpace(inner[cursor]) { cursor += 1 }298                    valueEnd = cursor299                }300                // First occurrence wins, as in browsers.301                if result[name] == nil {302                    // Skip decoding the huge attributes nobody reads (ICON data URLs).303                    result[name] = name == "ICON" || name == "ICON_URI" ? ""304                        : decodeEntities(String(decoding: inner[valueStart..<valueEnd], as: UTF8.self))305                }306            }307            return result308        }309310        private static func importableURL(_ text: String) -> URL? {311            let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)312            guard !trimmed.isEmpty, let url = URL(string: trimmed), let scheme = url.scheme?.lowercased(),313                  NetscapeBookmarks.importableSchemes.contains(scheme) else { return nil }314            return url315        }316317        /// `ADD_DATE` is seconds since 1970; some exporters write milliseconds or microseconds.318        private static func date(_ text: String) -> Date? {319            guard var value = Double(text.trimmingCharacters(in: .whitespaces)), value > 0 else { return nil }320            if value > 1e14 { value /= 1e6 } else if value > 1e11 { value /= 1e3 }321            return Date(timeIntervalSince1970: value)322        }323324        static let namedEntities: [String: String] = [325            "amp": "&", "lt": "<", "gt": ">", "quot": "\"", "apos": "'", "nbsp": "\u{A0}", "copy": "©",326            "reg": "®", "trade": "™", "hellip": "…", "mdash": "—", "ndash": "–", "laquo": "«", "raquo": "»",327            "lsquo": "‘", "rsquo": "’", "ldquo": "“", "rdquo": "”", "eacute": "é", "egrave": "è", "ecirc": "ê",328            "agrave": "à", "acirc": "â", "ccedil": "ç", "ocirc": "ô", "ugrave": "ù", "ucirc": "û", "icirc": "î",329            "iuml": "ï", "euml": "ë", "uuml": "ü", "ouml": "ö", "auml": "ä", "szlig": "ß", "ntilde": "ñ",330            "Eacute": "É", "middot": "·", "bull": "•", "deg": "°", "euro": "€",331        ]332333        static func decodeEntities(_ text: String) -> String {334            guard text.contains("&") else { return text }335            var result = ""336            var rest = Substring(text)337            while let ampersand = rest.firstIndex(of: "&") {338                result += rest[..<ampersand]339                let after = rest[rest.index(after: ampersand)...]340                guard let semicolon = after.firstIndex(of: ";"),341                      after.distance(from: after.startIndex, to: semicolon) <= 10 else {342                    result.append("&")343                    rest = after344                    continue345                }346                let name = String(after[..<semicolon])347                var replacement: String?348                if name.hasPrefix("#x") || name.hasPrefix("#X") {349                    replacement = UInt32(name.dropFirst(2), radix: 16).flatMap(Unicode.Scalar.init).map { String($0) }350                } else if name.hasPrefix("#") {351                    replacement = UInt32(name.dropFirst(), radix: 10).flatMap(Unicode.Scalar.init).map { String($0) }352                } else {353                    replacement = namedEntities[name]354                }355                if let replacement {356                    result += replacement357                    rest = after[after.index(after: semicolon)...]358                } else {359                    result.append("&")360                    rest = after361                }362            }363            result += rest364            return result365        }366    }367368    // MARK: - Writing369370    /// Writes a UTF-8 Netscape bookmark file that Safari, Chrome and Firefox import.371    ///372    /// Tags use Firefox's `TAGS="a,b"` attribute (a comma inside a tag becomes a space, the format has no373    /// escape for it). Favourites use the private `ORIX_FAVORITE="true"` attribute, which other browsers ignore.374    public static func export(_ roots: [BookmarkFileNode], title: String = "Bookmarks") -> String {375        var output = """376        <!DOCTYPE NETSCAPE-Bookmark-file-1>377        <!-- This is an automatically generated file.378             It will be read and overwritten.379             DO NOT EDIT! -->380        <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">381        <TITLE>\(escape(title))</TITLE>382        <H1>\(escape(title))</H1>383        <DL><p>384385        """386        write(roots, depth: 1, into: &output)387        output += "</DL><p>\n"388        return output389    }390391    private static func write(_ nodes: [BookmarkFileNode], depth: Int, into output: inout String) {392        let indent = String(repeating: "    ", count: depth)393        for node in nodes {394            var attributes = ""395            if let added = node.addedAt { attributes += " ADD_DATE=\"\(Int(added.timeIntervalSince1970))\"" }396            if let modified = node.modifiedAt { attributes += " LAST_MODIFIED=\"\(Int(modified.timeIntervalSince1970))\"" }397            if node.isFavorite { attributes += " ORIX_FAVORITE=\"true\"" }398            switch node.kind {399            case .folder:400                if node.isToolbarFolder { attributes += " PERSONAL_TOOLBAR_FOLDER=\"true\"" }401                output += "\(indent)<DT><H3\(attributes)>\(escape(node.title))</H3>\n\(indent)<DL><p>\n"402                write(node.children, depth: depth + 1, into: &output)403                output += "\(indent)</DL><p>\n"404            case .link:405                guard let url = node.url else { continue }406                if !node.tags.isEmpty {407                    let tags = node.tags.map { $0.replacingOccurrences(of: ",", with: " ") }.joined(separator: ",")408                    attributes += " TAGS=\"\(escape(tags))\""409                }410                output += "\(indent)<DT><A HREF=\"\(escape(url.absoluteString))\"\(attributes)>\(escape(node.title))</A>\n"411            }412        }413    }414415    private static func escape(_ text: String) -> String {416        var result = ""417        result.reserveCapacity(text.count)418        for character in text {419            switch character {420            case "&": result += "&amp;"421            case "<": result += "&lt;"422            case ">": result += "&gt;"423            case "\"": result += "&quot;"424            default: result.append(character)425            }426        }427        return result428    }429}430
Files main
Menu

Theme