Files
Morgan Pretty ac9816b118 Massive refactors of the SessionThreadViewModel and MessageViewModel
The `SessionThreadViewModel` has been renamed to `ConversationInfoViewModel` and is now a simple struct (as opposed to a FetchableRecord with a handful of behemoth database queries)

The `ConversationInfoViewModel` and `MessageViewModel` now get initialised with a `ConversationDataCache` which is an object that holds a bunch of [ID -> Data] stores for various types that are needed to construct the aforementioned view models. The `ConversationDataCache` will generally be populated via the `ConversationDataHelper` which, when combined with our `ObservableEvent` system, is where the majority of the work for this refactoring has gone. This helper essentially has 4 parts:
- `determineFetchRequirements`: Reviews any events which have come through and determines whether anything needs to be fetched from the database
- `applyNonDatabaseEvents`: Updates the cached data directly based on delta information included in the `ObservableEvent` instances
- `fetchFromDatabase`: Fetches any data from the database based on the info returned from `determineFetchRequirements`, this function will also resolve any dependant data that newly fetched objects need if they aren't already in the cache
- `fetchFromLibSession`: Retrieves requested data from libSession

Using the above setup all screens which contain conversation or message data now use these two view models, and can share the state of the view models between each other to reduce the need to refetch data when entering a new screen

Some additional changes included due to the above are:
• No longer need to pass `displayNameRetriever` throughout
• Removed deprecated display name retrieval functions
• Removed some duplicate code
• Removed some synchronous database query hacks we needed until refactoring had been completed
• Refactored mentions to be handled by tags
• Refactored and optimised the searching logic (also added some caching)
• Refactored the ThreadSettingsViewModel to use the new ObservationBuilder system
• Refactored the ThreadPickerViewModel to use the new ObservationBuilder system
• Refactored the HomeViewModel to retrieve data using the `ConversationDataHelper`
• Refactored the ConversationViewModel to retrieve data using the `ConversationDataHelper`
• Fixed an issue where communities weren't getting the correct "joined" timestamp
2025-12-11 16:47:37 +11:00

139 lines
5.6 KiB
Swift

// Copyright © 2023 Rangeproof Pty Ltd. All rights reserved.
import Foundation
import Combine
import GRDB
import SessionUtilitiesKit
import SessionNetworkingKit
public enum ExpirationUpdateJob: JobExecutor {
public static var maxFailureCount: Int = -1
public static var requiresThreadId: Bool = true
public static var requiresInteractionId: Bool = false
public static func run<S: Scheduler>(
_ job: Job,
scheduler: S,
success: @escaping (Job, Bool) -> Void,
failure: @escaping (Job, Error, Bool) -> Void,
deferred: @escaping (Job) -> Void,
using dependencies: Dependencies
) {
guard
let detailsData: Data = job.details,
let details: Details = try? JSONDecoder(using: dependencies).decode(Details.self, from: detailsData)
else { return failure(job, JobRunnerError.missingRequiredDetails, true) }
AnyPublisher
.lazy {
try Network.SnodeAPI
.preparedUpdateExpiry(
serverHashes: details.serverHashes,
updatedExpiryMs: details.expirationTimestampMs,
shortenOnly: true,
authMethod: try Authentication.with(
swarmPublicKey: dependencies[cache: .general].sessionId.hexString,
using: dependencies
),
using: dependencies
)
}
.flatMap { $0.send(using: dependencies) }
.subscribe(on: scheduler, using: dependencies)
.receive(on: scheduler, using: dependencies)
.map { _, response -> [UInt64: [String]] in
guard
let results: [UpdateExpiryResponseResult] = response
.compactMap({ _, value in value.didError ? nil : value })
.nullIfEmpty,
let unchangedMessages: [UInt64: [String]] = results
.reduce([:], { result, next in result.updated(with: next.unchanged) })
.groupedByValue()
.nullIfEmpty
else { return [:] }
return unchangedMessages
}
.sinkUntilComplete(
receiveCompletion: { result in
switch result {
case .finished: success(job, false)
case .failure(let error): failure(job, error, true)
}
},
receiveValue: { unchangedMessages in
guard !unchangedMessages.isEmpty else { return }
dependencies[singleton: .storage].writeAsync { db in
unchangedMessages.forEach { updatedExpiry, hashes in
hashes.forEach { hash in
guard
let interaction: Interaction = try? Interaction
.filter(Interaction.Columns.serverHash == hash)
.fetchOne(db),
let expiresInSeconds: TimeInterval = interaction.expiresInSeconds
else { return }
let expiresStartedAtMs: Double = Double(updatedExpiry - UInt64(expiresInSeconds * 1000))
dependencies[singleton: .jobRunner].upsert(
db,
job: DisappearingMessagesJob.updateNextRunIfNeeded(
db,
interaction: interaction,
startedAtMs: expiresStartedAtMs,
using: dependencies
),
canStartJob: true
)
}
}
}
}
)
}
}
// MARK: - ExpirationUpdateJob.Details
extension ExpirationUpdateJob {
public struct Details: Codable {
private enum CodingKeys: String, CodingKey {
case serverHashes
case expirationTimestampMs
}
public let serverHashes: [String]
public let expirationTimestampMs: Int64
// MARK: - Initialization
public init(
serverHashes: [String],
expirationTimestampMs: Int64
) {
self.serverHashes = serverHashes
self.expirationTimestampMs = expirationTimestampMs
}
// MARK: - Codable
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self = Details(
serverHashes: try container.decode([String].self, forKey: .serverHashes),
expirationTimestampMs: try container.decode(Int64.self, forKey: .expirationTimestampMs)
)
}
public func encode(to encoder: Encoder) throws {
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
try container.encode(serverHashes, forKey: .serverHashes)
try container.encode(expirationTimestampMs, forKey: .expirationTimestampMs)
}
}
}