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

65 lines
2.0 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 {
2022-12-10 07:31:59 +05:30
static let shared = FeedCacheModel()
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] {
logger.info("retrieving cache for \(account.feedCacheKey)")
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
}