IceCubesApp/Packages/Timeline/Sources/Timeline/TimelineViewModel.swift

378 lines
12 KiB
Swift
Raw Normal View History

2023-01-17 10:36:01 +00:00
import Env
2022-11-29 08:28:17 +00:00
import Models
2023-01-17 10:36:01 +00:00
import Network
2022-12-19 06:17:01 +00:00
import Status
2023-01-17 10:36:01 +00:00
import SwiftUI
2022-11-25 11:00:01 +00:00
@MainActor
class TimelineViewModel: ObservableObject {
@Published var scrollToIndex: Int?
2022-12-19 06:17:01 +00:00
@Published var statusesState: StatusesState = .loading
@Published var timeline: TimelineFilter = .federated {
2022-12-01 08:05:26 +00:00
didSet {
2023-02-08 17:46:09 +00:00
timelineTask?.cancel()
timelineTask = Task {
if timeline == .latest, let client {
await cache.clearCache(for: client)
timeline = .home
}
if oldValue != timeline {
statuses = []
pendingStatusesObserver.pendingStatuses = []
2023-01-04 17:37:58 +00:00
tag = nil
}
2023-02-08 17:46:09 +00:00
guard !Task.isCancelled else {
return
}
await fetchStatuses()
2022-12-25 07:17:16 +00:00
switch timeline {
case let .hashtag(tag, _):
await fetchTag(id: tag)
default:
break
2022-12-01 08:05:26 +00:00
}
}
}
}
2023-02-12 15:29:41 +00:00
2023-02-08 17:46:09 +00:00
private var timelineTask: Task<Void, Never>?
2023-01-17 10:36:01 +00:00
2022-12-21 11:39:29 +00:00
@Published var tag: Tag?
2023-01-17 10:36:01 +00:00
2023-02-04 16:17:38 +00:00
// Internal source of truth for a timeline.
private var statuses: [Status] = []
private let cache: TimelineCache = .shared
private var visibileStatusesIds = Set<String>()
private var canStreamEvents: Bool = true
private var accountId: String? {
CurrentAccount.shared.account?.id
}
var client: Client? {
didSet {
if oldValue != client {
statuses = []
}
}
}
var scrollToTopVisible: Bool = false {
didSet {
if scrollToTopVisible {
pendingStatusesObserver.pendingStatuses = []
}
}
}
var pendingStatusesEnabled: Bool {
timeline == .home
}
2023-01-17 10:36:01 +00:00
2022-11-25 11:00:01 +00:00
var serverName: String {
2022-12-19 11:28:55 +00:00
client?.server ?? "Error"
2022-11-25 11:00:01 +00:00
}
2023-02-04 16:17:38 +00:00
var isTimelineVisible: Bool = false
let pendingStatusesObserver: PendingStatusesObserver = .init()
var scrollToIndexAnimated: Bool = false
init() {
pendingStatusesObserver.scrollToIndex = { [weak self] index in
self?.scrollToIndexAnimated = true
self?.scrollToIndex = index
}
}
2023-01-17 10:36:01 +00:00
private func fetchTag(id: String) async {
guard let client else { return }
do {
tag = try await client.get(endpoint: Tags.tag(id: id))
} catch {}
}
2023-02-01 11:49:59 +00:00
func handleEvent(event: any StreamEvent, currentAccount _: CurrentAccount) {
if let event = event as? StreamEventUpdate,
canStreamEvents,
isTimelineVisible,
pendingStatusesEnabled,
!statuses.contains(where: { $0.id == event.status.id })
{
pendingStatusesObserver.pendingStatuses.insert(event.status.id, at: 0)
2023-02-18 06:42:35 +00:00
let newStatus = event.status
if let accountId {
if newStatus.mentions.first(where: { $0.id == accountId }) != nil {
2023-02-08 17:47:09 +00:00
newStatus.userMentioned = true
}
}
statuses.insert(newStatus, at: 0)
2023-02-01 12:28:04 +00:00
Task {
2023-02-01 12:41:28 +00:00
await cacheHome()
2023-02-01 12:28:04 +00:00
}
withAnimation {
statusesState = .display(statuses: statuses, nextPageState: .hasNextPage)
}
} else if let event = event as? StreamEventDelete {
withAnimation {
statuses.removeAll(where: { $0.id == event.status })
2023-02-01 12:28:04 +00:00
Task {
2023-02-01 12:41:28 +00:00
await cacheHome()
2023-02-01 12:28:04 +00:00
}
statusesState = .display(statuses: statuses, nextPageState: .hasNextPage)
}
} else if let event = event as? StreamEventStatusUpdate {
if let originalIndex = statuses.firstIndex(where: { $0.id == event.status.id }) {
statuses[originalIndex] = event.status
2023-02-01 12:28:04 +00:00
Task {
2023-02-01 12:41:28 +00:00
await cacheHome()
2023-02-01 12:28:04 +00:00
}
statusesState = .display(statuses: statuses, nextPageState: .hasNextPage)
}
}
}
}
// MARK: - Cache
2023-02-01 11:49:59 +00:00
extension TimelineViewModel {
2023-02-01 12:41:28 +00:00
private func cacheHome() async {
if let client, timeline == .home {
await cache.set(statuses: statuses, client: client)
}
}
2023-02-01 11:49:59 +00:00
private func getCachedStatuses() async -> [Status]? {
if let client {
return await cache.getStatuses(for: client)
}
return nil
}
}
// MARK: - StatusesFetcher
2023-02-01 11:49:59 +00:00
extension TimelineViewModel: StatusesFetcher {
2022-12-19 06:17:01 +00:00
func fetchStatuses() async {
2023-01-31 12:43:27 +00:00
guard let client else { return }
2022-11-25 11:00:01 +00:00
do {
if statuses.isEmpty || timeline == .trending {
if !statuses.isEmpty && timeline == .trending {
return
}
try await fetchFirstPage(client: client)
} else if let latest = statuses.first {
try await fetchNewPagesFrom(latestStatus: latest, client: client)
}
2022-11-25 11:00:01 +00:00
} catch {
2022-12-19 06:17:01 +00:00
statusesState = .error(error: error)
canStreamEvents = true
2022-12-21 11:39:29 +00:00
print("timeline parse error: \(error)")
2022-11-25 11:00:01 +00:00
}
}
2023-02-01 11:49:59 +00:00
// Hydrate statuses in the Timeline when statuses are empty.
private func fetchFirstPage(client: Client) async throws {
pendingStatusesObserver.pendingStatuses = []
2023-02-12 15:29:41 +00:00
2023-02-08 17:46:09 +00:00
if statuses.isEmpty {
statusesState = .loading
}
2023-02-01 11:49:59 +00:00
// If we get statuses from the cache for the home timeline, we displays those.
// Else we fetch top most page from the API.
2023-02-04 11:17:16 +00:00
if let cachedStatuses = await getCachedStatuses(),
2023-02-04 16:17:38 +00:00
!cachedStatuses.isEmpty,
timeline == .home
{
statuses = cachedStatuses
2023-02-04 13:42:10 +00:00
if let latestSeenId = await cache.getLatestSeenStatus(for: client)?.last,
let index = statuses.firstIndex(where: { $0.id == latestSeenId }),
2023-02-04 16:17:38 +00:00
index > 0
{
2023-02-04 13:42:10 +00:00
// Restore cache and scroll to latest seen status.
2023-02-04 19:37:22 +00:00
statusesState = .display(statuses: statuses, nextPageState: .hasNextPage)
2023-02-04 13:42:10 +00:00
scrollToIndexAnimated = false
scrollToIndex = index + 1
} else {
// Restore cache and scroll to top.
withAnimation {
2023-02-04 19:37:22 +00:00
statusesState = .display(statuses: statuses, nextPageState: .hasNextPage)
2023-02-04 13:42:10 +00:00
}
}
// And then we fetch statuses again toget newest statuses from there.
await fetchStatuses()
} else {
statuses = try await client.get(endpoint: timeline.endpoint(sinceId: nil,
maxId: nil,
minId: nil,
offset: 0))
updateMentionsToBeHighlighted(&statuses)
ReblogCache.shared.removeDuplicateReblogs(&statuses)
2023-02-01 12:41:28 +00:00
await cacheHome()
2023-02-12 15:29:41 +00:00
withAnimation {
statusesState = .display(statuses: statuses, nextPageState: statuses.count < 20 ? .none : .hasNextPage)
}
}
}
2023-02-01 11:49:59 +00:00
// Fetch pages from the top most status of the tomeline.
2023-02-01 11:49:59 +00:00
private func fetchNewPagesFrom(latestStatus: Status, client _: Client) async throws {
canStreamEvents = false
let initialTimeline = timeline
var newStatuses: [Status] = await fetchNewPages(minId: latestStatus.id, maxPages: 10)
2023-02-01 11:49:59 +00:00
// Dedup statuses, a status with the same id could have been streamed in.
newStatuses = newStatuses.filter { status in
!statuses.contains(where: { $0.id == status.id })
}
2023-02-04 16:17:38 +00:00
ReblogCache.shared.removeDuplicateReblogs(&newStatuses)
// If no new statuses, resume streaming and exit.
guard !newStatuses.isEmpty else {
canStreamEvents = true
return
}
2023-02-04 16:17:38 +00:00
// If the timeline is not visible, we don't update it as it would mess up the user position.
guard isTimelineVisible else {
canStreamEvents = true
return
}
2023-02-12 15:29:41 +00:00
2023-02-08 17:46:09 +00:00
// Return if task has been cancelled.
guard !Task.isCancelled else {
canStreamEvents = true
return
}
2023-02-18 06:26:48 +00:00
// As this is a long runnign task we need to ensure that the user didn't changed the timeline filter.
guard initialTimeline == timeline else {
canStreamEvents = true
return
}
2023-02-01 11:49:59 +00:00
// Keep track of the top most status, so we can scroll back to it after view update.
let topStatusId = statuses.first?.id
2023-02-01 11:49:59 +00:00
// Insert new statuses in internal datasource.
statuses.insert(contentsOf: newStatuses, at: 0)
2023-02-01 11:49:59 +00:00
// Cache statuses for home timeline.
2023-02-01 12:41:28 +00:00
await cacheHome()
2023-02-01 11:49:59 +00:00
// If pending statuses are not enabled, we simply load status on the top regardless of the current position.
if !pendingStatusesEnabled {
pendingStatusesObserver.pendingStatuses = []
withAnimation {
statusesState = .display(statuses: statuses, nextPageState: statuses.count < 20 ? .none : .hasNextPage)
canStreamEvents = true
}
} else {
// Append new statuses in the timeline indicator.
2023-02-01 11:49:59 +00:00
pendingStatusesObserver.pendingStatuses.insert(contentsOf: newStatuses.map { $0.id }, at: 0)
// High chance the user is scrolled to the top.
// We need to update the statuses state, and then scroll to the previous top most status.
if let topStatusId, visibileStatusesIds.contains(topStatusId), scrollToTopVisible {
pendingStatusesObserver.disableUpdate = true
statusesState = .display(statuses: statuses, nextPageState: statuses.count < 20 ? .none : .hasNextPage)
scrollToIndexAnimated = false
scrollToIndex = newStatuses.count + 1
DispatchQueue.main.async {
self.pendingStatusesObserver.disableUpdate = false
self.canStreamEvents = true
}
} else {
// This will keep the scroll position (if the list is scrolled) and prepend statuses on the top.
withAnimation {
statusesState = .display(statuses: statuses, nextPageState: statuses.count < 20 ? .none : .hasNextPage)
canStreamEvents = true
}
}
2023-02-12 15:29:41 +00:00
// We trigger a new fetch so we can get the next new statuses if any.
// If none, it'll stop there.
2023-02-08 17:46:09 +00:00
if !Task.isCancelled, let latest = statuses.first, let client {
try await fetchNewPagesFrom(latestStatus: latest, client: client)
}
}
}
2023-02-01 11:49:59 +00:00
private func fetchNewPages(minId: String, maxPages: Int) async -> [Status] {
guard let client else { return [] }
var pagesLoaded = 0
var allStatuses: [Status] = []
var latestMinId = minId
do {
while var newStatuses: [Status] = try await client.get(endpoint: timeline.endpoint(sinceId: nil,
maxId: nil,
2023-01-01 13:28:15 +00:00
minId: latestMinId,
offset: statuses.count)),
2023-01-17 10:36:01 +00:00
!newStatuses.isEmpty,
pagesLoaded < maxPages
{
pagesLoaded += 1
updateMentionsToBeHighlighted(&newStatuses)
ReblogCache.shared.removeDuplicateReblogs(&newStatuses)
2023-02-04 16:17:38 +00:00
allStatuses.insert(contentsOf: newStatuses, at: 0)
latestMinId = newStatuses.first?.id ?? ""
}
} catch {
2023-01-05 05:39:23 +00:00
return allStatuses
}
return allStatuses
}
2023-02-01 11:49:59 +00:00
2022-12-19 06:17:01 +00:00
func fetchNextPage() async {
2022-12-19 11:28:55 +00:00
guard let client else { return }
2022-11-25 11:00:01 +00:00
do {
guard let lastId = statuses.last?.id else { return }
2022-12-19 06:17:01 +00:00
statusesState = .display(statuses: statuses, nextPageState: .loadingNextPage)
var newStatuses: [Status] = try await client.get(endpoint: timeline.endpoint(sinceId: nil,
maxId: lastId,
2023-01-01 13:28:15 +00:00
minId: nil,
offset: statuses.count))
updateMentionsToBeHighlighted(&newStatuses)
ReblogCache.shared.removeDuplicateReblogs(&newStatuses)
2022-11-25 11:00:01 +00:00
statuses.append(contentsOf: newStatuses)
2023-02-04 19:37:22 +00:00
statusesState = .display(statuses: statuses, nextPageState: newStatuses.count < 20 ? .none : .hasNextPage)
2022-11-25 11:00:01 +00:00
} catch {
2022-12-19 06:17:01 +00:00
statusesState = .error(error: error)
2022-11-25 11:00:01 +00:00
}
}
2023-02-01 11:49:59 +00:00
private func updateMentionsToBeHighlighted(_ statuses: inout [Status]) {
if !statuses.isEmpty, let accountId {
for i in statuses.indices {
if statuses[i].mentions.first(where: { $0.id == accountId }) != nil {
2023-02-08 17:47:09 +00:00
statuses[i].userMentioned = true
}
}
}
}
2023-01-31 07:04:35 +00:00
func statusDidAppear(status: Status) {
pendingStatusesObserver.removeStatus(status: status)
visibileStatusesIds.insert(status.id)
2023-02-04 16:17:38 +00:00
2023-02-04 13:42:10 +00:00
if let client, timeline == .home {
Task {
2023-02-04 16:17:38 +00:00
await cache.setLatestSeenStatuses(ids: visibileStatusesIds.map { $0 }, for: client)
2023-02-04 13:42:10 +00:00
}
}
}
2023-02-01 11:49:59 +00:00
func statusDidDisappear(status: Status) {
visibileStatusesIds.remove(status.id)
2023-01-05 06:07:28 +00:00
}
2022-11-25 11:00:01 +00:00
}