SPB Git

Repository Public

HistoryStore.swift 7.7 KB 166 lines swift

1import Foundation23struct HistoryEntry: Identifiable, Equatable, Sendable {4    var id: Int645    var url: String6    var title: String7    var visitedAt: Date8}910/// A page aggregated over its visits, used for suggestions and "top sites".11struct HistorySuggestion: Equatable, Sendable {12    var url: String13    var title: String14    var visitCount: Int15    var lastVisit: Date16}1718final class HistoryStore: Sendable {19    private let db: SQLiteDatabase20    init(db: SQLiteDatabase) { self.db = db }2122    /// Only real web pages are recorded; internal, local-file and data URLs are not.23    static func isRecordable(_ url: URL) -> Bool {24        guard let scheme = url.scheme?.lowercased() else { return false }25        return scheme == "http" || scheme == "https"26    }2728    @discardableResult29    func record(url: URL, title: String, at date: Date = Date()) -> Bool {30        guard Self.isRecordable(url) else { return false }31        let text = url.absoluteString32        // Collapse reloads and rapid redirects back to the same address into one visit.33        if let last = try? db.query("SELECT id, url, visited_at FROM history ORDER BY id DESC LIMIT 1").first,34           last["url"]?.string == text, let when = last["visited_at"]?.double, date.timeIntervalSince1970 - when < 30,35           let id = last["id"]?.int {36            _ = try? db.execute("UPDATE history SET visited_at = ?, title = CASE WHEN ? = '' THEN title ELSE ? END WHERE id = ?",37                                [.double(date.timeIntervalSince1970), .text(title), .text(title), .int(id)])38            return true39        }40        return (try? db.execute("INSERT INTO history(url, title, visited_at) VALUES(?,?,?)",41                                [.text(text), .text(title), .double(date.timeIntervalSince1970)])) != nil42    }4344    func updateTitle(_ title: String, for url: URL) {45        guard !title.isEmpty else { return }46        _ = try? db.execute(47            "UPDATE history SET title = ? WHERE id = (SELECT id FROM history WHERE url = ? ORDER BY id DESC LIMIT 1)",48            [.text(title), .text(url.absoluteString)])49    }5051    func recent(limit: Int = 200, offset: Int = 0) -> [HistoryEntry] {52        rows("SELECT id, url, title, visited_at FROM history ORDER BY visited_at DESC, id DESC LIMIT ? OFFSET ?",53             [.int(Int64(limit)), .int(Int64(offset))])54    }5556    func search(_ text: String, limit: Int = 200) -> [HistoryEntry] {57        let needle = text.trimmingCharacters(in: .whitespaces)58        guard !needle.isEmpty else { return recent(limit: limit) }59        let pattern = "%" + sqlLikeEscape(needle) + "%"60        return rows("""61            SELECT id, url, title, visited_at FROM history62            WHERE url LIKE ? ESCAPE '\\' OR title LIKE ? ESCAPE '\\'63            ORDER BY visited_at DESC, id DESC LIMIT ?64            """, [.text(pattern), .text(pattern), .int(Int64(limit))])65    }6667    /// Pages matching `text`, most visited first — the source of address-bar suggestions.68    func suggestions(for text: String, limit: Int = 6) -> [HistorySuggestion] {69        let needle = text.trimmingCharacters(in: .whitespaces)70        guard !needle.isEmpty else { return [] }71        let pattern = "%" + sqlLikeEscape(needle) + "%"72        return aggregate("""73            SELECT url, MAX(title) AS title, COUNT(*) AS visits, MAX(visited_at) AS last FROM history74            WHERE url LIKE ? ESCAPE '\\' OR title LIKE ? ESCAPE '\\'75            GROUP BY url ORDER BY visits DESC, last DESC LIMIT ?76            """, [.text(pattern), .text(pattern), .int(Int64(limit))])77    }7879    func topSites(limit: Int = 8) -> [HistorySuggestion] {80        aggregate("""81            SELECT url, MAX(title) AS title, COUNT(*) AS visits, MAX(visited_at) AS last FROM history82            GROUP BY url ORDER BY visits DESC, last DESC LIMIT ?83            """, [.int(Int64(limit))])84    }8586    func delete(id: Int64) { _ = try? db.execute("DELETE FROM history WHERE id = ?", [.int(id)]) }8788    /// Removes every visit to `host` and its sub-domains. Returns the number of rows removed.89    @discardableResult90    func delete(host: String) -> Int {91        let h = sqlLikeEscape(host.lowercased())92        var removed = 093        for scheme in ["http", "https"] {94            for pattern in ["\(scheme)://\(h)", "\(scheme)://\(h)/%", "\(scheme)://\(h):%", "\(scheme)://%.\(h)", "\(scheme)://%.\(h)/%", "\(scheme)://%.\(h):%"] {95                removed += (try? db.execute("DELETE FROM history WHERE lower(url) LIKE ? ESCAPE '\\'", [.text(pattern)])) ?? 096            }97        }98        return removed99    }100101    /// Clears visits newer than `since`, or everything when `since` is `nil`.102    @discardableResult103    func clear(since: Date? = nil) -> Int {104        if let since {105            return (try? db.execute("DELETE FROM history WHERE visited_at >= ?", [.double(since.timeIntervalSince1970)])) ?? 0106        }107        return (try? db.execute("DELETE FROM history")) ?? 0108    }109110    // MARK: Aggregates used by synchronization111112    /// One row per address visited since `since`, with its latest title and visit.113    func aggregates(since: Date, limit: Int = 5000) -> [HistorySuggestion] {114        aggregate("""115            SELECT url, (SELECT h2.title FROM history h2 WHERE h2.url = history.url ORDER BY h2.visited_at DESC LIMIT 1) AS title,116                   COUNT(*) AS visits, MAX(visited_at) AS last FROM history117            GROUP BY url HAVING MAX(visited_at) > ? ORDER BY last DESC LIMIT ?118            """, [.double(since.timeIntervalSince1970), .int(Int64(limit))])119    }120121    func visitCount(url: String, after date: Date) -> Int {122        Int((try? db.query("SELECT COUNT(*) AS n FROM history WHERE url = ? AND visited_at > ?", [.text(url), .double(date.timeIntervalSince1970)]).first?["n"]?.int).flatMap { $0 } ?? 0)123    }124125    func lastVisit(url: String) -> Date? {126        (try? db.query("SELECT MAX(visited_at) AS last FROM history WHERE url = ?", [.text(url)]).first?["last"]?.double).flatMap { $0 }.map(Date.init(timeIntervalSince1970:))127    }128129    func allURLs() -> Set<String> {130        Set(((try? db.query("SELECT DISTINCT url FROM history")) ?? []).compactMap { $0["url"]?.string })131    }132133    @discardableResult134    func delete(url: String) -> Int { (try? db.execute("DELETE FROM history WHERE url = ?", [.text(url)])) ?? 0 }135136    /// Inserts a visit that happened on another device (no collapsing with recent local visits).137    func insertSynced(url: String, title: String, at date: Date) {138        _ = try? db.execute("INSERT INTO history(url, title, visited_at) VALUES(?,?,?)", [.text(url), .text(title), .double(date.timeIntervalSince1970)])139    }140141    /// Most recently visited distinct pages.142    func recentPages(limit: Int = 12) -> [HistorySuggestion] {143        aggregate("""144            SELECT url, MAX(title) AS title, COUNT(*) AS visits, MAX(visited_at) AS last FROM history145            GROUP BY url ORDER BY last DESC LIMIT ?146            """, [.int(Int64(limit))])147    }148149    var count: Int { Int((try? db.query("SELECT COUNT(*) AS n FROM history").first?["n"]?.int).flatMap { $0 } ?? 0) }150151    private func rows(_ sql: String, _ params: [SQLValue]) -> [HistoryEntry] {152        ((try? db.query(sql, params)) ?? []).map { row in153            HistoryEntry(id: row["id"]?.int ?? 0, url: row["url"]?.string ?? "", title: row["title"]?.string ?? "",154                         visitedAt: Date(timeIntervalSince1970: row["visited_at"]?.double ?? 0))155        }156    }157158    private func aggregate(_ sql: String, _ params: [SQLValue]) -> [HistorySuggestion] {159        ((try? db.query(sql, params)) ?? []).map { row in160            HistorySuggestion(url: row["url"]?.string ?? "", title: row["title"]?.string ?? "",161                              visitCount: Int(row["visits"]?.int ?? 0),162                              lastVisit: Date(timeIntervalSince1970: row["last"]?.double ?? 0))163        }164    }165}166
Files main
Menu

Theme