1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-13 22:00:31 +05:30
yattee/Model/Cache/PlaylistsCacheModel.swift

64 lines
2.1 KiB
Swift
Raw Normal View History

2022-12-11 22:34:39 +05:30
import Cache
import Foundation
import Logging
import SwiftyJSON
2022-12-12 14:51:46 +05:30
struct PlaylistsCacheModel: CacheModel {
2023-04-22 18:38:33 +05:30
static let shared = Self()
2022-12-11 22:34:39 +05:30
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 14:51:46 +05:30
let storage = try? Storage<String, JSON>(
2022-12-11 22:34:39 +05:30
diskConfig: Self.diskConfig,
memoryConfig: Self.memoryConfig,
2022-12-12 14:51:46 +05:30
transformer: BaseCacheModel.jsonTransformer
2022-12-11 22:34:39 +05:30
)
func storePlaylist(account: Account, playlists: [Playlist]) {
2022-12-12 14:51:46 +05:30
let date = iso8601DateFormatter.string(from: Date())
2022-12-11 22:34:39 +05:30
logger.info("caching \(playlistCacheKey(account)) -- \(date)")
let feedTimeObject: JSON = ["date": date]
let playlistsObject: JSON = ["playlists": playlists.map { $0.json.object }]
2022-12-12 14:51:46 +05:30
try? storage?.setObject(feedTimeObject, forKey: playlistTimeCacheKey(account))
try? storage?.setObject(playlistsObject, forKey: playlistCacheKey(account))
2022-12-11 22:34:39 +05:30
}
func retrievePlaylists(account: Account) -> [Playlist] {
2022-12-21 02:11:27 +05:30
logger.debug("retrieving cache for \(playlistCacheKey(account))")
2022-12-11 22:34:39 +05:30
2022-12-12 14:51:46 +05:30
if let json = try? storage?.object(forKey: playlistCacheKey(account)),
2022-12-11 22:34:39 +05:30
let playlists = json.dictionaryValue["playlists"]
{
return playlists.arrayValue.map { Playlist.from($0) }
}
return []
}
func getPlaylistsTime(account: Account) -> Date? {
2022-12-12 14:51:46 +05:30
if let json = try? storage?.object(forKey: playlistTimeCacheKey(account)),
2022-12-11 22:34:39 +05:30
let string = json.dictionaryValue["date"]?.string,
2022-12-12 14:51:46 +05:30
let date = iso8601DateFormatter.date(from: string)
2022-12-11 22:34:39 +05:30
{
return date
}
return nil
}
func getFormattedPlaylistTime(account: Account) -> String {
2022-12-12 14:51:46 +05:30
getFormattedDate(getPlaylistsTime(account: account))
2022-12-11 22:34:39 +05:30
}
private func playlistCacheKey(_ account: Account) -> String {
"playlists-\(account.id)"
}
private func playlistTimeCacheKey(_ account: Account) -> String {
"\(playlistCacheKey(account))-time"
}
}