diff --git a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt index 7759878be85..731b452a110 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt @@ -394,6 +394,9 @@ class ChatActivity : var openedViaNotification: Boolean = false var conversationThreadInfo: ThreadInfoDto? = null + + // Reply count of the open thread from its cached messages, which follows the chat while it is open + private var cachedThreadReplies: Int? = null val conversationUser: User get() = chatViewModel.currentUser lateinit var spreedCapabilities: SpreedCapabilityDto @@ -1858,6 +1861,13 @@ class ChatActivity : } } } + + this.lifecycleScope.launch { + chatViewModel.cachedThreadReplies.collect { replies -> + cachedThreadReplies = replies + updateToolbarState() + } + } } private fun removeUnreadMessagesMarker() { @@ -2177,7 +2187,9 @@ class ChatActivity : private fun buildToolbarSubtitle(conversation: ConversationModel?): String = when { isChatThread() -> { - val count = conversationThreadInfo?.thread?.numReplies ?: 0 + // The thread endpoint is only asked once when the thread is opened, while the cached messages + // follow the chat. A thread's reply count only grows, so the higher of both is the current one. + val count = maxOf(conversationThreadInfo?.thread?.numReplies ?: 0, cachedThreadReplies ?: 0) resources.getQuantityString(R.plurals.thread_replies, count, count) } conversation?.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL -> { diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt index 11a2a806c18..d7cbc5f598c 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt @@ -132,7 +132,15 @@ interface ChatMessageRepository : LifecycleAwareManager { fun observeParentMessages(parentIds: List): Flow> - suspend fun getNumberOfThreadReplies(threadId: Long): Int + /** + * Writes reply counts, keyed by thread id, into the cached root messages of those threads. + */ + suspend fun updateThreadReplies(threadReplies: Map) + + /** + * Emits the highest reply count stored on the cached messages of [threadId], or null while none is cached. + */ + fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow @Suppress("LongParameterList") suspend fun sendChatMessage( diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt index 44f16afb2bc..10c8111aeee 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt @@ -497,8 +497,12 @@ class OfflineFirstChatRepository @Inject constructor( lastCommonRead = newXChatLastCommonRead ) - override suspend fun getNumberOfThreadReplies(threadId: Long): Int = - chatDao.getNumberOfThreadReplies(internalConversationId, threadId) + override suspend fun updateThreadReplies(threadReplies: Map) = + chatDao.updateThreadRepliesOfThreads(internalConversationId, threadReplies) + + override fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow = + chatDao.observeThreadReplies(internalConversationId, threadId) + .distinctUntilChanged() override fun getMessage(messageId: Long, bundle: Bundle): Flow = flow { diff --git a/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt b/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt index 14773d6d63b..8dbda049dfa 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt @@ -121,6 +121,7 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChangedBy +import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first @@ -840,6 +841,21 @@ class ChatViewModel @AssistedInject constructor( } } + /** + * Reply count of the open thread, read from its cached messages. Every thread message carries the thread's + * current count, so this follows the chat while it is open. Emits nothing outside of a thread. + */ + @OptIn(ExperimentalCoroutinesApi::class) + val cachedThreadReplies: Flow = + conversationThreadId?.let { threadId -> + conversationAndUserFlow + .flatMapLatest { (conversation, _) -> + chatRepository.observeThreadReplies(conversation.internalId, threadId) + } + .filterNotNull() + .distinctUntilChanged() + } ?: emptyFlow() + // ------------------------------ // Last read message cache // ------------------------------ @@ -1522,10 +1538,35 @@ class ChatViewModel @AssistedInject constructor( ) getCapabilities(user, chatRoomToken, conversation) + refreshThreadReplies(credentials, user) } .launchIn(viewModelScope) } + /** + * Updates the reply counts of the cached thread roots of the main chat with the counts of the recently + * active threads on the server. Does nothing inside a thread or when the server has no threads. + */ + @Suppress("Detekt.TooGenericExceptionCaught") + private fun refreshThreadReplies(credentials: String, user: User) { + if (conversationThreadId != null) return + viewModelScope.launch { + val capabilities = spreedCapabilities.filterNotNull().first() + if (!hasSpreedFeatureCapability(capabilities, SpreedFeatures.THREADS)) return@launch + try { + val url = ApiUtils.getUrlForRecentThreads(version = 1, baseUrl = user.baseUrl, token = chatRoomToken) + val threads = threadsRepository.getThreads(credentials, url, RECENT_THREADS_LIMIT).ocs?.data.orEmpty() + chatRepository.updateThreadReplies( + threads.mapNotNull { it.thread }.associate { it.id.toLong() to it.numReplies } + ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.e(TAG, "Failed to refresh the reply counts of the recent threads", e) + } + } + } + fun isChatRelaySupported(user: User): Boolean { val websocketInstance = WebSocketConnectionHelper.getWebSocketInstanceForUser(user) return websocketInstance?.supportsChatRelay() == true @@ -2955,6 +2996,7 @@ class ChatViewModel @AssistedInject constructor( const val HTTP_CODE_OK: Int = 200 private const val CONVERSATION_AND_USER_FLOW_SHARING_TIMEOUT_MS = 5_000L private const val WEBSOCKET_CONNECT_TIMEOUT_MS = 3000L + private const val RECENT_THREADS_LIMIT = 50 private const val WEBSOCKET_POLL_INTERVAL_MS = 50L private const val ROOM_REFRESH_DEBOUNCE_MS = 500L private const val MESSAGES_REBUILD_WINDOW_MS = 200L diff --git a/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt b/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt index e7013721b02..5c61fc7a475 100644 --- a/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt +++ b/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt @@ -99,10 +99,23 @@ interface ChatMessagesDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertChatMessages(chatMessages: List) + /** + * Stores [chatMessages], drops the temporary messages their server copies replace, and carries the + * reply count of every thread in [chatMessages] over to its cached root message. The server sends the + * thread's current count with each message of the thread. + */ @Transaction suspend fun upsertChatMessagesAndDeleteTemp(internalConversationId: String, chatMessages: List) { upsertChatMessages(chatMessages) + updateThreadRepliesOfThreads( + internalConversationId, + chatMessages + .filter { it.isThread && it.threadId != null && it.threadReplies != null } + .groupBy { it.threadId!! } + .mapValues { (_, messages) -> messages.maxOf { it.threadReplies!! } } + ) + val referenceIds = chatMessages .mapNotNull { it.referenceId } .ifEmpty { return } @@ -113,6 +126,48 @@ interface ChatMessagesDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertChatMessage(chatMessage: ChatMessageEntity) + /** + * Raises the reply count of the cached root message of [threadId] to [threadReplies]. A thread's reply count + * only grows on the server, so a lower count is a stale one, e.g. from a response that took longer than a + * relayed reply, and is ignored. + */ + @Query( + """ + UPDATE ChatMessages + SET threadReplies = MAX(COALESCE(threadReplies, 0), :threadReplies) + WHERE internalConversationId = :internalConversationId + AND id = :threadId + """ + ) + suspend fun updateThreadReplies(internalConversationId: String, threadId: Long, threadReplies: Int) + + /** + * Emits the highest reply count stored on the cached messages of [threadId], or null while none is cached. + * Every message of a thread carries the thread's count, so this follows the thread even when its root + * message is not cached. + */ + @Query( + """ + SELECT MAX(threadReplies) + FROM ChatMessages + WHERE internalConversationId = :internalConversationId + AND threadId = :threadId + AND isThread = 1 + """ + ) + fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow + + /** + * Raises reply counts, keyed by thread id, on the cached root messages of those threads, all in one + * transaction, see [updateThreadReplies]. + */ + @Transaction + suspend fun updateThreadRepliesOfThreads(internalConversationId: String, threadReplies: Map) { + threadReplies.forEach { (threadId, replies) -> + updateThreadReplies(internalConversationId, threadId, replies) + } + } + @Query( """ SELECT EXISTS( @@ -473,18 +528,4 @@ interface ChatMessagesDao { """ ) fun deleteMessagesOlderThan(internalConversationId: String, messageId: Long) - - @Query( - """ - SELECT COUNT(*) - FROM ChatMessages AS child - INNER JOIN ChatMessages AS parent - ON child.parent = parent.id - WHERE child.internalConversationId = :internalConversationId - AND child.isTemporary = 0 - AND child.messageType = 'comment' - AND parent.threadId = :threadId - """ - ) - fun getNumberOfThreadReplies(internalConversationId: String, threadId: Long): Int } diff --git a/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt b/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt index 40146986ceb..0edd89a9af3 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt @@ -66,6 +66,12 @@ class DummyChatMessagesDaoImpl : ChatMessagesDao { /* */ } + override suspend fun updateThreadReplies(internalConversationId: String, threadId: Long, threadReplies: Int) { + /* */ + } + + override fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow = flowOf() + override suspend fun hasServerCopyOfReferenceId(internalConversationId: String, referenceId: String): Boolean = false @@ -177,8 +183,6 @@ class DummyChatMessagesDaoImpl : ChatMessagesDao { oldestMessageId: Long, newestMessageId: Long ): Long? = null - - override fun getNumberOfThreadReplies(internalConversationId: String, threadId: Long): Int = 0 } class DummyUserDaoImpl : UsersDao { diff --git a/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt b/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt index 42058ca8dae..4229fa29a7f 100644 --- a/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt +++ b/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt @@ -32,6 +32,10 @@ import com.nextcloud.talk.models.json.generic.GenericMetaDto import com.nextcloud.talk.models.json.generic.GenericOCS import com.nextcloud.talk.models.json.generic.GenericOverall import com.nextcloud.talk.models.json.participants.ParticipantDto +import com.nextcloud.talk.models.json.threads.ThreadDto +import com.nextcloud.talk.models.json.threads.ThreadInfoDto +import com.nextcloud.talk.models.json.threads.ThreadsOCS +import com.nextcloud.talk.models.json.threads.ThreadsOverall import com.nextcloud.talk.repositories.reactions.ReactionsRepository import com.nextcloud.talk.repositories.unifiedsearch.UnifiedSearchRepository import com.nextcloud.talk.threadsoverview.data.ThreadsRepository @@ -50,6 +54,10 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain @@ -65,6 +73,7 @@ import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -100,6 +109,8 @@ class ChatViewModelRoomJoinTest { private lateinit var viewModel: ChatViewModel private lateinit var chatRepository: ChatMessageRepository + private lateinit var createViewModel: (threadId: Long?) -> ChatViewModel + private val threadsRepository: ThreadsRepository = mock() private var capabilitiesState: ChatViewModel.ViewState? = null private var initialLoads = 0 private var joins = 0 @@ -130,24 +141,27 @@ class ChatViewModelRoomJoinTest { GenericOverall(GenericOCS(GenericMetaDto(statusCode = HTTP_OK))) } chatRepository = mockWithEmptyFlows() + createViewModel = { threadId -> + ChatViewModel( + mock(), + mock(), + network, + chatRepository, + threadsRepository, + conversations, + mock(), + mock(), + mock(), + mock(), + userManager, + appScope, + USER, + TOKEN, + threadId + ) + } - val newViewModel = ChatViewModel( - mock(), - mock(), - network, - chatRepository, - mock(), - conversations, - mock(), - mock(), - mock(), - mock(), - userManager, - appScope, - USER, - TOKEN, - null - ) + val newViewModel = createViewModel(null) viewModel = ViewModelProvider( viewModelStore, object : ViewModelProvider.Factory { @@ -386,6 +400,61 @@ class ChatViewModelRoomJoinTest { assertTrue(capabilitiesState is ChatViewModel.GetCapabilitiesUpdateState) } + @Test + fun `opening the main chat writes the reply counts of the recent threads into the cached thread roots`() { + whenever(network.getCapabilities(any(), any())).thenReturn( + Observable.just(SpreedCapabilityDto(features = listOf("threads"), config = null, version = "")) + ) + wheneverBlocking { threadsRepository.getThreads(any(), any(), any()) }.doReturn( + ThreadsOverall( + ThreadsOCS( + meta = null, + data = listOf( + ThreadInfoDto(thread = ThreadDto(id = THREAD_ID, numReplies = THREAD_REPLIES)) + ) + ) + ) + ) + conversation.value = ConversationResult.Found(conversationModel(5, remoteServer = REMOTE_SERVER)) + + owner.send(Lifecycle.Event.ON_CREATE) + viewModel.initData() + + verifyBlocking(threadsRepository) { getThreads(any(), any(), eq(MAX_RECENT_THREADS)) } + verifyBlocking(chatRepository) { updateThreadReplies(mapOf(THREAD_ID.toLong() to THREAD_REPLIES)) } + } + + @Test + fun `opening the main chat does not ask for threads when the server has none`() { + whenever(network.getCapabilities(any(), any())).thenReturn(Observable.just(SpreedCapabilityDto())) + conversation.value = ConversationResult.Found(conversationModel(5, remoteServer = REMOTE_SERVER)) + + owner.send(Lifecycle.Event.ON_CREATE) + viewModel.initData() + + verifyBlocking(threadsRepository, never()) { getThreads(any(), any(), any()) } + } + + @Test + fun `inside a thread the reply count follows the cached thread messages`() = + runBlocking { + whenever(chatRepository.observeThreadReplies(any(), eq(THREAD_ID.toLong()))) + .thenReturn(flowOf(null, 3, 3, THREAD_REPLIES)) + owner.send(Lifecycle.Event.ON_CREATE) + + val replies = createViewModel(THREAD_ID.toLong()).cachedThreadReplies.take(2).toList() + + assertEquals(listOf(3, THREAD_REPLIES), replies) + } + + @Test + fun `the main chat has no thread reply count`() = + runBlocking { + owner.send(Lifecycle.Event.ON_CREATE) + + assertEquals(emptyList(), viewModel.cachedThreadReplies.toList()) + } + private fun conversationModel(lastReadMessage: Int, remoteServer: String = ""): ConversationModel = ConversationModel.mapToConversationModel( ConversationDto( @@ -420,6 +489,9 @@ class ChatViewModelRoomJoinTest { private const val TOKEN = "room-token" private const val HTTP_OK = 200 private const val REMOTE_SERVER = "https://remote.example.com" + private const val THREAD_ID = 100 + private const val THREAD_REPLIES = 23 + private const val MAX_RECENT_THREADS = 50 private val USER = User( id = 1, userId = "me", diff --git a/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt b/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt new file mode 100644 index 00000000000..eb5748138a6 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt @@ -0,0 +1,157 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package com.nextcloud.talk.data.database.dao + +import android.app.Application +import android.content.Context +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import com.nextcloud.talk.chat.data.model.ChatMessage +import com.nextcloud.talk.data.database.mappers.asEntity +import com.nextcloud.talk.data.database.model.ChatMessageEntity +import com.nextcloud.talk.data.source.local.TalkDatabase +import com.nextcloud.talk.data.user.model.UserEntity +import com.nextcloud.talk.models.json.chat.ChatMessageDto +import com.nextcloud.talk.models.json.conversations.ConversationDto +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The reply count shown on a thread root is taken from the cached root message, while the server sends the + * thread's current count with every message of the thread. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = Application::class, sdk = [33]) +class ChatMessagesDaoThreadRepliesTest { + + private lateinit var db: TalkDatabase + + @Before + fun setUp() { + val context = ApplicationProvider.getApplicationContext() + db = Room.inMemoryDatabaseBuilder(context, TalkDatabase::class.java).build() + runBlocking { + db.usersDao().saveUser(UserEntity(id = ACCOUNT_ID, userId = "me", username = "me", baseUrl = BASE_URL)) + db.conversationsDao().upsertConversations( + ACCOUNT_ID, + listOf(ConversationDto(token = ROOM_TOKEN).asEntity(ACCOUNT_ID)) + ) + } + } + + @After + fun tearDown() { + db.close() + } + + @Test + fun `a new reply updates the reply count of the cached thread root`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + + store(threadMessage(id = ROOT_ID + 2, threadReplies = 2)) + + assertEquals(2, threadRepliesOfRoot()) + } + + @Test + fun `the highest count of a thread decides the reply count`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + + store( + threadMessage(id = ROOT_ID + 3, threadReplies = 3), + threadMessage(id = ROOT_ID + 2, threadReplies = 2) + ) + + assertEquals(3, threadRepliesOfRoot()) + } + + @Test + fun `a stale count stored later does not lower the reply count`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + store(threadMessage(id = ROOT_ID + 3, threadReplies = 3)) + + store(threadMessage(id = ROOT_ID + 2, threadReplies = 2)) + + assertEquals(3, threadRepliesOfRoot()) + } + + @Test + fun `the reply count of a thread follows its messages when the root is not cached`() = + runBlocking { + store(threadMessage(id = ROOT_ID + 2, threadReplies = 2)) + store(threadMessage(id = ROOT_ID + 3, threadReplies = 3)) + + assertEquals( + 3, + db.chatMessagesDao().observeThreadReplies(INTERNAL_CONVERSATION_ID, ROOT_ID).first() + ) + } + + @Test + fun `a message outside of a thread leaves the reply count alone`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + + store(threadMessage(id = ROOT_ID + 2, threadReplies = 0).copy(isThread = false, threadId = ROOT_ID + 2)) + + assertEquals(1, threadRepliesOfRoot()) + } + + @Test + fun `the reply counts of several threads are written into their cached roots`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + + db.chatMessagesDao().updateThreadRepliesOfThreads( + INTERNAL_CONVERSATION_ID, + mapOf(ROOT_ID to 23, ROOT_ID + 1000 to 5) + ) + + assertEquals(23, threadRepliesOfRoot()) + } + + private suspend fun store(vararg messages: ChatMessageEntity) { + db.chatMessagesDao().upsertChatMessagesAndDeleteTemp(INTERNAL_CONVERSATION_ID, messages.toList()) + } + + private suspend fun threadRepliesOfRoot(): Int? = + db.chatMessagesDao().getChatMessageEntity(INTERNAL_CONVERSATION_ID, ROOT_ID)?.threadReplies + + private fun threadMessage(id: Long, threadReplies: Int) = + ChatMessageDto( + id = id, + token = ROOM_TOKEN, + actorType = "users", + actorId = "other", + actorDisplayName = "Other", + message = "message $id", + messageType = "comment", + systemMessageType = ChatMessage.SystemMessageType.DUMMY, + threadId = ROOT_ID, + hasThread = true, + threadReplies = threadReplies + ).asEntity(ACCOUNT_ID) + + companion object { + private const val ACCOUNT_ID = 1L + private const val ROOM_TOKEN = "room1" + private const val INTERNAL_CONVERSATION_ID = "$ACCOUNT_ID@$ROOM_TOKEN" + private const val BASE_URL = "https://server.example.com" + private const val ROOT_ID = 100L + } +}