Repository Public License
1import Foundation2import NavigatorCore34/// A bookmark with its children, as returned by `BookmarkStore.tree`.5public struct BookmarkNode: Sendable, Hashable, Identifiable {6 public var bookmark: Bookmark7 public var children: [BookmarkNode]8 public var id: BookmarkID { bookmark.id }9}1011public struct BookmarkImportReport: Sendable, Hashable {12 public var foldersCreated: Int13 public var linksCreated: Int14 /// Links of the file that were not imported (bookmarklets, `place:` queries, unparsable URLs).15 public var linksSkipped: Int16}1718enum BookmarkSQL {19 /// Every bookmark query selects through this, so `Bookmark(row:)` always finds `tags_json`.20 static let select = """21 SELECT b.*, (SELECT json_group_array(tag) FROM22 (SELECT tag FROM bookmark_tags t WHERE t.bookmark_id = b.id ORDER BY t.position)) AS tags_json23 FROM bookmarks b24 """2526 static func nextOrder(_ connection: SQLiteConnection, profile: ProfileID, parent: BookmarkID?) throws -> Int {27 try connection.scalar("SELECT max(sort_order) + 1 FROM bookmarks WHERE profile_id = ? AND parent_id IS ?",28 [profile, parent], as: Int.self) ?? 029 }3031 static func validate(_ bookmark: Bookmark, _ context: StoreContext, _ connection: SQLiteConnection) throws {32 try context.requireProfile(bookmark.profileID, connection)33 if bookmark.kind == .link, bookmark.url == nil {34 throw PersistenceError.conflict("a link bookmark needs a URL")35 }36 guard let parent = bookmark.parentID else { return }37 guard parent != bookmark.id else { throw PersistenceError.conflict("a bookmark cannot be its own parent") }38 guard let row = try connection.queryOne("SELECT kind, profile_id FROM bookmarks WHERE id = ?", [parent]) else {39 throw PersistenceError.notFound(entity: "bookmark folder", id: parent.string)40 }41 guard try row.get("kind", as: String.self) == Bookmark.Kind.folder.rawValue else {42 throw PersistenceError.conflict("the parent of a bookmark must be a folder")43 }44 guard try row.get("profile_id", as: ProfileID.self) == bookmark.profileID else {45 throw PersistenceError.conflict("a bookmark and its folder must belong to the same profile")46 }47 }4849 /// True when `candidate` is `ancestor` or lies below it.50 static func isDescendant(_ candidate: BookmarkID, of ancestor: BookmarkID, _ connection: SQLiteConnection) throws -> Bool {51 try connection.scalar("""52 WITH RECURSIVE chain(id) AS (53 SELECT ?1 UNION ALL54 SELECT b.parent_id FROM bookmarks b JOIN chain ON b.id = chain.id WHERE b.parent_id IS NOT NULL55 ) SELECT 1 FROM chain WHERE id = ?2 LIMIT 156 """, [candidate, ancestor], as: Int.self) != nil57 }5859 static func renumber(_ ids: [BookmarkID], _ connection: SQLiteConnection) throws {60 for (index, id) in ids.enumerated() {61 try connection.execute("UPDATE bookmarks SET sort_order = ? WHERE id = ?", [index, id])62 }63 }64}6566/// Bookmarks: a tree of folders and links per profile, with favourites and tags.67public struct BookmarkStore: Sendable {68 let context: StoreContext6970 // MARK: Writing7172 /// Inserts or updates a bookmark exactly as given (including `order`). The parent must be a folder of the73 /// same profile.74 public func save(_ bookmark: Bookmark) async throws {75 try await context.transaction { connection in76 try BookmarkSQL.validate(bookmark, context, connection)77 if let parent = bookmark.parentID, bookmark.kind == .folder,78 try BookmarkSQL.isDescendant(parent, of: bookmark.id, connection) {79 throw PersistenceError.conflict("a folder cannot be moved into itself")80 }81 try bookmark.save(connection)82 }83 }8485 /// Adds a new bookmark after its last sibling and returns it with the `order` it received.86 @discardableResult87 public func append(_ bookmark: Bookmark) async throws -> Bookmark {88 try await context.transaction { connection in89 try BookmarkSQL.validate(bookmark, context, connection)90 var stored = bookmark91 stored.order = try BookmarkSQL.nextOrder(connection, profile: bookmark.profileID, parent: bookmark.parentID)92 try stored.save(connection)93 return stored94 }95 }9697 /// Moves a bookmark or folder under `parent` (`nil` = top level) at `index` among its new siblings98 /// (`nil` or out of range = last) and renumbers them. Moving a folder into its own subtree is refused.99 public func move(_ id: BookmarkID, to parent: BookmarkID?, index: Int? = nil, at date: Date = .now) async throws {100 try await context.transaction { connection in101 guard let row = try connection.queryOne("SELECT profile_id FROM bookmarks WHERE id = ?", [id]) else {102 throw PersistenceError.notFound(entity: "bookmark", id: id.string)103 }104 let profile: ProfileID = try row.get("profile_id")105 if let parent {106 guard let parentRow = try connection.queryOne("SELECT kind, profile_id FROM bookmarks WHERE id = ?",107 [parent]) else {108 throw PersistenceError.notFound(entity: "bookmark folder", id: parent.string)109 }110 guard try parentRow.get("kind", as: String.self) == Bookmark.Kind.folder.rawValue,111 try parentRow.get("profile_id", as: ProfileID.self) == profile else {112 throw PersistenceError.conflict("the destination must be a folder of the same profile")113 }114 guard try !BookmarkSQL.isDescendant(parent, of: id, connection) else {115 throw PersistenceError.conflict("a folder cannot be moved into itself")116 }117 }118 var siblings: [BookmarkID] = try connection.query("""119 SELECT id FROM bookmarks WHERE profile_id = ? AND parent_id IS ? AND id <> ? ORDER BY sort_order, created_at, id120 """, [profile, parent, id]).map { try $0.get("id") }121 siblings.insert(id, at: min(max(index ?? siblings.count, 0), siblings.count))122 try connection.execute("UPDATE bookmarks SET parent_id = ?, updated_at = ? WHERE id = ?", [parent, date, id])123 try BookmarkSQL.renumber(siblings, connection)124 }125 }126127 /// Rewrites the order of the children of `parent` to match `ids`; children not listed follow, in their128 /// previous order.129 public func reorder(parent: BookmarkID?, profile: ProfileID, _ ids: [BookmarkID]) async throws {130 try await context.transaction { connection in131 let current: [BookmarkID] = try connection.query("""132 SELECT id FROM bookmarks WHERE profile_id = ? AND parent_id IS ? ORDER BY sort_order, created_at, id133 """, [profile, parent]).map { try $0.get("id") }134 let known = Set(current)135 let listed = ids.filter(known.contains)136 let listedSet = Set(listed)137 try BookmarkSQL.renumber(listed + current.filter { !listedSet.contains($0) }, connection)138 }139 }140141 public func setFavorite(_ id: BookmarkID, _ favorite: Bool, at date: Date = .now) async throws {142 try await context.transaction {143 _ = try $0.execute("UPDATE bookmarks SET is_favorite = ?, updated_at = ? WHERE id = ?", [favorite, date, id])144 }145 }146147 public func setTags(_ id: BookmarkID, _ tags: [String], at date: Date = .now) async throws {148 try await context.transaction { connection in149 guard let row = try connection.queryOne("\(BookmarkSQL.select) WHERE b.id = ?", [id]) else {150 throw PersistenceError.notFound(entity: "bookmark", id: id.string)151 }152 var bookmark = try Bookmark(row: row)153 bookmark.tags = tags154 bookmark.updatedAt = date155 try bookmark.save(connection)156 }157 }158159 /// Deletes a bookmark; a folder goes with everything below it. Returns the number of bookmarks deleted.160 @discardableResult161 public func delete(_ id: BookmarkID) async throws -> Int {162 try await context.transaction { connection in163 let count = try connection.scalar("""164 WITH RECURSIVE tree(id) AS (165 SELECT ?1 UNION ALL SELECT b.id FROM bookmarks b JOIN tree ON b.parent_id = tree.id166 ) SELECT count(*) FROM tree JOIN bookmarks USING (id)167 """, [id], as: Int.self) ?? 0168 try connection.execute("DELETE FROM bookmarks WHERE id = ?", [id])169 return count170 }171 }172173 // MARK: Reading174175 public func bookmark(_ id: BookmarkID) async throws -> Bookmark? {176 try await context.read { try $0.queryOne("\(BookmarkSQL.select) WHERE b.id = ?", [id]).map(Bookmark.init(row:)) }177 }178179 /// Direct children of a folder (`nil` = top level), in order.180 public func children(of parent: BookmarkID?, profile: ProfileID) async throws -> [Bookmark] {181 try await context.read { connection in182 try connection.query("""183 \(BookmarkSQL.select) WHERE b.profile_id = ? AND b.parent_id IS ? ORDER BY b.sort_order, b.created_at, b.id184 """, [profile, parent]).map(Bookmark.init(row:))185 }186 }187188 public func all(profile: ProfileID) async throws -> [Bookmark] {189 try await context.read { connection in190 try connection.query("""191 \(BookmarkSQL.select) WHERE b.profile_id = ? ORDER BY b.parent_id, b.sort_order, b.created_at, b.id192 """, [profile]).map(Bookmark.init(row:))193 }194 }195196 /// The whole bookmark tree of a profile.197 public func tree(profile: ProfileID) async throws -> [BookmarkNode] {198 Self.buildTree(try await all(profile: profile))199 }200201 static func buildTree(_ bookmarks: [Bookmark]) -> [BookmarkNode] {202 var byParent: [BookmarkID?: [Bookmark]] = [:]203 for bookmark in bookmarks { byParent[bookmark.parentID, default: []].append(bookmark) }204 func nodes(_ parent: BookmarkID?) -> [BookmarkNode] {205 (byParent[parent] ?? []).sorted { ($0.order, $0.createdAt, $0.id) < ($1.order, $1.createdAt, $1.id) }206 .map { BookmarkNode(bookmark: $0, children: $0.kind == .folder ? nodes($0.id) : []) }207 }208 return nodes(nil)209 }210211 public func favorites(profile: ProfileID) async throws -> [Bookmark] {212 try await context.read { connection in213 try connection.query("""214 \(BookmarkSQL.select) WHERE b.profile_id = ? AND b.is_favorite = 1 ORDER BY b.sort_order, b.created_at, b.id215 """, [profile]).map(Bookmark.init(row:))216 }217 }218219 public func bookmarks(taggedWith tag: String, profile: ProfileID) async throws -> [Bookmark] {220 try await context.read { connection in221 try connection.query("""222 \(BookmarkSQL.select) WHERE b.profile_id = ?223 AND b.id IN (SELECT bookmark_id FROM bookmark_tags WHERE tag = ?) ORDER BY b.title COLLATE NOCASE, b.id224 """, [profile, tag]).map(Bookmark.init(row:))225 }226 }227228 /// Every tag of a profile with the number of bookmarks carrying it, alphabetically.229 public func tags(profile: ProfileID) async throws -> [(tag: String, count: Int)] {230 try await context.read { connection in231 try connection.query("""232 SELECT t.tag AS tag, count(*) AS uses FROM bookmark_tags t JOIN bookmarks b ON b.id = t.bookmark_id233 WHERE b.profile_id = ? GROUP BY t.tag ORDER BY t.tag COLLATE NOCASE234 """, [profile]).map { (tag: try $0.get("tag"), count: try $0.get("uses")) }235 }236 }237238 /// Bookmarks pointing at a URL ("is this page bookmarked?").239 public func bookmarks(for url: URL, profile: ProfileID) async throws -> [Bookmark] {240 try await context.read { connection in241 try connection.query("\(BookmarkSQL.select) WHERE b.profile_id = ? AND b.url = ? ORDER BY b.created_at, b.id",242 [profile, url]).map(Bookmark.init(row:))243 }244 }245246 /// Case-insensitive substring search over title, URL and tags. User text is matched literally.247 public func search(_ text: String, profile: ProfileID, limit: Int = 50) async throws -> [Bookmark] {248 let needle = text.trimmingCharacters(in: .whitespacesAndNewlines)249 guard !needle.isEmpty else { return [] }250 let pattern = LikePattern.contains(needle)251 return try await context.read { connection in252 try connection.query("""253 \(BookmarkSQL.select) WHERE b.profile_id = ?1 AND (254 b.title LIKE ?2 ESCAPE '\\' OR b.url LIKE ?2 ESCAPE '\\'255 OR EXISTS (SELECT 1 FROM bookmark_tags t WHERE t.bookmark_id = b.id AND t.tag LIKE ?2 ESCAPE '\\'))256 ORDER BY b.is_favorite DESC, b.title COLLATE NOCASE, b.id LIMIT ?3257 """, [profile, pattern, limit]).map(Bookmark.init(row:))258 }259 }260261 // MARK: Netscape HTML262263 /// Imports a Netscape bookmark file under `parent` (`nil` = top level), after the existing items. The whole264 /// import is one transaction.265 @discardableResult266 public func importHTML(_ data: Data, profile: ProfileID, into parent: BookmarkID? = nil,267 at date: Date = .now) async throws -> BookmarkImportReport {268 try await importNodes(NetscapeBookmarks.parse(data: data), profile: profile, into: parent, at: date)269 }270271 @discardableResult272 public func importHTML(_ html: String, profile: ProfileID, into parent: BookmarkID? = nil,273 at date: Date = .now) async throws -> BookmarkImportReport {274 try await importNodes(NetscapeBookmarks.parse(html), profile: profile, into: parent, at: date)275 }276277 private func importNodes(_ parsed: NetscapeBookmarks.ParseResult, profile: ProfileID, into parent: BookmarkID?,278 at date: Date) async throws -> BookmarkImportReport {279 try await context.transaction { connection in280 try context.requireProfile(profile, connection)281 if let parent {282 guard try connection.scalar("SELECT 1 FROM bookmarks WHERE id = ? AND kind = 'folder' AND profile_id = ?",283 [parent, profile], as: Int.self) != nil else {284 throw PersistenceError.notFound(entity: "bookmark folder", id: parent.string)285 }286 }287 var report = BookmarkImportReport(foldersCreated: 0, linksCreated: 0, linksSkipped: parsed.skippedLinks)288 func insert(_ nodes: [BookmarkFileNode], under parent: BookmarkID?, startingAt first: Int) throws {289 for (offset, node) in nodes.enumerated() {290 let created = node.addedAt ?? date291 let bookmark = Bookmark(profileID: profile, parentID: parent,292 kind: node.kind == .folder ? .folder : .link, title: node.title,293 url: node.url, order: first + offset, tags: node.tags,294 isFavorite: node.isFavorite, createdAt: created,295 updatedAt: node.modifiedAt ?? created)296 try bookmark.save(connection)297 if node.kind == .folder {298 report.foldersCreated += 1299 try insert(node.children, under: bookmark.id, startingAt: 0)300 } else {301 report.linksCreated += 1302 }303 }304 }305 try insert(parsed.roots, under: parent,306 startingAt: try BookmarkSQL.nextOrder(connection, profile: profile, parent: parent))307 return report308 }309 }310311 /// Exports the bookmark tree of a profile as a Netscape bookmark file.312 public func exportHTML(profile: ProfileID, title: String = "Bookmarks") async throws -> String {313 func convert(_ nodes: [BookmarkNode]) -> [BookmarkFileNode] {314 nodes.map { node in315 BookmarkFileNode(kind: node.bookmark.kind == .folder ? .folder : .link, title: node.bookmark.title,316 url: node.bookmark.url, addedAt: node.bookmark.createdAt,317 modifiedAt: node.bookmark.updatedAt, tags: node.bookmark.tags,318 isFavorite: node.bookmark.isFavorite, children: convert(node.children))319 }320 }321 return NetscapeBookmarks.export(convert(try await tree(profile: profile)), title: title)322 }323}324