mirror of
https://github.com/yattee/yattee.git
synced 2025-08-06 10:44:06 +00:00
User playlists cache
This commit is contained in:
@@ -114,8 +114,7 @@ final class InvidiousAPI: Service, ObservableObject, VideosAPI {
|
||||
}
|
||||
|
||||
configureTransformer(pathPattern("auth/playlists"), requestMethods: [.post, .patch]) { (content: Entity<Data>) -> Playlist in
|
||||
// hacky, to verify if possible to get it in easier way
|
||||
Playlist(JSON(parseJSON: String(data: content.content, encoding: .utf8)!))
|
||||
self.extractPlaylist(from: JSON(parseJSON: String(data: content.content, encoding: .utf8)!))
|
||||
}
|
||||
|
||||
configureTransformer(pathPattern("auth/feed"), requestMethods: [.get]) { (content: Entity<JSON>) -> [Video] in
|
||||
|
@@ -121,8 +121,7 @@ final class PeerTubeAPI: Service, ObservableObject, VideosAPI {
|
||||
}
|
||||
|
||||
configureTransformer(pathPattern("auth/playlists"), requestMethods: [.post, .patch]) { (content: Entity<Data>) -> Playlist in
|
||||
// hacky, to verify if possible to get it in easier way
|
||||
Playlist(JSON(parseJSON: String(data: content.content, encoding: .utf8)!))
|
||||
self.extractPlaylist(from: JSON(parseJSON: String(data: content.content, encoding: .utf8)!))
|
||||
}
|
||||
|
||||
configureTransformer(pathPattern("auth/feed"), requestMethods: [.get]) { (content: Entity<JSON>) -> [Video] in
|
||||
|
@@ -13,18 +13,36 @@ struct CacheModel {
|
||||
func clear() {
|
||||
FeedCacheModel.shared.clear()
|
||||
VideosCacheModel.shared.clear()
|
||||
PlaylistsCacheModel.shared.clear()
|
||||
}
|
||||
|
||||
var totalSize: Int {
|
||||
(FeedCacheModel.shared.storage.totalDiskStorageSize ?? 0) +
|
||||
(VideosCacheModel.shared.storage.totalDiskStorageSize ?? 0)
|
||||
(VideosCacheModel.shared.storage.totalDiskStorageSize ?? 0) +
|
||||
(PlaylistsCacheModel.shared.storage.totalDiskStorageSize ?? 0)
|
||||
}
|
||||
|
||||
var totalSizeFormatted: String {
|
||||
totalSizeFormatter.string(fromByteCount: Int64(totalSize))
|
||||
byteCountFormatter.string(fromByteCount: Int64(totalSize))
|
||||
}
|
||||
|
||||
private var totalSizeFormatter: ByteCountFormatter {
|
||||
.init()
|
||||
var dateFormatter: DateFormatter {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .short
|
||||
formatter.timeStyle = .medium
|
||||
|
||||
return formatter
|
||||
}
|
||||
|
||||
var dateFormatterForTimeOnly: DateFormatter {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .none
|
||||
formatter.timeStyle = .medium
|
||||
|
||||
return formatter
|
||||
}
|
||||
|
||||
var iso8601DateFormatter: ISO8601DateFormatter { .init() }
|
||||
|
||||
private var byteCountFormatter: ByteCountFormatter { .init() }
|
||||
}
|
||||
|
@@ -18,7 +18,7 @@ struct FeedCacheModel {
|
||||
)
|
||||
|
||||
func storeFeed(account: Account, videos: [Video]) {
|
||||
let date = iso8601DateFormatter.string(from: Date())
|
||||
let date = CacheModel.shared.iso8601DateFormatter.string(from: Date())
|
||||
logger.info("caching feed \(account.feedCacheKey) -- \(date)")
|
||||
let feedTimeObject: JSON = ["date": date]
|
||||
let videosObject: JSON = ["videos": videos.prefix(Self.limit).map { $0.json.object }]
|
||||
@@ -41,7 +41,7 @@ struct FeedCacheModel {
|
||||
func getFeedTime(account: Account) -> Date? {
|
||||
if let json = try? storage.object(forKey: feedTimeCacheKey(account.feedCacheKey)),
|
||||
let string = json.dictionaryValue["date"]?.string,
|
||||
let date = iso8601DateFormatter.date(from: string)
|
||||
let date = CacheModel.shared.iso8601DateFormatter.date(from: string)
|
||||
{
|
||||
return date
|
||||
}
|
||||
@@ -56,24 +56,4 @@ struct FeedCacheModel {
|
||||
private func feedTimeCacheKey(_ feedCacheKey: String) -> String {
|
||||
"\(feedCacheKey)-feedTime"
|
||||
}
|
||||
|
||||
private var iso8601DateFormatter: ISO8601DateFormatter {
|
||||
.init()
|
||||
}
|
||||
|
||||
private var dateFormatter: DateFormatter {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .short
|
||||
formatter.timeStyle = .medium
|
||||
|
||||
return formatter
|
||||
}
|
||||
|
||||
private var dateFormatterForTimeOnly: DateFormatter {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .none
|
||||
formatter.timeStyle = .medium
|
||||
|
||||
return formatter
|
||||
}
|
||||
}
|
||||
|
73
Model/Cache/PlaylistsCacheModel.swift
Normal file
73
Model/Cache/PlaylistsCacheModel.swift
Normal file
@@ -0,0 +1,73 @@
|
||||
import Cache
|
||||
import Foundation
|
||||
import Logging
|
||||
import SwiftyJSON
|
||||
|
||||
struct PlaylistsCacheModel {
|
||||
static let shared = PlaylistsCacheModel()
|
||||
static let limit = 30
|
||||
let logger = Logger(label: "stream.yattee.cache.playlists")
|
||||
|
||||
static let diskConfig = DiskConfig(name: "playlists")
|
||||
static let memoryConfig = MemoryConfig()
|
||||
|
||||
let storage = try! Storage<String, JSON>(
|
||||
diskConfig: Self.diskConfig,
|
||||
memoryConfig: Self.memoryConfig,
|
||||
transformer: CacheModel.jsonTransformer
|
||||
)
|
||||
|
||||
func storePlaylist(account: Account, playlists: [Playlist]) {
|
||||
let date = CacheModel.shared.iso8601DateFormatter.string(from: Date())
|
||||
logger.info("caching \(playlistCacheKey(account)) -- \(date)")
|
||||
let feedTimeObject: JSON = ["date": date]
|
||||
let playlistsObject: JSON = ["playlists": playlists.map { $0.json.object }]
|
||||
try? storage.setObject(feedTimeObject, forKey: playlistTimeCacheKey(account))
|
||||
try? storage.setObject(playlistsObject, forKey: playlistCacheKey(account))
|
||||
}
|
||||
|
||||
func retrievePlaylists(account: Account) -> [Playlist] {
|
||||
logger.info("retrieving cache for \(playlistCacheKey(account))")
|
||||
|
||||
if let json = try? storage.object(forKey: playlistCacheKey(account)),
|
||||
let playlists = json.dictionaryValue["playlists"]
|
||||
{
|
||||
return playlists.arrayValue.map { Playlist.from($0) }
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
func getPlaylistsTime(account: Account) -> Date? {
|
||||
if let json = try? storage.object(forKey: playlistTimeCacheKey(account)),
|
||||
let string = json.dictionaryValue["date"]?.string,
|
||||
let date = CacheModel.shared.iso8601DateFormatter.date(from: string)
|
||||
{
|
||||
return date
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getFormattedPlaylistTime(account: Account) -> String {
|
||||
if let time = getPlaylistsTime(account: account) {
|
||||
let isSameDay = Calendar(identifier: .iso8601).isDate(time, inSameDayAs: Date())
|
||||
let formatter = isSameDay ? CacheModel.shared.dateFormatterForTimeOnly : CacheModel.shared.dateFormatter
|
||||
return formatter.string(from: time)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func clear() {
|
||||
try? storage.removeAll()
|
||||
}
|
||||
|
||||
private func playlistCacheKey(_ account: Account) -> String {
|
||||
"playlists-\(account.id)"
|
||||
}
|
||||
|
||||
private func playlistTimeCacheKey(_ account: Account) -> String {
|
||||
"\(playlistCacheKey(account))-time"
|
||||
}
|
||||
}
|
@@ -106,7 +106,7 @@ final class FeedModel: ObservableObject {
|
||||
var formattedFeedTime: String {
|
||||
if let feedTime {
|
||||
let isSameDay = Calendar(identifier: .iso8601).isDate(feedTime, inSameDayAs: Date())
|
||||
let formatter = isSameDay ? dateFormatterForTimeOnly : dateFormatter
|
||||
let formatter = isSameDay ? CacheModel.shared.dateFormatterForTimeOnly : CacheModel.shared.dateFormatter
|
||||
return formatter.string(from: feedTime)
|
||||
}
|
||||
|
||||
@@ -123,22 +123,6 @@ final class FeedModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
private var dateFormatter: DateFormatter {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .short
|
||||
formatter.timeStyle = .medium
|
||||
|
||||
return formatter
|
||||
}
|
||||
|
||||
private var dateFormatterForTimeOnly: DateFormatter {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .none
|
||||
formatter.timeStyle = .medium
|
||||
|
||||
return formatter
|
||||
}
|
||||
|
||||
private func request(_ resource: Resource, force: Bool = false) -> Request? {
|
||||
if force {
|
||||
return resource.load()
|
||||
|
@@ -23,7 +23,14 @@ struct Playlist: Identifiable, Equatable, Hashable {
|
||||
|
||||
var videos = [Video]()
|
||||
|
||||
init(id: String, title: String, visibility: Visibility, editable: Bool = true, updated: TimeInterval? = nil, videos: [Video] = []) {
|
||||
init(
|
||||
id: String,
|
||||
title: String,
|
||||
visibility: Visibility,
|
||||
editable: Bool = true,
|
||||
updated: TimeInterval? = nil,
|
||||
videos: [Video] = []
|
||||
) {
|
||||
self.id = id
|
||||
self.title = title
|
||||
self.visibility = visibility
|
||||
@@ -32,11 +39,29 @@ struct Playlist: Identifiable, Equatable, Hashable {
|
||||
self.videos = videos
|
||||
}
|
||||
|
||||
init(_ json: JSON) {
|
||||
id = json["playlistId"].stringValue
|
||||
title = json["title"].stringValue
|
||||
visibility = json["isListed"].boolValue ? .public : .private
|
||||
updated = json["updated"].doubleValue
|
||||
var json: JSON {
|
||||
let dateFormatter = ISO8601DateFormatter()
|
||||
|
||||
return [
|
||||
"id": id,
|
||||
"title": title,
|
||||
"visibility": visibility.rawValue,
|
||||
"editable": editable ? "editable" : "",
|
||||
"updated": updated ?? "",
|
||||
"videos": videos.map(\.json).map(\.object)
|
||||
]
|
||||
}
|
||||
|
||||
static func from(_ json: JSON) -> Self {
|
||||
let dateFormatter = ISO8601DateFormatter()
|
||||
|
||||
return .init(
|
||||
id: json["id"].stringValue,
|
||||
title: json["title"].stringValue,
|
||||
visibility: .init(rawValue: json["visibility"].stringValue) ?? .public,
|
||||
updated: json["updated"].doubleValue,
|
||||
videos: json["videos"].arrayValue.map { Video.from($0) }
|
||||
)
|
||||
}
|
||||
|
||||
static func == (lhs: Playlist, rhs: Playlist) -> Bool {
|
||||
|
@@ -6,6 +6,7 @@ import SwiftUI
|
||||
final class PlaylistsModel: ObservableObject {
|
||||
static var shared = PlaylistsModel()
|
||||
|
||||
@Published var isLoading = false
|
||||
@Published var playlists = [Playlist]()
|
||||
@Published var reloadPlaylists = false
|
||||
|
||||
@@ -36,29 +37,49 @@ final class PlaylistsModel: ObservableObject {
|
||||
}
|
||||
|
||||
func load(force: Bool = false, onSuccess: @escaping () -> Void = {}) {
|
||||
guard accounts.app.supportsUserPlaylists, accounts.signedIn else {
|
||||
guard accounts.app.supportsUserPlaylists, accounts.signedIn, let account = accounts.current else {
|
||||
playlists = []
|
||||
return
|
||||
}
|
||||
|
||||
let request = force ? resource?.load() : resource?.loadIfNeeded()
|
||||
loadCachedPlaylists(account)
|
||||
|
||||
guard !request.isNil else {
|
||||
onSuccess()
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self else { return }
|
||||
let request = force ? self.resource?.load() : self.resource?.loadIfNeeded()
|
||||
|
||||
request?
|
||||
.onSuccess { resource in
|
||||
if let playlists: [Playlist] = resource.typedContent() {
|
||||
self.playlists = playlists
|
||||
onSuccess()
|
||||
guard !request.isNil else {
|
||||
onSuccess()
|
||||
return
|
||||
}
|
||||
|
||||
self.isLoading = true
|
||||
|
||||
request?
|
||||
.onCompletion { [weak self] _ in
|
||||
self?.isLoading = false
|
||||
}
|
||||
.onSuccess { resource in
|
||||
if let playlists: [Playlist] = resource.typedContent() {
|
||||
self.playlists = playlists
|
||||
PlaylistsCacheModel.shared.storePlaylist(account: account, playlists: playlists)
|
||||
onSuccess()
|
||||
}
|
||||
}
|
||||
.onFailure { error in
|
||||
self.playlists = []
|
||||
NavigationModel.shared.presentAlert(title: "Could not refresh Playlists", message: error.userMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func loadCachedPlaylists(_ account: Account) {
|
||||
let cache = PlaylistsCacheModel.shared.retrievePlaylists(account: account)
|
||||
if !cache.isEmpty {
|
||||
DispatchQueue.main.async(qos: .userInteractive) {
|
||||
self.playlists = cache
|
||||
}
|
||||
.onFailure { error in
|
||||
self.playlists = []
|
||||
NavigationModel.shared.presentAlert(title: "Could not refresh Playlists", message: error.userMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func addVideo(
|
||||
|
@@ -89,7 +89,7 @@ final class SubscribedChannelsModel: ObservableObject {
|
||||
}
|
||||
|
||||
func storeChannels(account: Account, channels: [Channel]) {
|
||||
let date = iso8601DateFormatter.string(from: Date())
|
||||
let date = CacheModel.shared.iso8601DateFormatter.string(from: Date())
|
||||
logger.info("caching channels \(channelsDateCacheKey(account)) -- \(date)")
|
||||
|
||||
let dateObject: JSON = ["date": date]
|
||||
@@ -117,10 +117,6 @@ final class SubscribedChannelsModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
private var iso8601DateFormatter: ISO8601DateFormatter {
|
||||
.init()
|
||||
}
|
||||
|
||||
private func channelsCacheKey(_ account: Account) -> String {
|
||||
"channels-\(account.id)"
|
||||
}
|
||||
@@ -132,7 +128,7 @@ final class SubscribedChannelsModel: ObservableObject {
|
||||
func getFeedTime(account: Account) -> Date? {
|
||||
if let json = try? storage.object(forKey: channelsDateCacheKey(account)),
|
||||
let string = json.dictionaryValue["date"]?.string,
|
||||
let date = iso8601DateFormatter.date(from: string)
|
||||
let date = CacheModel.shared.iso8601DateFormatter.date(from: string)
|
||||
{
|
||||
return date
|
||||
}
|
||||
@@ -151,26 +147,10 @@ final class SubscribedChannelsModel: ObservableObject {
|
||||
var formattedCacheTime: String {
|
||||
if let feedTime {
|
||||
let isSameDay = Calendar(identifier: .iso8601).isDate(feedTime, inSameDayAs: Date())
|
||||
let formatter = isSameDay ? dateFormatterForTimeOnly : dateFormatter
|
||||
let formatter = isSameDay ? CacheModel.shared.dateFormatterForTimeOnly : CacheModel.shared.dateFormatter
|
||||
return formatter.string(from: feedTime)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
private var dateFormatter: DateFormatter {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .short
|
||||
formatter.timeStyle = .medium
|
||||
|
||||
return formatter
|
||||
}
|
||||
|
||||
private var dateFormatterForTimeOnly: DateFormatter {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .none
|
||||
formatter.timeStyle = .medium
|
||||
|
||||
return formatter
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user