2022-12-10 02:01:59 +00:00
|
|
|
import Cache
|
2022-12-13 11:09:20 +00:00
|
|
|
import Defaults
|
2022-12-10 02:01:59 +00:00
|
|
|
import Foundation
|
|
|
|
import Logging
|
|
|
|
import SwiftyJSON
|
|
|
|
|
2022-12-12 09:21:46 +00:00
|
|
|
struct FeedCacheModel: CacheModel {
|
2022-12-10 02:01:59 +00:00
|
|
|
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 09:21:46 +00:00
|
|
|
let storage = try? Storage<String, JSON>(
|
2022-12-10 02:01:59 +00:00
|
|
|
diskConfig: Self.diskConfig,
|
|
|
|
memoryConfig: Self.memoryConfig,
|
2022-12-12 09:21:46 +00:00
|
|
|
transformer: BaseCacheModel.jsonTransformer
|
2022-12-10 02:01:59 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func storeFeed(account: Account, videos: [Video]) {
|
2022-12-12 09:21:46 +00:00
|
|
|
let date = iso8601DateFormatter.string(from: Date())
|
2022-12-10 02:01:59 +00:00
|
|
|
logger.info("caching feed \(account.feedCacheKey) -- \(date)")
|
|
|
|
let feedTimeObject: JSON = ["date": date]
|
2022-12-13 11:09:20 +00:00
|
|
|
let videosObject: JSON = ["videos": videos.prefix(cacheLimit).map { $0.json.object }]
|
2022-12-12 09:21:46 +00:00
|
|
|
try? storage?.setObject(feedTimeObject, forKey: feedTimeCacheKey(account.feedCacheKey))
|
|
|
|
try? storage?.setObject(videosObject, forKey: account.feedCacheKey)
|
2022-12-10 02:01:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func retrieveFeed(account: Account) -> [Video] {
|
|
|
|
logger.info("retrieving cache for \(account.feedCacheKey)")
|
|
|
|
|
2022-12-12 09:21:46 +00:00
|
|
|
if let json = try? storage?.object(forKey: account.feedCacheKey),
|
2022-12-10 02:01:59 +00:00
|
|
|
let videos = json.dictionaryValue["videos"]
|
|
|
|
{
|
|
|
|
return videos.arrayValue.map { Video.from($0) }
|
|
|
|
}
|
|
|
|
|
|
|
|
return []
|
|
|
|
}
|
|
|
|
|
|
|
|
func getFeedTime(account: Account) -> Date? {
|
2022-12-12 09:21:46 +00:00
|
|
|
if let json = try? storage?.object(forKey: feedTimeCacheKey(account.feedCacheKey)),
|
2022-12-10 02:01:59 +00:00
|
|
|
let string = json.dictionaryValue["date"]?.string,
|
2022-12-12 09:21:46 +00:00
|
|
|
let date = iso8601DateFormatter.date(from: string)
|
2022-12-10 02:01:59 +00:00
|
|
|
{
|
|
|
|
return date
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-12-13 11:09:20 +00:00
|
|
|
private var cacheLimit: Int {
|
|
|
|
let setting = Int(Defaults[.feedCacheSize]) ?? 0
|
|
|
|
if setting > 0 {
|
|
|
|
return setting
|
|
|
|
}
|
|
|
|
|
|
|
|
return 50
|
|
|
|
}
|
|
|
|
|
2022-12-11 11:38:57 +00:00
|
|
|
private func feedTimeCacheKey(_ feedCacheKey: String) -> String {
|
|
|
|
"\(feedCacheKey)-feedTime"
|
|
|
|
}
|
2022-12-10 02:01:59 +00:00
|
|
|
}
|