yattee/Model/Cache/ChannelPlaylistsCacheModel.swift

57 lines
1.8 KiB
Swift
Raw Normal View History

2022-12-11 17:44:55 +00:00
import Cache
import Foundation
import Logging
import SwiftyJSON
2022-12-12 09:21:46 +00:00
struct ChannelPlaylistsCacheModel: CacheModel {
2023-04-22 13:08:33 +00:00
static let shared = Self()
2022-12-11 17:44:55 +00:00
let logger = Logger(label: "stream.yattee.cache.channel-playlists")
static let diskConfig = DiskConfig(name: "channel-playlists")
static let memoryConfig = MemoryConfig()
2022-12-12 09:21:46 +00:00
var storage = try? Storage<String, JSON>(
2022-12-11 17:44:55 +00:00
diskConfig: Self.diskConfig,
memoryConfig: Self.memoryConfig,
2022-12-12 09:21:46 +00:00
transformer: BaseCacheModel.jsonTransformer
2022-12-11 17:44:55 +00:00
)
func storePlaylist(playlist: ChannelPlaylist) {
2022-12-12 09:21:46 +00:00
let date = iso8601DateFormatter.string(from: Date())
2022-12-16 19:37:05 +00:00
logger.info("STORE \(playlist.cacheKey) -- \(date)")
2022-12-11 17:44:55 +00:00
let feedTimeObject: JSON = ["date": date]
let playlistObject: JSON = ["playlist": playlist.json.object]
2022-12-16 19:37:05 +00:00
try? storage?.setObject(feedTimeObject, forKey: playlistTimeCacheKey(playlist.cacheKey))
try? storage?.setObject(playlistObject, forKey: playlist.cacheKey)
2022-12-11 17:44:55 +00:00
}
2022-12-16 19:37:05 +00:00
func retrievePlaylist(_ playlist: ChannelPlaylist) -> ChannelPlaylist? {
logger.info("RETRIEVE \(playlist.cacheKey)")
2022-12-11 17:44:55 +00:00
2022-12-16 19:37:05 +00:00
if let json = try? storage?.object(forKey: playlist.cacheKey).dictionaryValue["playlist"] {
2022-12-11 17:44:55 +00:00
return ChannelPlaylist.from(json)
}
return nil
}
func getPlaylistsTime(_ id: ChannelPlaylist.ID) -> Date? {
2022-12-12 09:21:46 +00:00
if let json = try? storage?.object(forKey: playlistTimeCacheKey(id)),
2022-12-11 17:44:55 +00:00
let string = json.dictionaryValue["date"]?.string,
2022-12-12 09:21:46 +00:00
let date = iso8601DateFormatter.date(from: string)
2022-12-11 17:44:55 +00:00
{
return date
}
return nil
}
func getFormattedPlaylistTime(_ id: ChannelPlaylist.ID) -> String {
2022-12-12 09:21:46 +00:00
getFormattedDate(getPlaylistsTime(id))
2022-12-11 17:44:55 +00:00
}
2022-12-16 19:37:05 +00:00
private func playlistTimeCacheKey(_ cacheKey: ChannelPlaylist.ID) -> String {
"\(cacheKey)-time"
2022-12-11 17:44:55 +00:00
}
}