1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-13 22:00:31 +05:30
yattee/Model/Cache/FeedCacheModel.swift

65 lines
1.9 KiB
Swift
Raw Normal View History

2022-12-10 07:31:59 +05:30
import Cache
2022-12-13 16:39:20 +05:30
import Defaults
2022-12-10 07:31:59 +05:30
import Foundation
import Logging
import SwiftyJSON
2022-12-12 14:51:46 +05:30
struct FeedCacheModel: CacheModel {
2023-04-22 18:38:33 +05:30
static let shared = Self()
2022-12-10 07:31:59 +05:30
let logger = Logger(label: "stream.yattee.cache.feed")
static let diskConfig = DiskConfig(name: "feed")
static let memoryConfig = MemoryConfig()
2022-12-12 14:51:46 +05:30
let storage = try? Storage<String, JSON>(
2022-12-10 07:31:59 +05:30
diskConfig: Self.diskConfig,
memoryConfig: Self.memoryConfig,
2022-12-12 14:51:46 +05:30
transformer: BaseCacheModel.jsonTransformer
2022-12-10 07:31:59 +05:30
)
func storeFeed(account: Account, videos: [Video]) {
2022-12-12 14:51:46 +05:30
let date = iso8601DateFormatter.string(from: Date())
2022-12-10 07:31:59 +05:30
logger.info("caching feed \(account.feedCacheKey) -- \(date)")
let feedTimeObject: JSON = ["date": date]
2022-12-13 16:39:20 +05:30
let videosObject: JSON = ["videos": videos.prefix(cacheLimit).map { $0.json.object }]
2022-12-12 14:51:46 +05:30
try? storage?.setObject(feedTimeObject, forKey: feedTimeCacheKey(account.feedCacheKey))
try? storage?.setObject(videosObject, forKey: account.feedCacheKey)
2022-12-10 07:31:59 +05:30
}
func retrieveFeed(account: Account) -> [Video] {
2022-12-21 02:11:27 +05:30
logger.debug("retrieving cache for \(account.feedCacheKey)")
2022-12-10 07:31:59 +05:30
2022-12-12 14:51:46 +05:30
if let json = try? storage?.object(forKey: account.feedCacheKey),
2022-12-10 07:31:59 +05:30
let videos = json.dictionaryValue["videos"]
{
return videos.arrayValue.map { Video.from($0) }
}
return []
}
func getFeedTime(account: Account) -> Date? {
2022-12-12 14:51:46 +05:30
if let json = try? storage?.object(forKey: feedTimeCacheKey(account.feedCacheKey)),
2022-12-10 07:31:59 +05:30
let string = json.dictionaryValue["date"]?.string,
2022-12-12 14:51:46 +05:30
let date = iso8601DateFormatter.date(from: string)
2022-12-10 07:31:59 +05:30
{
return date
}
return nil
}
2022-12-13 16:39:20 +05:30
private var cacheLimit: Int {
let setting = Int(Defaults[.feedCacheSize]) ?? 0
if setting > 0 {
return setting
}
return 50
}
private func feedTimeCacheKey(_ feedCacheKey: String) -> String {
"\(feedCacheKey)-feedTime"
}
2022-12-10 07:31:59 +05:30
}