1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-13 22:00:31 +05:30
yattee/Model/SubscriptionsModel.swift

63 lines
1.7 KiB
Swift
Raw Normal View History

2021-09-25 13:48:22 +05:30
import Foundation
import Siesta
import SwiftUI
final class SubscriptionsModel: ObservableObject {
@Published var channels = [Channel]()
2021-10-17 04:18:58 +05:30
var accounts: AccountsModel
2021-10-21 03:51:50 +05:30
var resource: Resource? {
accounts.api.subscriptions
2021-09-25 13:48:22 +05:30
}
2021-10-17 04:18:58 +05:30
init(accounts: AccountsModel? = nil) {
self.accounts = accounts ?? AccountsModel()
2021-09-25 13:48:22 +05:30
}
var all: [Channel] {
channels.sorted { $0.name.lowercased() < $1.name.lowercased() }
}
func subscribe(_ channelID: String, onSuccess: @escaping () -> Void = {}) {
accounts.api.subscribe(channelID) {
self.scheduleLoad(onSuccess: onSuccess)
}
2021-09-25 13:48:22 +05:30
}
func unsubscribe(_ channelID: String, onSuccess: @escaping () -> Void = {}) {
accounts.api.unsubscribe(channelID) {
self.scheduleLoad(onSuccess: onSuccess)
}
2021-09-25 13:48:22 +05:30
}
func isSubscribing(_ channelID: String) -> Bool {
channels.contains { $0.id == channelID }
}
func load(force: Bool = false, onSuccess: @escaping () -> Void = {}) {
guard accounts.app.supportsSubscriptions, accounts.signedIn else {
channels = []
return
}
2021-10-21 03:51:50 +05:30
let request = force ? resource?.load() : resource?.loadIfNeeded()
2021-09-25 13:48:22 +05:30
request?
.onSuccess { resource in
if let channels: [Channel] = resource.typedContent() {
self.channels = channels
onSuccess()
}
}
.onFailure { _ in
self.channels = []
}
}
private func scheduleLoad(onSuccess: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
2021-09-25 13:48:22 +05:30
self.load(force: true, onSuccess: onSuccess)
}
}
}