This commit is contained in:
2026-07-09 17:28:37 +07:00
parent 38b704fe18
commit 8ea66d1769
2 changed files with 29 additions and 40 deletions

View File

@@ -24,7 +24,7 @@ import su.reya.coop.repository.MediaRepository
import su.reya.coop.roomId import su.reya.coop.roomId
data class ChatState( data class ChatState(
val rooms: Set<Room> = emptySet(), val rooms: Map<Long, Room> = emptyMap(),
val isSyncing: Boolean = false, val isSyncing: Boolean = false,
val isPartialProcessedGiftWrap: Boolean = false, val isPartialProcessedGiftWrap: Boolean = false,
) )
@@ -48,8 +48,8 @@ class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
private val _sentReports = MutableSharedFlow<Map<EventId, List<RelayUrl>>>() private val _sentReports = MutableSharedFlow<Map<EventId, List<RelayUrl>>>()
val sentReport = _sentReports.asSharedFlow() val sentReport = _sentReports.asSharedFlow()
val chatRooms = state.map { it.rooms } val chatRooms = state.map { it.rooms.values.sortedByDescending { it.createdAt.asSecs() } }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptySet()) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
val isSyncing = state.map { it.isSyncing } val isSyncing = state.map { it.isSyncing }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)
@@ -80,16 +80,12 @@ class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
launch { launch {
nostr.newEvents.collect { event -> nostr.newEvents.collect { event ->
val roomId = event.roomId() val roomId = event.roomId()
val existingRoom = _state.value.rooms.firstOrNull { it.id == roomId } val existingRoom = _state.value.rooms[roomId]
if (existingRoom == null) { if (existingRoom == null) {
val currentUser = nostr.signer.getPublicKeyAsync() ?: return@collect val currentUser = nostr.signer.getPublicKeyAsync() ?: return@collect
val newRoom = Room.new(event, currentUser) val newRoom = Room.new(event, currentUser)
_state.update { _state.update { it.copy(rooms = it.rooms + (newRoom.id to newRoom)) }
it.copy(
rooms = (it.rooms + newRoom).sortedDescending().toSet()
)
}
} else { } else {
updateRoomList(roomId, event) updateRoomList(roomId, event)
} }
@@ -117,7 +113,7 @@ class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
// Check if the room already exists // Check if the room already exists
val id = rumor.roomId() val id = rumor.roomId()
val existingRoom = _state.value.rooms.firstOrNull { it.id == id } val existingRoom = _state.value.rooms[id]
// If the room already exists, return its ID // If the room already exists, return its ID
if (existingRoom != null) { if (existingRoom != null) {
@@ -128,7 +124,7 @@ class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
val room = Room.new(rumor, currentUser) val room = Room.new(rumor, currentUser)
// Update the chat rooms state // Update the chat rooms state
_state.update { it.copy(rooms = (it.rooms + room).sortedDescending().toSet()) } _state.update { it.copy(rooms = it.rooms + (room.id to room)) }
return room.id return room.id
} catch (e: Exception) { } catch (e: Exception) {
@@ -137,18 +133,16 @@ class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
} }
fun getChatRoom(id: Long): Room? { fun getChatRoom(id: Long): Room? {
return _state.value.rooms.firstOrNull { it.id == id } return _state.value.rooms[id]
} }
suspend fun refreshChatRooms() { suspend fun refreshChatRooms() {
try { try {
val rooms = nostr.messages.getChatRooms() ?: emptySet() val rooms = nostr.messages.getChatRooms() ?: emptySet()
_state.update { currentState -> _state.update { currentState ->
val merged = currentState.rooms.associateBy { it.id }.toMutableMap() val newMap = currentState.rooms.toMutableMap()
// Add or update rooms from the database rooms.forEach { room -> newMap[room.id] = room }
rooms.forEach { room -> merged[room.id] = room } currentState.copy(rooms = newMap)
// Return as a sorted set to maintain UI consistency
currentState.copy(rooms = merged.values.sortedDescending().toSet())
} }
} catch (e: Exception) { } catch (e: Exception) {
showError("Error: ${e.message}") showError("Error: ${e.message}")
@@ -230,24 +224,19 @@ class ChatViewModel(private val nostr: Nostr) : BaseViewModel() {
private fun updateRoomList(roomId: Long, newMessage: UnsignedEvent) { private fun updateRoomList(roomId: Long, newMessage: UnsignedEvent) {
_state.update { currentState -> _state.update { currentState ->
val updatedRooms = currentState.rooms.map { room -> val room = currentState.rooms[roomId] ?: return@update currentState
if (room.id == roomId) { val updatedRoom = room.copy(
room.copy( lastMessage = newMessage.content(),
lastMessage = newMessage.content(), createdAt = newMessage.createdAt()
createdAt = newMessage.createdAt() )
) currentState.copy(rooms = currentState.rooms + (roomId to updatedRoom))
} else {
room
}
}.sortedDescending().toSet()
currentState.copy(rooms = updatedRooms)
} }
} }
fun resetInternalState() { fun resetInternalState() {
_state.update { _state.update {
it.copy( it.copy(
rooms = emptySet(), rooms = emptyMap(),
isPartialProcessedGiftWrap = false, isPartialProcessedGiftWrap = false,
) )
} }

View File

@@ -158,12 +158,14 @@ class NostrViewModel(private val nostr: Nostr) : BaseViewModel() {
viewModelScope.launch { viewModelScope.launch {
// Wait until the client is ready // Wait until the client is ready
nostr.waitUntilInitialized() nostr.waitUntilInitialized()
val cache = nostr.profiles.getAllCacheMetadata()
nostr.profiles.getAllCacheMetadata().forEach { (pubkey, metadata) -> profilesMutex.withLock {
// Update the metadata state cache.forEach { (pubkey, metadata) ->
updateMetadata(pubkey, Profile(pubkey, metadata)) val profile = Profile(pubkey, metadata)
// Update seenPublicKeys to avoid duplicate requests profiles.getOrPut(pubkey) { MutableStateFlow(null) }.value = profile
seenPublicKeys.add(pubkey) seenPublicKeys.add(pubkey)
}
} }
} }
} }
@@ -196,11 +198,9 @@ class NostrViewModel(private val nostr: Nostr) : BaseViewModel() {
} }
} }
private fun updateMetadata(pubkey: PublicKey, profile: Profile) { private suspend fun updateMetadata(pubkey: PublicKey, profile: Profile) {
viewModelScope.launch { profilesMutex.withLock {
profilesMutex.withLock { profiles.getOrPut(pubkey) { MutableStateFlow(null) }.value = profile
profiles.getOrPut(pubkey) { MutableStateFlow(null) }.value = profile
}
} }
} }