1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-13 13:50:32 +05:30
yattee/Model/PlaylistsModel.swift

78 lines
1.9 KiB
Swift
Raw Normal View History

2021-09-25 13:48:22 +05:30
import Foundation
import Siesta
import SwiftUI
final class PlaylistsModel: ObservableObject {
@Published var playlists = [Playlist]()
2021-10-17 04:18:58 +05:30
var accounts = AccountsModel()
init(_ playlists: [Playlist] = [Playlist]()) {
self.playlists = playlists
2021-09-25 13:48:22 +05:30
}
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 13:48:22 +05:30
}
func load(force: Bool = false, onSuccess: @escaping () -> Void = {}) {
guard !resource.isNil else {
playlists = []
return
}
let request = force ? resource?.load() : resource?.loadIfNeeded()
2021-09-25 13:48:22 +05:30
guard !request.isNil else {
onSuccess()
return
}
2021-09-25 13:48:22 +05:30
request?
.onSuccess { resource in
if let playlists: [Playlist] = resource.typedContent() {
self.playlists = playlists
onSuccess()
2021-09-25 13:48:22 +05:30
}
}
.onFailure { _ in
self.playlists = []
}
}
2021-10-25 03:06:24 +05:30
func addVideo(playlistID: Playlist.ID, videoID: Video.ID, onSuccess: @escaping () -> Void = {}) {
let resource = accounts.api.playlistVideos(playlistID)
let body = ["videoId": videoID]
2021-10-21 03:51:50 +05:30
resource?.request(.post, json: body).onSuccess { _ in
self.load(force: true)
onSuccess()
}
}
2021-10-25 03:06:24 +05:30
func removeVideo(videoIndexID: String, playlistID: Playlist.ID, onSuccess: @escaping () -> Void = {}) {
2021-10-21 03:51:50 +05:30
let resource = accounts.api.playlistVideo(playlistID, videoIndexID)
2021-10-21 03:51:50 +05:30
resource?.request(.delete).onSuccess { _ in
self.load(force: true)
onSuccess()
}
}
private var resource: Resource? {
accounts.api.playlists
}
2021-09-25 13:48:22 +05:30
}