mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-11-28 00:04:25 +00:00
Move HTMLMetadata cache to a database.
This commit is contained in:
1 parent
5763e30110
commit
91aa17f7d2
13 files changed
+668
-280
No files matched your search
@@ -0,0 +1,146 @@
|
||||
//
|
||||
// HTMLMetadataDatabase.swift
|
||||
// HTMLMetadata
|
||||
//
|
||||
// Created by Brent Simmons on 4/6/26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import RSCore
|
||||
import RSDatabase
|
||||
import RSDatabaseObjC
|
||||
|
||||
actor HTMLMetadataDatabase {
|
||||
|
||||
@MainActor static let shared: HTMLMetadataDatabase = {
|
||||
let databasePath = AppConfig.dataFolder
|
||||
.appendingPathComponent("HTMLMetadata.db").path
|
||||
return HTMLMetadataDatabase(databasePath: databasePath)
|
||||
}()
|
||||
|
||||
private let database: FMDatabase
|
||||
private var cache = [String: CachedRecord]()
|
||||
|
||||
private struct CachedRecord {
|
||||
let record: HTMLMetadataRecord? // nil for a failure-only entry with no metadata
|
||||
let lastChecked: Date
|
||||
let statusCode: Int
|
||||
|
||||
/// True when the last contact for this URL returned a 4xx — a dead or
|
||||
/// missing homepage we shouldn’t keep re-requesting.
|
||||
var isFailure: Bool {
|
||||
(400...499).contains(statusCode)
|
||||
}
|
||||
}
|
||||
|
||||
private static let tableCreationStatements = """
|
||||
CREATE TABLE IF NOT EXISTS metadata (url TEXT PRIMARY KEY NOT NULL, lastChecked REAL NOT NULL, lastStatusCode INTEGER NOT NULL DEFAULT 200, favicons TEXT, appleTouchIcons TEXT, feedLinks TEXT, openGraphImages TEXT, twitterImageURL TEXT);
|
||||
"""
|
||||
|
||||
/// 73 hours — prime number close to 3 days.
|
||||
private static let cacheExpirationHours = 73
|
||||
|
||||
/// Entries that haven't been checked in a number of days are deleted on init.
|
||||
private static let maximumDaysWithoutCheck = 30
|
||||
|
||||
/// A homepage that returned a 4xx isn't retried until this many days pass.
|
||||
private static let failureRetryDays = 11
|
||||
|
||||
private init(databasePath: String) {
|
||||
let database = FMDatabase.openAndSetUpDatabase(path: databasePath)
|
||||
database.executeStatements("PRAGMA journal_mode = WAL;")
|
||||
database.runCreateStatements(Self.tableCreationStatements)
|
||||
self.database = database
|
||||
|
||||
NotificationCenter.default.addObserver(
|
||||
self, selector: #selector(handleAppDidGoToBackground(_:)),
|
||||
name: .appDidGoToBackground, object: nil
|
||||
)
|
||||
|
||||
// Run maintenance off the main thread (init may be evaluated there).
|
||||
Task {
|
||||
await performStartupMaintenance()
|
||||
}
|
||||
}
|
||||
|
||||
private func performStartupMaintenance() {
|
||||
removeExpiredEntries()
|
||||
database.vacuumIfNeeded()
|
||||
}
|
||||
|
||||
@objc nonisolated func handleAppDidGoToBackground(_ notification: Notification) {
|
||||
Task {
|
||||
await emptyCache()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the cached entry for a URL — in-memory if present, otherwise loaded
|
||||
/// from SQLite and cached. Returns nil only when there’s no row at all.
|
||||
private func cachedOrFetched(_ url: String) -> CachedRecord? {
|
||||
if let cached = cache[url] {
|
||||
return cached
|
||||
}
|
||||
|
||||
guard let fetched = HTMLMetadataTable.fetchRecordAndLastCheckedDate(url: url, database: database) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let cached = CachedRecord(record: fetched.record, lastChecked: fetched.lastChecked, statusCode: fetched.statusCode)
|
||||
cache[url] = cached
|
||||
return cached
|
||||
}
|
||||
|
||||
/// Returns a non-expired, successfully-fetched record. Returns nil if there’s
|
||||
/// no record, it’s a failure entry, or it has expired.
|
||||
func cachedRecord(for url: String) -> HTMLMetadataRecord? {
|
||||
guard let cached = cachedOrFetched(url), !cached.isFailure, let record = cached.record else {
|
||||
return nil
|
||||
}
|
||||
guard Date().timeIntervalSince(cached.lastChecked) < TimeInterval(hours: Self.cacheExpirationHours) else {
|
||||
return nil
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
/// Returns a successfully-fetched record regardless of expiration. Used for stale fallback.
|
||||
func staleCachedRecord(for url: String) -> HTMLMetadataRecord? {
|
||||
guard let cached = cachedOrFetched(url), !cached.isFailure else {
|
||||
return nil
|
||||
}
|
||||
return cached.record
|
||||
}
|
||||
|
||||
/// True if the last contact for this URL was a recent 4xx, meaning we should
|
||||
/// skip re-downloading it for now.
|
||||
func recentlyFailed(for url: String) -> Bool {
|
||||
guard let cached = cachedOrFetched(url), cached.isFailure else {
|
||||
return false
|
||||
}
|
||||
return Date().timeIntervalSince(cached.lastChecked) < TimeInterval(days: Self.failureRetryDays)
|
||||
}
|
||||
|
||||
func save(_ record: HTMLMetadataRecord, statusCode: Int) {
|
||||
cache[record.url] = CachedRecord(record: record, lastChecked: Date(), statusCode: statusCode)
|
||||
HTMLMetadataTable.insertOrReplace(record: record, statusCode: statusCode, database: database)
|
||||
}
|
||||
|
||||
/// Records a 4xx outcome for a URL so we stop re-requesting it across launches.
|
||||
/// Mirrors the SQLite guard in HTMLMetadataTable.noteFailure: never downgrade a
|
||||
/// successful entry — keep serving its metadata. Only record the failure when
|
||||
/// there’s no successful entry to protect.
|
||||
func noteFailure(url: String, statusCode: Int) {
|
||||
if cache[url]?.isFailure ?? true {
|
||||
cache[url] = CachedRecord(record: nil, lastChecked: Date(), statusCode: statusCode)
|
||||
}
|
||||
HTMLMetadataTable.noteFailure(url: url, statusCode: statusCode, database: database)
|
||||
}
|
||||
|
||||
func emptyCache() {
|
||||
cache.removeAll()
|
||||
}
|
||||
|
||||
func removeExpiredEntries() {
|
||||
let cutoff = Date().timeIntervalSince1970 - TimeInterval(days: Self.maximumDaysWithoutCheck)
|
||||
HTMLMetadataTable.removeExpired(olderThan: cutoff, database: database)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//
|
||||
// HTMLMetadataDownloader.swift
|
||||
// HTMLMetadata
|
||||
//
|
||||
// Created by Brent Simmons on 11/26/17.
|
||||
// Copyright © 2017 Ranchero Software. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import os
|
||||
import RSCore
|
||||
import RSParser
|
||||
import RSWeb
|
||||
import ActivityLog
|
||||
|
||||
nonisolated public final class HTMLMetadataDownloader: Sendable {
|
||||
|
||||
public static let shared = HTMLMetadataDownloader()
|
||||
|
||||
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "HTMLMetadataDownloader")
|
||||
|
||||
private static let hoursBetweenAttempts = 3
|
||||
|
||||
private let attemptDates = OSAllocatedUnfairLock(initialState: [String: Date]())
|
||||
|
||||
// Synchronous in-memory mirror of records that have been loaded from the
|
||||
// database or freshly downloaded this session. The database (see
|
||||
// HTMLMetadataDatabase) is the persistent store; this cache exists so
|
||||
// `cachedMetadata(for:)` can answer synchronously after a record has been
|
||||
// posted via .htmlMetadataAvailable. Cleared on background and low memory.
|
||||
private let cache = OSAllocatedUnfairLock(initialState: [String: HTMLMetadataRecord]())
|
||||
|
||||
init() {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
|
||||
}
|
||||
|
||||
@objc func handleAppDidGoToBackground(_ notification: Notification) {
|
||||
cache.withLock { $0.removeAll() }
|
||||
}
|
||||
|
||||
@objc func handleLowMemory(_ notification: Notification) {
|
||||
cache.withLock { $0.removeAll() }
|
||||
}
|
||||
|
||||
/// Returns cached metadata synchronously if available, otherwise kicks off a fetch.
|
||||
/// When the fetch (database lookup or download) finishes, the record is cached
|
||||
/// and a .htmlMetadataAvailable notification is posted — callers re-query then.
|
||||
public func cachedMetadata(for url: String) -> HTMLMetadataRecord? {
|
||||
if Self.shouldSkipDownloadingMetadata(url) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if let record = cache.withLock({ $0[url] }) {
|
||||
return record
|
||||
}
|
||||
|
||||
fetchAndDownloadIfNeeded(url)
|
||||
return nil
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
nonisolated private extension HTMLMetadataDownloader {
|
||||
|
||||
private static let specialCasesToSkip = [SpecialCase.rachelByTheBayHostName, SpecialCase.openRSSOrgHostName]
|
||||
|
||||
static func shouldSkipDownloadingMetadata(_ urlString: String) -> Bool {
|
||||
SpecialCase.urlStringContainSpecialCase(urlString, specialCasesToSkip)
|
||||
}
|
||||
|
||||
func fetchAndDownloadIfNeeded(_ url: String) {
|
||||
Task { @MainActor in
|
||||
if let record = await HTMLMetadataDatabase.shared.cachedRecord(for: url) {
|
||||
cacheRecord(record)
|
||||
postNotification(record)
|
||||
return
|
||||
}
|
||||
|
||||
if await HTMLMetadataDatabase.shared.recentlyFailed(for: url) {
|
||||
return
|
||||
}
|
||||
|
||||
downloadMetadataIfNeeded(url)
|
||||
}
|
||||
}
|
||||
|
||||
func cacheRecord(_ record: HTMLMetadataRecord) {
|
||||
cache.withLock { $0[record.url] = record }
|
||||
}
|
||||
|
||||
func downloadMetadataIfNeeded(_ url: String) {
|
||||
let shouldDownload = attemptDates.withLock { dates in
|
||||
let currentDate = Date()
|
||||
if let attemptDate = dates[url], attemptDate > currentDate.bySubtracting(hours: Self.hoursBetweenAttempts) {
|
||||
return false
|
||||
}
|
||||
dates[url] = currentDate
|
||||
return true
|
||||
}
|
||||
|
||||
if shouldDownload {
|
||||
downloadMetadata(url)
|
||||
}
|
||||
}
|
||||
|
||||
func downloadMetadata(_ url: String) {
|
||||
guard let actualURL = URL(string: url) else {
|
||||
return
|
||||
}
|
||||
|
||||
Task { @MainActor in
|
||||
let activityLog = ActivityLog.shared
|
||||
let kind = ActivityKind.downloadHTMLMetadata(urlString: url)
|
||||
activityLog.createActivity(owner: .htmlMetadataDownloader, kind: kind)
|
||||
activityLog.didStart(.htmlMetadataDownloader, kind: kind)
|
||||
|
||||
do {
|
||||
let (data, response) = try await Downloader.shared.download(actualURL)
|
||||
|
||||
if let data, !data.isEmpty, let response, response.statusIsOK {
|
||||
let urlToUse = response.url ?? actualURL
|
||||
let parserData = ParserData(url: urlToUse.absoluteString, data: data)
|
||||
let htmlMetadata = HTMLMetadataParser.htmlMetadata(with: parserData)
|
||||
let record = HTMLMetadataRecord(url: url, metadata: htmlMetadata)
|
||||
|
||||
let statusCode = response.forcedStatusCode
|
||||
await HTMLMetadataDatabase.shared.save(record, statusCode: statusCode)
|
||||
cacheRecord(record)
|
||||
postNotification(record)
|
||||
|
||||
activityLog.didComplete(.htmlMetadataDownloader, kind: kind)
|
||||
return
|
||||
}
|
||||
|
||||
let statusCode = response?.forcedStatusCode ?? -1
|
||||
if (400...499).contains(statusCode) {
|
||||
await HTMLMetadataDatabase.shared.noteFailure(url: url, statusCode: statusCode)
|
||||
}
|
||||
|
||||
// Download failed — try returning stale cached data.
|
||||
await returnStaleCacheIfAvailable(url)
|
||||
|
||||
let userInfo = [NSLocalizedDescriptionKey: "HTTP \(statusCode)"]
|
||||
let statusError = NSError(domain: "NetNewsWire", code: statusCode, userInfo: userInfo)
|
||||
activityLog.didFail(.htmlMetadataDownloader, kind: kind, error: statusError)
|
||||
|
||||
} catch {
|
||||
// Download failed — try returning stale cached data.
|
||||
await returnStaleCacheIfAvailable(url)
|
||||
|
||||
activityLog.didFail(.htmlMetadataDownloader, kind: kind, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func postNotification(_ record: HTMLMetadataRecord) {
|
||||
let userInfo: [String: Any] = [
|
||||
HTMLMetadataUserInfoKey.record: record,
|
||||
HTMLMetadataUserInfoKey.url: record.url
|
||||
]
|
||||
NotificationCenter.default.postOnMainThread(
|
||||
name: .htmlMetadataAvailable, object: self, userInfo: userInfo
|
||||
)
|
||||
}
|
||||
|
||||
@MainActor func returnStaleCacheIfAvailable(_ url: String) async {
|
||||
if let record = await HTMLMetadataDatabase.shared.staleCachedRecord(for: url) {
|
||||
cacheRecord(record)
|
||||
postNotification(record)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// HTMLMetadataNotification.swift
|
||||
// HTMLMetadata
|
||||
//
|
||||
// Created by Brent Simmons on 4/6/26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public extension Notification.Name {
|
||||
|
||||
/// Posted when HTMLMetadata is cached. Posted on any thread.
|
||||
nonisolated static let htmlMetadataAvailable = Notification.Name("htmlMetadataAvailable")
|
||||
}
|
||||
|
||||
public struct HTMLMetadataUserInfoKey {
|
||||
|
||||
public static let record = "htmlMetadataRecord" // HTMLMetadataRecord value
|
||||
public static let url = "url" // String value
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//
|
||||
// HTMLMetadataRecord.swift
|
||||
// HTMLMetadata
|
||||
//
|
||||
// Created by Brent Simmons on 4/6/26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import RSParser
|
||||
|
||||
public struct HTMLMetadataRecord: Sendable {
|
||||
|
||||
public let url: String
|
||||
public let favicons: [Favicon]
|
||||
public let appleTouchIcons: [AppleTouchIcon]
|
||||
public let feedLinks: [FeedLink]
|
||||
public let openGraphImages: [OpenGraphImage]
|
||||
public let twitterImageURL: String?
|
||||
|
||||
init(url: String, favicons: [Favicon], appleTouchIcons: [AppleTouchIcon],
|
||||
feedLinks: [FeedLink], openGraphImages: [OpenGraphImage],
|
||||
twitterImageURL: String?) {
|
||||
self.url = url
|
||||
self.favicons = favicons
|
||||
self.appleTouchIcons = appleTouchIcons
|
||||
self.feedLinks = feedLinks
|
||||
self.openGraphImages = openGraphImages
|
||||
self.twitterImageURL = twitterImageURL
|
||||
}
|
||||
|
||||
public init(url: String, metadata: HTMLMetadata) {
|
||||
self.url = url
|
||||
|
||||
self.favicons = metadata.favicons.map { favicon in
|
||||
Favicon(type: favicon.type, urlString: favicon.urlString)
|
||||
}
|
||||
|
||||
self.appleTouchIcons = metadata.appleTouchIcons.map { icon in
|
||||
AppleTouchIcon(
|
||||
rel: icon.rel,
|
||||
sizes: icon.sizes,
|
||||
width: icon.size.width,
|
||||
height: icon.size.height,
|
||||
urlString: icon.urlString
|
||||
)
|
||||
}
|
||||
|
||||
self.feedLinks = metadata.feedLinks.map { link in
|
||||
FeedLink(title: link.title, type: link.type, urlString: link.urlString)
|
||||
}
|
||||
|
||||
self.openGraphImages = metadata.openGraphProperties.images.map { image in
|
||||
OpenGraphImage(
|
||||
url: image.url,
|
||||
secureURL: image.secureURL,
|
||||
mimeType: image.mimeType,
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
altText: image.altText
|
||||
)
|
||||
}
|
||||
|
||||
self.twitterImageURL = metadata.twitterProperties.imageURL
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Nested Types
|
||||
|
||||
public extension HTMLMetadataRecord {
|
||||
|
||||
struct Favicon: Codable, Sendable {
|
||||
public let type: String?
|
||||
public let urlString: String?
|
||||
}
|
||||
|
||||
struct AppleTouchIcon: Codable, Sendable {
|
||||
public let rel: String?
|
||||
public let sizes: String?
|
||||
public let width: CGFloat
|
||||
public let height: CGFloat
|
||||
public let urlString: String?
|
||||
}
|
||||
|
||||
struct FeedLink: Codable, Sendable {
|
||||
public let title: String?
|
||||
public let type: String?
|
||||
public let urlString: String?
|
||||
}
|
||||
|
||||
struct OpenGraphImage: Codable, Sendable {
|
||||
public let url: String?
|
||||
public let secureURL: String?
|
||||
public let mimeType: String?
|
||||
public let width: CGFloat
|
||||
public let height: CGFloat
|
||||
public let altText: String?
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Icon Selection
|
||||
|
||||
public extension HTMLMetadataRecord {
|
||||
|
||||
func bestWebsiteIconURL() -> String? {
|
||||
if let appleTouchIcon = largestAppleTouchIcon() {
|
||||
return appleTouchIcon
|
||||
}
|
||||
if let openGraphImageURL = largestOpenGraphImageURL() {
|
||||
return openGraphImageURL
|
||||
}
|
||||
return twitterImageURL
|
||||
}
|
||||
|
||||
func largestOpenGraphImageURL() -> String? {
|
||||
guard !openGraphImages.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var bestImage: OpenGraphImage?
|
||||
|
||||
for image in openGraphImages {
|
||||
if image.height > 0 && image.width / image.height > 2 {
|
||||
continue
|
||||
}
|
||||
if bestImage == nil {
|
||||
bestImage = image
|
||||
continue
|
||||
}
|
||||
if let best = bestImage, image.height > best.height && image.width > best.width {
|
||||
bestImage = image
|
||||
}
|
||||
}
|
||||
|
||||
guard let url = bestImage?.secureURL ?? bestImage?.url else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let badURLs: Set<String> = ["https://s0.wp.com/i/blank.jpg"]
|
||||
guard !badURLs.contains(url) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return url
|
||||
}
|
||||
|
||||
func largestAppleTouchIcon() -> String? {
|
||||
guard !appleTouchIcons.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var bestImage: AppleTouchIcon?
|
||||
|
||||
for image in appleTouchIcons {
|
||||
if image.height > 0 && image.width / image.height > 2 {
|
||||
continue
|
||||
}
|
||||
if bestImage == nil {
|
||||
bestImage = image
|
||||
continue
|
||||
}
|
||||
if let best = bestImage, image.height > best.height && image.width > best.width {
|
||||
bestImage = image
|
||||
}
|
||||
}
|
||||
|
||||
return bestImage?.urlString
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//
|
||||
// HTMLMetadataTable.swift
|
||||
// HTMLMetadata
|
||||
//
|
||||
// Created by Brent Simmons on 4/6/26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import RSDatabase
|
||||
import RSDatabaseObjC
|
||||
|
||||
struct HTMLMetadataTable {
|
||||
|
||||
static let name = "metadata"
|
||||
|
||||
private struct Column {
|
||||
static let url = "url"
|
||||
static let lastChecked = "lastChecked"
|
||||
static let lastStatusCode = "lastStatusCode"
|
||||
static let favicons = "favicons"
|
||||
static let appleTouchIcons = "appleTouchIcons"
|
||||
static let feedLinks = "feedLinks"
|
||||
static let openGraphImages = "openGraphImages"
|
||||
static let twitterImageURL = "twitterImageURL"
|
||||
}
|
||||
|
||||
static func insertOrReplace(record: HTMLMetadataRecord, statusCode: Int, database: FMDatabase) {
|
||||
let dictionary: DatabaseDictionary = [
|
||||
Column.url: record.url,
|
||||
Column.lastChecked: Date().timeIntervalSince1970,
|
||||
Column.lastStatusCode: statusCode,
|
||||
Column.favicons: jsonString(record.favicons) as Any,
|
||||
Column.appleTouchIcons: jsonString(record.appleTouchIcons) as Any,
|
||||
Column.feedLinks: jsonString(record.feedLinks) as Any,
|
||||
Column.openGraphImages: jsonString(record.openGraphImages) as Any,
|
||||
Column.twitterImageURL: record.twitterImageURL as Any
|
||||
]
|
||||
database.insertRow(dictionary, insertType: .orReplace, tableName: name)
|
||||
}
|
||||
|
||||
static func fetchRecordAndLastCheckedDate(url: String, database: FMDatabase) -> (record: HTMLMetadataRecord, lastChecked: Date, statusCode: Int)? {
|
||||
guard let resultSet = database.rs_selectSingleRowWhereKey(Column.url, equalsValue: url, tableName: name) else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
resultSet.close()
|
||||
}
|
||||
|
||||
guard let record = record(from: resultSet) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let lastChecked = Date(timeIntervalSince1970: resultSet.double(forColumn: Column.lastChecked))
|
||||
let statusCode = resultSet.long(forColumn: Column.lastStatusCode)
|
||||
return (record, lastChecked, statusCode)
|
||||
}
|
||||
|
||||
/// Records a 4xx outcome for a URL: inserts a failure marker, or updates an
|
||||
/// existing failure row's status and date. The `WHERE` guard preserves rows
|
||||
/// that hold a successful (2xx) fetch, so a transient 4xx never erases good
|
||||
/// cached metadata.
|
||||
static func noteFailure(url: String, statusCode: Int, database: FMDatabase) {
|
||||
let sql = "INSERT INTO \(name) (\(Column.url), \(Column.lastChecked), \(Column.lastStatusCode)) VALUES (?, ?, ?) ON CONFLICT(\(Column.url)) DO UPDATE SET \(Column.lastChecked) = excluded.\(Column.lastChecked), \(Column.lastStatusCode) = excluded.\(Column.lastStatusCode) WHERE \(Column.lastStatusCode) >= 400;"
|
||||
database.executeUpdate(sql, withArgumentsIn: [url, Date().timeIntervalSince1970, statusCode])
|
||||
}
|
||||
|
||||
static func removeExpired(olderThan cutoff: TimeInterval, database: FMDatabase) {
|
||||
let sql = "DELETE FROM \(name) WHERE \(Column.lastChecked) < ?;"
|
||||
database.executeUpdate(sql, withArgumentsIn: [cutoff])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private extension HTMLMetadataTable {
|
||||
|
||||
static func record(from row: FMResultSet) -> HTMLMetadataRecord? {
|
||||
guard let url = row.string(forColumn: Column.url) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let favicons: [HTMLMetadataRecord.Favicon] =
|
||||
decoded(row.string(forColumn: Column.favicons)) ?? []
|
||||
let appleTouchIcons: [HTMLMetadataRecord.AppleTouchIcon] =
|
||||
decoded(row.string(forColumn: Column.appleTouchIcons)) ?? []
|
||||
let feedLinks: [HTMLMetadataRecord.FeedLink] =
|
||||
decoded(row.string(forColumn: Column.feedLinks)) ?? []
|
||||
let openGraphImages: [HTMLMetadataRecord.OpenGraphImage] =
|
||||
decoded(row.string(forColumn: Column.openGraphImages)) ?? []
|
||||
let twitterImageURL = row.string(forColumn: Column.twitterImageURL)
|
||||
|
||||
return HTMLMetadataRecord(
|
||||
url: url,
|
||||
favicons: favicons,
|
||||
appleTouchIcons: appleTouchIcons,
|
||||
feedLinks: feedLinks,
|
||||
openGraphImages: openGraphImages,
|
||||
twitterImageURL: twitterImageURL
|
||||
)
|
||||
}
|
||||
|
||||
static func jsonString<T: Encodable>(_ value: T) -> String? {
|
||||
guard let data = try? JSONEncoder().encode(value) else {
|
||||
return nil
|
||||
}
|
||||
return String(data: data, encoding: .utf8)
|
||||
}
|
||||
|
||||
static func decoded<T: Decodable>(_ jsonString: String?) -> T? {
|
||||
guard let jsonString, let data = jsonString.data(using: .utf8) else {
|
||||
return nil
|
||||
}
|
||||
return try? JSONDecoder().decode(T.self, from: data)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user