Vernissage/CoreData/ViewedStatusHandler.swift

74 lines
2.5 KiB
Swift
Raw Normal View History

2023-10-04 18:14:12 +02:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
// Licensed under the Apache License 2.0.
//
import Foundation
2023-10-20 07:45:18 +02:00
import SwiftData
2023-10-04 18:14:12 +02:00
import PixelfedKit
class ViewedStatusHandler {
public static let shared = ViewedStatusHandler()
private init() { }
2023-10-06 17:19:53 +02:00
/// Check if given status (real picture) has been already visible on the timeline (during last month).
2023-10-20 07:45:18 +02:00
func hasBeenAlreadyOnTimeline(accountId: String, status: Status, modelContext: ModelContext) -> Bool {
2023-10-04 18:14:12 +02:00
guard let reblog = status.reblog else {
return false
}
do {
2023-10-20 07:45:18 +02:00
let reblogId = reblog.id
var fetchDescriptor = FetchDescriptor<ViewedStatus>(predicate: #Predicate { viewedStatus in
(viewedStatus.id == reblogId || viewedStatus.reblogId == reblogId) && viewedStatus.pixelfedAccount?.id == accountId
})
fetchDescriptor.fetchLimit = 1
fetchDescriptor.includePendingChanges = true
guard let first = try modelContext.fetch(fetchDescriptor).first else {
2023-10-04 18:14:12 +02:00
return false
}
if first.reblogId == nil {
return true
}
if first.id != status.id {
return true
}
return false
} catch {
2023-10-06 17:19:53 +02:00
CoreDataError.shared.handle(error, message: "Error during fetching viewed statuses (hasBeenAlreadyOnTimeline).")
2023-10-04 18:14:12 +02:00
return false
}
}
2023-10-06 17:19:53 +02:00
/// Mark to delete statuses older then one month.
2023-10-20 07:45:18 +02:00
func deleteOldViewedStatuses(modelContext: ModelContext) {
let oldViewedStatuses = self.getOldViewedStatuses(modelContext: modelContext)
2023-10-06 17:19:53 +02:00
for status in oldViewedStatuses {
2023-10-20 07:45:18 +02:00
modelContext.delete(status)
2023-10-06 17:19:53 +02:00
}
}
2023-10-20 07:45:18 +02:00
private func getOldViewedStatuses(modelContext: ModelContext) -> [ViewedStatus] {
2023-10-06 17:19:53 +02:00
guard let date = Calendar.current.date(byAdding: .month, value: -1, to: Date()) else {
return []
}
do {
2023-10-20 07:45:18 +02:00
var fetchDescriptor = FetchDescriptor<ViewedStatus>(predicate: #Predicate { viewedStatus in
viewedStatus.date < date
})
fetchDescriptor.includePendingChanges = true
return try modelContext.fetch(fetchDescriptor)
2023-10-06 17:19:53 +02:00
} catch {
CoreDataError.shared.handle(error, message: "Error during fetching viewed statuses (getOldViewedStatuses).")
return []
}
}
2023-10-04 18:14:12 +02:00
}