yattee/Model/PlaylistsModel.swift

83 lines
2.1 KiB
Swift
Raw Normal View History

2021-09-25 08:18:22 +00:00
import Foundation
import Siesta
import SwiftUI
final class PlaylistsModel: ObservableObject {
@Published var playlists = [Playlist]()
@Published var reloadPlaylists = false
2021-09-25 08:18:22 +00:00
2021-10-16 22:48:58 +00:00
var accounts = AccountsModel()
init(_ playlists: [Playlist] = [Playlist]()) {
self.playlists = playlists
2021-09-25 08:18:22 +00:00
}
var all: [Playlist] {
playlists.sorted { $0.title.lowercased() < $1.title.lowercased() }
}
func find(id: Playlist.ID?) -> Playlist? {
if id.isNil {
return nil
}
return playlists.first { $0.id == id! }
}
var isEmpty: Bool {
playlists.isEmpty
2021-09-25 08:18:22 +00:00
}
func load(force: Bool = false, onSuccess: @escaping () -> Void = {}) {
guard accounts.app.supportsUserPlaylists, accounts.signedIn else {
playlists = []
return
}
let request = force ? resource?.load() : resource?.loadIfNeeded()
2021-09-25 08:18:22 +00:00
guard !request.isNil else {
onSuccess()
return
}
2021-09-25 08:18:22 +00:00
request?
.onSuccess { resource in
if let playlists: [Playlist] = resource.typedContent() {
self.playlists = playlists
onSuccess()
2021-09-25 08:18:22 +00:00
}
}
.onFailure { _ in
self.playlists = []
}
}
2021-12-17 19:53:05 +00:00
func addVideo(
playlistID: Playlist.ID,
videoID: Video.ID,
onSuccess: @escaping () -> Void = {},
onFailure: @escaping (RequestError) -> Void = { _ in }
) {
accounts.api.addVideoToPlaylist(videoID, playlistID, onFailure: onFailure) {
self.load(force: true) {
self.reloadPlaylists.toggle()
onSuccess()
}
}
}
func removeVideo(index: String, playlistID: Playlist.ID, onSuccess: @escaping () -> Void = {}) {
accounts.api.removeVideoFromPlaylist(index, playlistID, onFailure: { _ in }) {
self.load(force: true) {
self.reloadPlaylists.toggle()
2021-12-17 19:53:05 +00:00
onSuccess()
}
}
}
private var resource: Resource? {
accounts.api.playlists
}
2021-09-25 08:18:22 +00:00
}