2021-09-25 08:18:22 +00:00
|
|
|
import Foundation
|
|
|
|
import Siesta
|
|
|
|
import SwiftUI
|
|
|
|
|
|
|
|
final class SubscriptionsModel: ObservableObject {
|
2022-11-24 20:36:05 +00:00
|
|
|
static var shared = SubscriptionsModel()
|
|
|
|
|
2021-09-25 08:18:22 +00:00
|
|
|
@Published var channels = [Channel]()
|
2022-11-24 20:36:05 +00:00
|
|
|
var accounts: AccountsModel { .shared }
|
2021-10-16 22:48:58 +00:00
|
|
|
|
2021-10-20 22:21:50 +00:00
|
|
|
var resource: Resource? {
|
|
|
|
accounts.api.subscriptions
|
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 = {}) {
|
2021-11-14 23:06:01 +00:00
|
|
|
accounts.api.subscribe(channelID) {
|
|
|
|
self.scheduleLoad(onSuccess: onSuccess)
|
|
|
|
}
|
2021-09-25 08:18:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func unsubscribe(_ channelID: String, onSuccess: @escaping () -> Void = {}) {
|
2021-11-14 23:06:01 +00:00
|
|
|
accounts.api.unsubscribe(channelID) {
|
|
|
|
self.scheduleLoad(onSuccess: onSuccess)
|
|
|
|
}
|
2021-09-25 08:18:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func isSubscribing(_ channelID: String) -> Bool {
|
|
|
|
channels.contains { $0.id == channelID }
|
|
|
|
}
|
|
|
|
|
|
|
|
func load(force: Bool = false, onSuccess: @escaping () -> Void = {}) {
|
2021-12-19 22:27:20 +00:00
|
|
|
guard accounts.app.supportsSubscriptions, accounts.signedIn else {
|
|
|
|
channels = []
|
2021-11-14 23:06:01 +00:00
|
|
|
return
|
|
|
|
}
|
2021-12-19 22:27:20 +00:00
|
|
|
|
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 = []
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-14 23:06:01 +00:00
|
|
|
private func scheduleLoad(onSuccess: @escaping () -> Void) {
|
|
|
|
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
|
2021-09-25 08:18:22 +00:00
|
|
|
self.load(force: true, onSuccess: onSuccess)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|