yattee/Model/Cache/PlaylistsCacheModel.swift

65 lines
2.1 KiB
Swift
Raw Normal View History

2022-12-11 17:04:39 +00:00
import Cache
import Foundation
import Logging
import SwiftyJSON
2022-12-12 09:21:46 +00:00
struct PlaylistsCacheModel: CacheModel {
2023-04-22 13:08:33 +00:00
static let shared = Self()
2022-12-11 17:04:39 +00:00
static let limit = 30
let logger = Logger(label: "stream.yattee.cache.playlists")
static let diskConfig = DiskConfig(name: "playlists")
static let memoryConfig = MemoryConfig()
2022-12-12 09:21:46 +00:00
let storage = try? Storage<String, JSON>(
2022-12-11 17:04:39 +00:00
diskConfig: Self.diskConfig,
memoryConfig: Self.memoryConfig,
fileManager: FileManager.default,
2022-12-12 09:21:46 +00:00
transformer: BaseCacheModel.jsonTransformer
2022-12-11 17:04:39 +00:00
)
func storePlaylist(account: Account, playlists: [Playlist]) {
2022-12-12 09:21:46 +00:00
let date = iso8601DateFormatter.string(from: Date())
2022-12-11 17:04:39 +00:00
logger.info("caching \(playlistCacheKey(account)) -- \(date)")
let feedTimeObject: JSON = ["date": date]
let playlistsObject: JSON = ["playlists": playlists.map(\.json.object)]
2022-12-12 09:21:46 +00:00
try? storage?.setObject(feedTimeObject, forKey: playlistTimeCacheKey(account))
try? storage?.setObject(playlistsObject, forKey: playlistCacheKey(account))
2022-12-11 17:04:39 +00:00
}
func retrievePlaylists(account: Account) -> [Playlist] {
2022-12-20 20:41:27 +00:00
logger.debug("retrieving cache for \(playlistCacheKey(account))")
2022-12-11 17:04:39 +00:00
2022-12-12 09:21:46 +00:00
if let json = try? storage?.object(forKey: playlistCacheKey(account)),
2022-12-11 17:04:39 +00:00
let playlists = json.dictionaryValue["playlists"]
{
return playlists.arrayValue.map { Playlist.from($0) }
}
return []
}
func getPlaylistsTime(account: Account) -> Date? {
2022-12-12 09:21:46 +00:00
if let json = try? storage?.object(forKey: playlistTimeCacheKey(account)),
2022-12-11 17:04:39 +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:04:39 +00:00
{
return date
}
return nil
}
func getFormattedPlaylistTime(account: Account) -> String {
2022-12-12 09:21:46 +00:00
getFormattedDate(getPlaylistsTime(account: account))
2022-12-11 17:04:39 +00:00
}
private func playlistCacheKey(_ account: Account) -> String {
"playlists-\(account.id)"
}
private func playlistTimeCacheKey(_ account: Account) -> String {
"\(playlistCacheKey(account))-time"
}
}