yattee/Model/CommentsModel.swift

108 lines
2.8 KiB
Swift
Raw Normal View History

2021-12-04 19:35:41 +00:00
import Defaults
import Foundation
import SwiftyJSON
final class CommentsModel: ObservableObject {
static let shared = CommentsModel()
2021-12-04 19:35:41 +00:00
@Published var all = [Comment]()
@Published var nextPage: String?
@Published var firstPage = true
2021-12-17 19:46:49 +00:00
@Published var loaded = false
@Published var disabled = false
@Published var replies = [Comment]()
@Published var repliesPageID: String?
@Published var repliesLoaded = false
2021-12-04 19:35:41 +00:00
var player = PlayerModel.shared
var accounts = AccountsModel.shared
2021-12-04 19:35:41 +00:00
2022-07-01 22:14:04 +00:00
var instance: Instance? {
accounts.current?.instance
}
2021-12-04 19:35:41 +00:00
var nextPageAvailable: Bool {
!(nextPage?.isEmpty ?? true)
}
2022-11-13 17:52:15 +00:00
func loadIfNeeded() {
guard !loaded else { return }
load()
}
2021-12-04 19:35:41 +00:00
func load(page: String? = nil) {
2022-07-01 22:14:04 +00:00
guard let video = player.currentVideo else { return }
guard firstPage || nextPageAvailable else { return }
2021-12-04 19:35:41 +00:00
2023-04-22 13:08:33 +00:00
player
.playerAPI(video)?
.comments(video.videoID, page: page)?
2021-12-04 19:35:41 +00:00
.load()
.onSuccess { [weak self] response in
guard let self else { return }
if let commentsPage: CommentsPage = response.typedContent() {
self.all += commentsPage.comments
self.nextPage = commentsPage.nextPage
self.disabled = commentsPage.disabled
2021-12-04 19:35:41 +00:00
}
}
2024-04-01 12:00:02 +00:00
.onFailure { [weak self] _ in
self?.disabled = true
2022-07-01 22:14:04 +00:00
}
2021-12-04 19:35:41 +00:00
.onCompletion { [weak self] _ in
self?.loaded = true
}
}
2022-01-05 16:12:32 +00:00
func loadNextPageIfNeeded(current comment: Comment) {
let thresholdIndex = all.index(all.endIndex, offsetBy: -5)
if all.firstIndex(where: { $0 == comment }) == thresholdIndex {
loadNextPage()
}
}
2021-12-04 19:35:41 +00:00
func loadNextPage() {
2023-06-07 20:56:29 +00:00
guard nextPageAvailable else { return }
2021-12-04 19:35:41 +00:00
load(page: nextPage)
}
func loadReplies(page: String) {
guard !player.currentVideo.isNil else {
return
}
if page == repliesPageID {
return
}
2021-12-04 19:35:41 +00:00
replies = []
repliesPageID = page
repliesLoaded = false
2021-12-04 19:35:41 +00:00
accounts.api.comments(player.currentVideo!.videoID, page: page)?
.load()
.onSuccess { [weak self] response in
if let page: CommentsPage = response.typedContent() {
self?.replies = page.comments
2021-12-17 19:46:49 +00:00
self?.repliesLoaded = true
}
}
2021-12-17 19:46:49 +00:00
.onFailure { [weak self] _ in
self?.repliesLoaded = true
2021-12-04 19:35:41 +00:00
}
}
func reset() {
2021-12-04 19:35:41 +00:00
all = []
disabled = false
2021-12-04 19:35:41 +00:00
firstPage = true
nextPage = nil
loaded = false
replies = []
repliesLoaded = false
2021-12-04 19:35:41 +00:00
}
}