yattee/Model/SubscriptionsModel.swift

54 lines
1.6 KiB
Swift
Raw Normal View History

2021-09-25 08:18:22 +00:00
import Foundation
import Siesta
import SwiftUI
final class SubscriptionsModel: ObservableObject {
@Published var channels = [Channel]()
2021-10-16 22:48:58 +00:00
var accounts: AccountsModel
2021-10-20 22:21:50 +00:00
var resource: Resource? {
accounts.api.subscriptions
2021-09-25 08:18:22 +00:00
}
2021-10-16 22:48:58 +00:00
init(accounts: AccountsModel? = nil) {
self.accounts = accounts ?? AccountsModel()
2021-09-25 08:18:22 +00:00
}
var all: [Channel] {
channels.sorted { $0.name.lowercased() < $1.name.lowercased() }
}
func subscribe(_ channelID: String, onSuccess: @escaping () -> Void = {}) {
performRequest(channelID, method: .post, onSuccess: onSuccess)
}
func unsubscribe(_ channelID: String, onSuccess: @escaping () -> Void = {}) {
performRequest(channelID, method: .delete, onSuccess: onSuccess)
}
func isSubscribing(_ channelID: String) -> Bool {
channels.contains { $0.id == channelID }
}
func load(force: Bool = false, onSuccess: @escaping () -> Void = {}) {
2021-10-20 22:21:50 +00:00
let request = force ? resource?.load() : resource?.loadIfNeeded()
2021-09-25 08:18:22 +00:00
request?
.onSuccess { resource in
if let channels: [Channel] = resource.typedContent() {
self.channels = channels
onSuccess()
}
}
.onFailure { _ in
self.channels = []
}
}
fileprivate func performRequest(_ channelID: String, method: RequestMethod, onSuccess: @escaping () -> Void = {}) {
2021-10-20 22:21:50 +00:00
accounts.api.channelSubscription(channelID)?.request(method).onCompletion { _ in
2021-09-25 08:18:22 +00:00
self.load(force: true, onSuccess: onSuccess)
}
}
}