Bubble/Threaded/Data/Content/FetchTimeline.swift

72 lines
2.1 KiB
Swift
Raw Normal View History

2023-12-29 11:17:37 +01:00
//Made by Lumaa
import Foundation
struct FetchTimeline {
2024-01-06 02:51:07 +01:00
var client: Client?
public private(set) var datasource: [Status] = []
2023-12-29 11:17:37 +01:00
public var statusesState: LoadingState = .loading
private var timeline: TimelineFilter = .home
init(client: Client) {
self.client = client
}
2024-01-06 02:51:07 +01:00
init() {
self.client = nil
}
public mutating func fetch(client: Client) async -> [Status] {
self.client = client
2023-12-29 11:17:37 +01:00
self.statusesState = .loading
self.datasource = await fetchNewestStatuses()
2024-01-06 02:51:07 +01:00
self.statusesState = .loaded
return self.datasource
}
public mutating func addStatuses(lastStatusIndex: Int) async -> [Status] {
// print("i: \(lastStatusIndex)\ndatasource-6: \(self.datasource.count - 6)")
2024-01-06 02:51:07 +01:00
guard client != nil && lastStatusIndex >= self.datasource.count - 6 else { return self.datasource }
self.statusesState = .loading
let lastStatus = self.datasource.last!
let newStatuses: [Status] = await fetchNewestStatuses(lastStatusId: lastStatus.id)
self.datasource.append(contentsOf: newStatuses)
self.statusesState = .loaded
print("added posts")
return self.datasource
2023-12-29 11:17:37 +01:00
}
2024-01-06 02:51:07 +01:00
private mutating func fetchNewestStatuses(lastStatusId: String? = nil) async -> [Status] {
guard client != nil else { return [] }
2023-12-29 11:17:37 +01:00
do {
2024-01-06 02:51:07 +01:00
let statuses: [Status] = try await client!.get(endpoint: timeline.endpoint(sinceId: nil, maxId: lastStatusId, minId: nil, offset: 0))
if lastStatusId == nil {
self.datasource = statuses
}
2023-12-29 11:17:37 +01:00
self.statusesState = .loaded
return statuses
} catch {
statusesState = .error(error: error)
print("timeline parse error: \(error)")
}
return []
}
mutating func setTimelineFilter(_ filter: TimelineFilter) {
self.timeline = filter
}
2023-12-29 11:17:37 +01:00
func getStatuses() -> [Status] {
return datasource
}
enum LoadingState {
case loading
case loaded
case error(error: Error)
}
}