2021-09-25 08:18:22 +00:00
|
|
|
import Foundation
|
|
|
|
import Siesta
|
|
|
|
import SwiftUI
|
|
|
|
|
|
|
|
final class PlaylistsModel: ObservableObject {
|
|
|
|
@Published var playlists = [Playlist]()
|
2021-09-28 18:06:05 +00:00
|
|
|
@Published var api = InvidiousAPI()
|
2021-09-25 08:18:22 +00:00
|
|
|
|
2021-09-28 18:06:05 +00:00
|
|
|
@Published var selectedPlaylistID: Playlist.ID = ""
|
2021-09-25 08:18:22 +00:00
|
|
|
|
2021-09-28 18:06:05 +00:00
|
|
|
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? {
|
2021-09-28 18:06:05 +00:00
|
|
|
playlists.first { $0.id == id }
|
|
|
|
}
|
|
|
|
|
|
|
|
var isEmpty: Bool {
|
|
|
|
playlists.isEmpty
|
2021-09-25 08:18:22 +00:00
|
|
|
}
|
|
|
|
|
2021-09-28 18:06:05 +00:00
|
|
|
func load(force: Bool = false, onSuccess: @escaping () -> Void = {}) {
|
2021-09-25 08:18:22 +00:00
|
|
|
let request = force ? resource.load() : resource.loadIfNeeded()
|
|
|
|
|
|
|
|
request?
|
|
|
|
.onSuccess { resource in
|
|
|
|
if let playlists: [Playlist] = resource.typedContent() {
|
|
|
|
self.playlists = playlists
|
2021-09-28 18:06:05 +00:00
|
|
|
if self.selectedPlaylistID.isEmpty {
|
|
|
|
self.selectPlaylist(self.all.first?.id)
|
|
|
|
}
|
|
|
|
onSuccess()
|
2021-09-25 08:18:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
.onFailure { _ in
|
|
|
|
self.playlists = []
|
|
|
|
}
|
|
|
|
}
|
2021-09-28 18:06:05 +00:00
|
|
|
|
|
|
|
func addVideoToCurrentPlaylist(videoID: Video.ID, onSuccess: @escaping () -> Void = {}) {
|
|
|
|
let resource = api.playlistVideos(currentPlaylist!.id)
|
|
|
|
let body = ["videoId": videoID]
|
|
|
|
|
|
|
|
resource.request(.post, json: body).onSuccess { _ in
|
|
|
|
self.load(force: true)
|
|
|
|
onSuccess()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func removeVideoFromPlaylist(videoIndexID: String, playlistID: Playlist.ID, onSuccess: @escaping () -> Void = {}) {
|
|
|
|
let resource = api.playlistVideo(playlistID, videoIndexID)
|
|
|
|
|
|
|
|
resource.request(.delete).onSuccess { _ in
|
|
|
|
self.load(force: true)
|
|
|
|
onSuccess()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func selectPlaylist(_ id: String?) {
|
|
|
|
selectedPlaylistID = id ?? ""
|
|
|
|
}
|
|
|
|
|
|
|
|
private var resource: Resource {
|
|
|
|
api.playlists
|
|
|
|
}
|
|
|
|
|
|
|
|
private var selectedPlaylist: Playlist? {
|
|
|
|
guard !selectedPlaylistID.isEmpty else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return find(id: selectedPlaylistID)
|
|
|
|
}
|
|
|
|
|
|
|
|
var currentPlaylist: Playlist? {
|
|
|
|
selectedPlaylist ?? all.first
|
|
|
|
}
|
2021-09-25 08:18:22 +00:00
|
|
|
}
|