Repository Public
1import Foundation23struct Bookmark: Identifiable, Equatable, Sendable {4 var id: String5 var parentID: String?6 var isFolder: Bool7 var title: String8 var url: String?9 var tags: [String]10 var position: Int11 var createdAt: Date12}1314/// A bookmark with its descendants, used for import/export and for rendering the tree.15struct BookmarkNode: Equatable, Sendable {16 var bookmark: Bookmark17 var children: [BookmarkNode]18}1920final class BookmarkStore: Sendable {21 private let db: SQLiteDatabase22 init(db: SQLiteDatabase) { self.db = db }2324 static func normalizeTags(_ tags: [String]) -> [String] {25 var seen = Set<String>()26 return tags.map { $0.trimmingCharacters(in: .whitespaces).lowercased().replacingOccurrences(of: ",", with: " ") }27 .filter { !$0.isEmpty && seen.insert($0).inserted }28 }2930 @discardableResult31 func add(title: String, url: String?, parentID: String? = nil, isFolder: Bool = false, tags: [String] = [],32 id: String = UUID().uuidString, createdAt: Date = Date()) -> Bookmark? {33 let position = nextPosition(in: parentID)34 let cleanTags = Self.normalizeTags(tags)35 let ok = (try? db.execute(36 "INSERT INTO bookmarks(id, parent_id, is_folder, title, url, position, created_at, tags) VALUES(?,?,?,?,?,?,?,?)",37 [.text(id), parentID.map(SQLValue.text) ?? .null, .int(isFolder ? 1 : 0), .text(title),38 url.map(SQLValue.text) ?? .null, .int(Int64(position)), .double(createdAt.timeIntervalSince1970),39 .text(cleanTags.joined(separator: ","))])) != nil40 return ok ? Bookmark(id: id, parentID: parentID, isFolder: isFolder, title: title, url: url, tags: cleanTags,41 position: position, createdAt: createdAt) : nil42 }4344 @discardableResult45 func addFolder(_ title: String, parentID: String? = nil) -> Bookmark? {46 add(title: title, url: nil, parentID: parentID, isFolder: true)47 }4849 func update(_ bookmark: Bookmark) {50 _ = try? db.execute("UPDATE bookmarks SET title = ?, url = ?, tags = ? WHERE id = ?",51 [.text(bookmark.title), bookmark.url.map(SQLValue.text) ?? .null,52 .text(Self.normalizeTags(bookmark.tags).joined(separator: ",")), .text(bookmark.id)])53 }5455 /// Writes a bookmark exactly as another device has it (identifier, parent and position included).56 func upsertSynced(_ b: Bookmark) {57 _ = try? db.execute("""58 INSERT INTO bookmarks(id, parent_id, is_folder, title, url, position, created_at, tags) VALUES(?,?,?,?,?,?,?,?)59 ON CONFLICT(id) DO UPDATE SET parent_id = excluded.parent_id, title = excluded.title, url = excluded.url,60 position = excluded.position, tags = excluded.tags61 """, [.text(b.id), b.parentID.map(SQLValue.text) ?? .null, .int(b.isFolder ? 1 : 0), .text(b.title), b.url.map(SQLValue.text) ?? .null,62 .int(Int64(b.position)), .double(b.createdAt.timeIntervalSince1970), .text(Self.normalizeTags(b.tags).joined(separator: ","))])63 }6465 /// Deletes a bookmark; deleting a folder deletes its contents (foreign-key cascade).66 func delete(id: String) { _ = try? db.execute("DELETE FROM bookmarks WHERE id = ?", [.text(id)]) }6768 func deleteAll() { _ = try? db.execute("DELETE FROM bookmarks") }6970 /// Moves `id` under `parentID` at `index`. Moving a folder into itself or one of its descendants is refused.71 @discardableResult72 func move(id: String, toParent parentID: String?, at index: Int? = nil) -> Bool {73 if let parentID {74 if parentID == id { return false }75 var cursor: String? = parentID76 var guardCount = 077 while let current = cursor, guardCount < 1000 {78 if current == id { return false }79 cursor = bookmark(id: current)?.parentID80 guardCount += 181 }82 guard bookmark(id: parentID)?.isFolder == true else { return false }83 }84 var siblings = children(of: parentID).filter { $0.id != id }.map(\.id)85 siblings.insert(id, at: min(max(index ?? siblings.count, 0), siblings.count))86 do {87 try db.transaction {88 try db.execute("UPDATE bookmarks SET parent_id = ? WHERE id = ?", [parentID.map(SQLValue.text) ?? .null, .text(id)])89 for (position, sibling) in siblings.enumerated() {90 try db.execute("UPDATE bookmarks SET position = ? WHERE id = ?", [.int(Int64(position)), .text(sibling)])91 }92 }93 return true94 } catch { return false }95 }9697 func bookmark(id: String) -> Bookmark? {98 rows("SELECT * FROM bookmarks WHERE id = ?", [.text(id)]).first99 }100101 func children(of parentID: String?) -> [Bookmark] {102 if let parentID {103 return rows("SELECT * FROM bookmarks WHERE parent_id = ? ORDER BY position, created_at", [.text(parentID)])104 }105 return rows("SELECT * FROM bookmarks WHERE parent_id IS NULL ORDER BY position, created_at", [])106 }107108 func all() -> [Bookmark] { rows("SELECT * FROM bookmarks ORDER BY parent_id, position, created_at", []) }109110 func folders() -> [Bookmark] { rows("SELECT * FROM bookmarks WHERE is_folder = 1 ORDER BY title COLLATE NOCASE", []) }111112 func tree(from parentID: String? = nil) -> [BookmarkNode] {113 children(of: parentID).map { BookmarkNode(bookmark: $0, children: $0.isFolder ? tree(from: $0.id) : []) }114 }115116 /// Matches title, URL and tags; `#tag` restricts to an exact tag.117 func search(_ text: String, limit: Int = 100) -> [Bookmark] {118 let needle = text.trimmingCharacters(in: .whitespaces).lowercased()119 guard !needle.isEmpty else { return rows("SELECT * FROM bookmarks WHERE is_folder = 0 ORDER BY created_at DESC LIMIT ?", [.int(Int64(limit))]) }120 if needle.hasPrefix("#") {121 let tag = String(needle.dropFirst())122 return rows("SELECT * FROM bookmarks WHERE is_folder = 0 ORDER BY created_at DESC", []).filter { $0.tags.contains(tag) }.prefix(limit).map { $0 }123 }124 let pattern = "%" + sqlLikeEscape(needle) + "%"125 return rows("""126 SELECT * FROM bookmarks WHERE is_folder = 0 AND127 (lower(title) LIKE ? ESCAPE '\\' OR lower(url) LIKE ? ESCAPE '\\' OR tags LIKE ? ESCAPE '\\')128 ORDER BY created_at DESC LIMIT ?129 """, [.text(pattern), .text(pattern), .text(pattern), .int(Int64(limit))])130 }131132 func bookmarks(forURL url: String) -> [Bookmark] {133 rows("SELECT * FROM bookmarks WHERE is_folder = 0 AND url = ?", [.text(url)])134 }135136 func isBookmarked(_ url: String) -> Bool { !bookmarks(forURL: url).isEmpty }137138 func allTags() -> [String] {139 Array(Set(rows("SELECT * FROM bookmarks WHERE tags != ''", []).flatMap(\.tags))).sorted()140 }141142 /// Inserts an imported tree under `parentID`, returning how many bookmarks (not folders) were added.143 @discardableResult144 func importNodes(_ nodes: [BookmarkNode], under parentID: String? = nil) -> Int {145 var count = 0146 for node in nodes {147 let b = node.bookmark148 guard let created = add(title: b.title, url: b.isFolder ? nil : b.url, parentID: parentID, isFolder: b.isFolder,149 tags: b.tags, createdAt: b.createdAt) else { continue }150 if b.isFolder { count += importNodes(node.children, under: created.id) } else { count += 1 }151 }152 return count153 }154155 private func nextPosition(in parentID: String?) -> Int {156 let rows: [[String: SQLValue]]157 if let parentID {158 rows = (try? db.query("SELECT COALESCE(MAX(position), -1) + 1 AS p FROM bookmarks WHERE parent_id = ?", [.text(parentID)])) ?? []159 } else {160 rows = (try? db.query("SELECT COALESCE(MAX(position), -1) + 1 AS p FROM bookmarks WHERE parent_id IS NULL")) ?? []161 }162 return Int(rows.first?["p"]?.int ?? 0)163 }164165 private func rows(_ sql: String, _ params: [SQLValue]) -> [Bookmark] {166 ((try? db.query(sql, params)) ?? []).map { row in167 Bookmark(id: row["id"]?.string ?? "", parentID: row["parent_id"]?.string, isFolder: (row["is_folder"]?.int ?? 0) != 0,168 title: row["title"]?.string ?? "", url: row["url"]?.string,169 tags: (row["tags"]?.string ?? "").split(separator: ",").map(String.init),170 position: Int(row["position"]?.int ?? 0),171 createdAt: Date(timeIntervalSince1970: row["created_at"]?.double ?? 0))172 }173 }174}175176/// Reads and writes the Netscape bookmark file format understood by Safari, Chrome, Firefox and Edge.177enum NetscapeBookmarkCodec {178 static func export(_ nodes: [BookmarkNode]) -> String {179 var out = """180 <!DOCTYPE NETSCAPE-Bookmark-file-1>181 <!-- This is an automatically generated file. -->182 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">183 <TITLE>Bookmarks</TITLE>184 <H1>Bookmarks</H1>185 <DL><p>186187 """188 write(nodes, indent: 1, into: &out)189 out += "</DL><p>\n"190 return out191 }192193 private static func write(_ nodes: [BookmarkNode], indent: Int, into out: inout String) {194 let pad = String(repeating: " ", count: indent)195 for node in nodes {196 let b = node.bookmark197 let date = Int(b.createdAt.timeIntervalSince1970)198 if b.isFolder {199 out += "\(pad)<DT><H3 ADD_DATE=\"\(date)\">\(escape(b.title))</H3>\n\(pad)<DL><p>\n"200 write(node.children, indent: indent + 1, into: &out)201 out += "\(pad)</DL><p>\n"202 } else if let url = b.url {203 let tags = b.tags.isEmpty ? "" : " TAGS=\"\(escape(b.tags.joined(separator: ",")))\""204 out += "\(pad)<DT><A HREF=\"\(escape(url))\" ADD_DATE=\"\(date)\"\(tags)>\(escape(b.title))</A>\n"205 }206 }207 }208209 /// Tolerant parser: handles unclosed tags, mixed case and unknown attributes. Only http(s), file and ftp links are kept.210 static func parse(_ html: String) -> [BookmarkNode] {211 var stack: [[BookmarkNode]] = [[]]212 var pendingFolders: [Bookmark] = []213 var folderAwaitingList: Bookmark?214 let scanner = Scanner(string: html)215 scanner.charactersToBeSkipped = nil216 scanner.caseSensitive = false217218 func closeFolder() {219 guard stack.count > 1, let folder = pendingFolders.popLast() else { return }220 let children = stack.removeLast()221 stack[stack.count - 1].append(BookmarkNode(bookmark: folder, children: children))222 }223224 while !scanner.isAtEnd {225 _ = scanner.scanUpToString("<")226 guard scanner.scanString("<") != nil else { break }227 guard let tagBody = scanner.scanUpToString(">") else { break }228 _ = scanner.scanString(">")229 let lower = tagBody.lowercased()230 if lower.hasPrefix("h3") {231 let title = unescape(scanner.scanUpToString("<") ?? "")232 folderAwaitingList = Bookmark(id: UUID().uuidString, parentID: nil, isFolder: true, title: title, url: nil,233 tags: [], position: 0, createdAt: date(from: attribute("add_date", in: tagBody)))234 } else if lower.hasPrefix("dl") {235 if let folder = folderAwaitingList {236 pendingFolders.append(folder)237 stack.append([])238 folderAwaitingList = nil239 }240 } else if lower.hasPrefix("/dl") {241 closeFolder()242 } else if lower.hasPrefix("a ") || lower.hasPrefix("a\n") || lower.hasPrefix("a\t") {243 let title = unescape(scanner.scanUpToString("<") ?? "")244 guard let href = attribute("href", in: tagBody).map(unescape), let url = URL(string: href),245 let scheme = url.scheme?.lowercased(), ["http", "https", "file", "ftp"].contains(scheme) else { continue }246 let tags = (attribute("tags", in: tagBody).map(unescape) ?? "").split(separator: ",").map(String.init)247 let bookmark = Bookmark(id: UUID().uuidString, parentID: nil, isFolder: false,248 title: title.isEmpty ? href : title, url: href, tags: BookmarkStore.normalizeTags(tags),249 position: 0, createdAt: date(from: attribute("add_date", in: tagBody)))250 stack[stack.count - 1].append(BookmarkNode(bookmark: bookmark, children: []))251 }252 }253 while stack.count > 1 { closeFolder() }254 return stack.first ?? []255 }256257 private static func attribute(_ name: String, in tag: String) -> String? {258 let lower = tag.lowercased()259 var searchRange = lower.startIndex..<lower.endIndex260 while let range = lower.range(of: name + "=", range: searchRange) {261 // Must be preceded by whitespace so that "data-href=" does not match "href=".262 if range.lowerBound > lower.startIndex, !lower[lower.index(before: range.lowerBound)].isWhitespace {263 searchRange = range.upperBound..<lower.endIndex264 continue265 }266 let start = tag.index(tag.startIndex, offsetBy: lower.distance(from: lower.startIndex, to: range.upperBound))267 let rest = tag[start...]268 guard let quote = rest.first else { return nil }269 if quote == "\"" || quote == "'" {270 let body = rest.dropFirst()271 guard let end = body.firstIndex(of: quote) else { return String(body) }272 return String(body[..<end])273 }274 return String(rest.prefix { !$0.isWhitespace })275 }276 return nil277 }278279 private static func date(from value: String?) -> Date {280 guard let value, let seconds = TimeInterval(value), seconds > 0 else { return Date() }281 return Date(timeIntervalSince1970: seconds)282 }283284 static func escape(_ text: String) -> String {285 text.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<")286 .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)287 }288289 static func unescape(_ text: String) -> String {290 text.trimmingCharacters(in: .whitespacesAndNewlines)291 .replacingOccurrences(of: "<", with: "<").replacingOccurrences(of: ">", with: ">")292 .replacingOccurrences(of: """, with: "\"").replacingOccurrences(of: "'", with: "'")293 .replacingOccurrences(of: "'", with: "'").replacingOccurrences(of: "&", with: "&")294 }295}296