Repository Public
1import Foundation23/// Keeps the sync mirror and the profile's history table in step, by comparison rather than by hooks:4/// the profile database stays the single place history is written, and private windows (which never write to it)5/// can never leak into the mirror.6struct HistorySyncBridge: Sendable {7 let history: HistoryStore8 let mirror: SyncDatabase9 /// Only this many of the most recent pages are synchronized.10 var limit = 40001112 /// Local → mirror: new or updated visits since the last capture, and deletions.13 func captureLocalChanges() {14 let since = mirror.meta("history.capturedAt").flatMap(Double.init).map(Date.init(timeIntervalSince1970:)) ?? .distantPast15 let now = Date()16 for page in history.aggregates(since: since, limit: limit) {17 let existing: HistorySyncItem? = mirror.value(SyncCollection.history, key: page.url)18 if let existing, existing.lastVisit >= page.lastVisit.addingTimeInterval(-0.001) { continue }19 // Visits made here since the mirrored state add to the count other devices already reported.20 let count = existing.map { $0.visitCount + max(1, history.visitCount(url: page.url, after: $0.lastVisit)) } ?? page.visitCount21 mirror.put(SyncCollection.history, key: page.url,22 value: HistorySyncItem(url: page.url, title: page.title.isEmpty ? (existing?.title ?? "") : page.title, lastVisit: page.lastVisit, visitCount: count),23 modifiedAt: page.lastVisit)24 }25 // A mirrored page that was in the local history and no longer is was deleted by the user.26 // One that never reached the local history (the app stopped between a pull and its application) is applied now instead.27 let present = history.allURLs()28 let known = knownKeys()29 for record in mirror.records(SyncCollection.history) where !present.contains(record.key) {30 if known.contains(record.key) {31 mirror.remove(SyncCollection.history, key: record.key, at: now)32 } else if let item = try? SyncDatabase.decoder.decode(HistorySyncItem.self, from: record.json), let url = URL(string: item.url), HistoryStore.isRecordable(url) {33 history.insertSynced(url: item.url, title: item.title, at: item.lastVisit)34 }35 }36 mirror.setMeta("history.capturedAt", String(now.timeIntervalSince1970))37 rememberKnown()38 }3940 /// Mirror → local, after a pull changed the history collection.41 func applyRemoteChanges() {42 let mirrored = Dictionary(uniqueKeysWithValues: mirror.values(SyncCollection.history, as: HistorySyncItem.self).map { ($0.url, $0) })43 // Deleted elsewhere: the mirror no longer has the record, and the page was captured before, so remove it here.44 for url in knownKeys() where mirrored[url] == nil { history.delete(url: url) }45 for item in mirrored.values {46 guard let url = URL(string: item.url), HistoryStore.isRecordable(url) else { continue }47 let last = history.lastVisit(url: item.url)48 if last == nil || last! < item.lastVisit.addingTimeInterval(-1) {49 history.insertSynced(url: item.url, title: item.title, at: item.lastVisit)50 }51 }52 rememberKnown()53 }5455 private func knownKeys() -> Set<String> { Set((mirror.meta("history.known") ?? "").split(separator: "\n").map(String.init)) }5657 /// Records which pages the mirror holds, so a later disappearance can be told apart from "never synchronized".58 func rememberKnown() {59 mirror.setMeta("history.known", mirror.records(SyncCollection.history).map(\.key).joined(separator: "\n"))60 }61}6263/// Same idea for bookmarks: the profile database is authoritative locally, the mirror carries changes both ways.64struct BookmarkSyncBridge: Sendable {65 let bookmarks: BookmarkStore66 let mirror: SyncDatabase6768 private func item(_ b: Bookmark) -> BookmarkSyncItem {69 BookmarkSyncItem(id: b.id, parentID: b.parentID, isFolder: b.isFolder, title: b.title, url: b.url, tags: b.tags, position: b.position, createdAt: b.createdAt)70 }7172 func captureLocalChanges() {73 let local = bookmarks.all()74 let localIDs = Set(local.map(\.id))75 for bookmark in local {76 let current = item(bookmark)77 let existing: BookmarkSyncItem? = mirror.value(SyncCollection.bookmarks, key: bookmark.id)78 if existing != current { mirror.put(SyncCollection.bookmarks, key: bookmark.id, value: current) }79 }80 // Only bookmarks that were here before count as deleted by the user; ones pulled but not yet applied are left for `applyRemoteChanges`.81 let known = Set((mirror.meta("bookmarks.known") ?? "").split(separator: "\n").map(String.init))82 var unapplied = false83 for record in mirror.records(SyncCollection.bookmarks) where !localIDs.contains(record.key) {84 if known.contains(record.key) { mirror.remove(SyncCollection.bookmarks, key: record.key) } else { unapplied = true }85 }86 if unapplied { applyRemoteChanges() } else { rememberKnown() }87 }8889 private func rememberKnown() {90 mirror.setMeta("bookmarks.known", mirror.records(SyncCollection.bookmarks).map(\.key).joined(separator: "\n"))91 }9293 func applyRemoteChanges() {94 let remote = mirror.values(SyncCollection.bookmarks, as: BookmarkSyncItem.self)95 let remoteIDs = Set(remote.map(\.id))96 for bookmark in bookmarks.all() where !remoteIDs.contains(bookmark.id) { bookmarks.delete(id: bookmark.id) }97 let existing = Dictionary(uniqueKeysWithValues: bookmarks.all().map { ($0.id, $0) })98 // Parents before children: folders first, then by depth as far as the data allows.99 var pending = remote.sorted { ($0.isFolder ? 0 : 1, $0.position) < ($1.isFolder ? 0 : 1, $1.position) }100 var inserted = Set(existing.keys)101 var progress = true102 while !pending.isEmpty, progress {103 progress = false104 var later: [BookmarkSyncItem] = []105 for entry in pending {106 // A parent that is missing everywhere (deleted on another device) moves the bookmark to the top level.107 let parent = entry.parentID.flatMap { remoteIDs.contains($0) ? $0 : nil }108 if let parent, !inserted.contains(parent) { later.append(entry); continue }109 bookmarks.upsertSynced(Bookmark(id: entry.id, parentID: parent, isFolder: entry.isFolder, title: entry.title, url: entry.url,110 tags: entry.tags, position: entry.position, createdAt: entry.createdAt))111 inserted.insert(entry.id)112 progress = true113 }114 pending = later115 }116 rememberKnown()117 }118}119120/// Favorites, reading list, search history, preferences and tabs of other devices: the mirror is their store.121struct SyncedLibrary: Sendable {122 let mirror: SyncDatabase123124 // Favorites125 func favorites() -> [FavoriteItem] { mirror.values(SyncCollection.favorites, as: FavoriteItem.self).sorted { ($0.position, $0.title) < ($1.position, $1.title) } }126 func isFavorite(_ url: String) -> Bool { favorites().contains { $0.url == url } }127 @discardableResult128 func addFavorite(title: String, url: String) -> FavoriteItem {129 if let existing = favorites().first(where: { $0.url == url }) { return existing }130 let item = FavoriteItem(title: title.isEmpty ? (URL(string: url)?.host ?? url) : title, url: url, position: (favorites().map(\.position).max() ?? -1) + 1)131 mirror.put(SyncCollection.favorites, key: item.id, value: item)132 return item133 }134 func removeFavorite(url: String) { favorites().filter { $0.url == url }.forEach { mirror.remove(SyncCollection.favorites, key: $0.id) } }135 func update(_ favorite: FavoriteItem) { mirror.put(SyncCollection.favorites, key: favorite.id, value: favorite) }136137 // Reading list138 func readingList() -> [ReadingItem] { mirror.values(SyncCollection.reading, as: ReadingItem.self).sorted { $0.addedAt > $1.addedAt } }139 func isInReadingList(_ url: String) -> Bool { mirror.record(SyncCollection.reading, key: url).map { !$0.deleted } ?? false }140 func addToReadingList(title: String, url: String) { mirror.put(SyncCollection.reading, key: url, value: ReadingItem(url: url, title: title)) }141 func setRead(_ item: ReadingItem, _ read: Bool) { var copy = item; copy.isRead = read; mirror.put(SyncCollection.reading, key: item.url, value: copy) }142 func removeFromReadingList(url: String) { mirror.remove(SyncCollection.reading, key: url) }143144 // Search history145 func recentSearches(limit: Int = 12) -> [SearchHistoryItem] {146 Array(mirror.values(SyncCollection.searches, as: SearchHistoryItem.self).sorted { $0.lastUsed > $1.lastUsed }.prefix(limit))147 }148 /// Past queries containing `text`, the most used first — the source of query suggestions.149 func searchSuggestions(for text: String, limit: Int = 5) -> [SearchHistoryItem] {150 let needle = SearchHighlighter.fold(text.trimmingCharacters(in: .whitespaces))151 guard !needle.isEmpty else { return [] }152 let all = mirror.values(SyncCollection.searches, as: SearchHistoryItem.self)153 let matches = all.filter { SearchHighlighter.fold($0.query).contains(needle) && SearchHighlighter.fold($0.query) != needle }154 return Array(matches.sorted {155 let a = SearchHighlighter.fold($0.query).hasPrefix(needle), b = SearchHighlighter.fold($1.query).hasPrefix(needle)156 return a != b ? a : ($0.count, $0.lastUsed) > ($1.count, $1.lastUsed)157 }.prefix(limit))158 }159 /// Past queries sharing a term with `query` (shown as "related from your searches"; never invented).160 func relatedSearches(to query: String, limit: Int = 6) -> [String] {161 let terms = Set(SearchHighlighter.terms(in: query))162 guard !terms.isEmpty else { return [] }163 let folded = SearchHighlighter.fold(query)164 return Array(mirror.values(SyncCollection.searches, as: SearchHistoryItem.self)165 .filter { SearchHighlighter.fold($0.query) != folded && !terms.isDisjoint(with: SearchHighlighter.terms(in: $0.query)) }166 .sorted { $0.lastUsed > $1.lastUsed }.prefix(limit).map(\.query))167 }168 func recordSearch(_ query: String) {169 let text = SearchQuery.normalize(query)170 guard !text.isEmpty else { return }171 let key = text.lowercased()172 let existing: SearchHistoryItem? = mirror.value(SyncCollection.searches, key: key)173 mirror.put(SyncCollection.searches, key: key, value: SearchHistoryItem(query: text, lastUsed: Date(), count: (existing?.count ?? 0) + 1))174 }175 func removeSearch(_ item: SearchHistoryItem) { mirror.remove(SyncCollection.searches, key: item.query.lowercased()) }176 func clearSearches() { mirror.removeAll(SyncCollection.searches) }177178 // Preferences179 func preferences() -> SyncedPreferences { mirror.value(SyncCollection.prefs, key: "prefs") ?? SyncedPreferences() }180 func setPreferences(_ value: SyncedPreferences) { if value != preferences() { mirror.put(SyncCollection.prefs, key: "prefs", value: value) } }181182 // Tabs183 /// Publishes this device's open tabs. Callers pass regular windows only: private tabs are never given to this method.184 func publishTabs(_ tabs: [RemoteTab], closed: [RemoteTab], deviceID: String, deviceName: String, platform: String) {185 let open = DeviceTabs(deviceID: deviceID, deviceName: deviceName, platform: platform, tabs: Array(tabs.prefix(200)))186 if let current: DeviceTabs = mirror.value(SyncCollection.tabs, key: deviceID), current.tabs == open.tabs, current.deviceName == deviceName {} else {187 mirror.put(SyncCollection.tabs, key: deviceID, value: open)188 }189 let recentlyClosed = DeviceTabs(deviceID: deviceID, deviceName: deviceName, platform: platform, tabs: Array(closed.prefix(25)))190 let currentClosed: DeviceTabs? = mirror.value(SyncCollection.closed, key: deviceID)191 if currentClosed?.tabs == recentlyClosed.tabs || (currentClosed == nil && closed.isEmpty) {} else {192 mirror.put(SyncCollection.closed, key: deviceID, value: recentlyClosed)193 }194 }195 /// Tabs open on the user's other devices, most recently active device first.196 func otherDevicesTabs(excluding deviceID: String?) -> [DeviceTabs] {197 mirror.values(SyncCollection.tabs, as: DeviceTabs.self).filter { $0.deviceID != deviceID && !$0.tabs.isEmpty }.sorted { $0.updatedAt > $1.updatedAt }198 }199 func otherDevicesClosedTabs(excluding deviceID: String?) -> [DeviceTabs] {200 mirror.values(SyncCollection.closed, as: DeviceTabs.self).filter { $0.deviceID != deviceID && !$0.tabs.isEmpty }.sorted { $0.updatedAt > $1.updatedAt }201 }202}203