yattee/Model/Cache/ChannelPlaylistsCacheModel.swift

61 lines
2.0 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 {
2022-12-11 17:44:55 +00:00
static let shared = ChannelPlaylistsCacheModel()
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-11 17:44:55 +00:00
logger.info("STORE \(playlistCacheKey(playlist.id)) -- \(date)")
let feedTimeObject: JSON = ["date": date]
let playlistObject: JSON = ["playlist": playlist.json.object]
2022-12-12 09:21:46 +00:00
try? storage?.setObject(feedTimeObject, forKey: playlistTimeCacheKey(playlist.id))
try? storage?.setObject(playlistObject, forKey: playlistCacheKey(playlist.id))
2022-12-11 17:44:55 +00:00
}
func retrievePlaylist(_ id: ChannelPlaylist.ID) -> ChannelPlaylist? {
logger.info("RETRIEVE \(playlistCacheKey(id))")
2022-12-12 09:21:46 +00:00
if let json = try? storage?.object(forKey: playlistCacheKey(id)).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
}
private func playlistCacheKey(_ playlist: ChannelPlaylist.ID) -> String {
"channelplaylists-\(playlist)"
}
private func playlistTimeCacheKey(_ playlist: ChannelPlaylist.ID) -> String {
"\(playlistCacheKey(playlist))-time"
}
}