Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1858,6 +1861,13 @@ class ChatActivity :
}
}
}

this.lifecycleScope.launch {
chatViewModel.cachedThreadReplies.collect { replies ->
cachedThreadReplies = replies
updateToolbarState()
}
}
}

private fun removeUnreadMessagesMarker() {
Expand Down Expand Up @@ -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 -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,15 @@ interface ChatMessageRepository : LifecycleAwareManager {

fun observeParentMessages(parentIds: List<Long>): Flow<List<ChatMessage>>

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<Long, Int>)

/**
* 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<Int?>

@Suppress("LongParameterList")
suspend fun sendChatMessage(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Long, Int>) =
chatDao.updateThreadRepliesOfThreads(internalConversationId, threadReplies)

override fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow<Int?> =
chatDao.observeThreadReplies(internalConversationId, threadId)
.distinctUntilChanged()

override fun getMessage(messageId: Long, bundle: Bundle): Flow<ChatMessage> =
flow {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Int> =
conversationThreadId?.let { threadId ->
conversationAndUserFlow
.flatMapLatest { (conversation, _) ->
chatRepository.observeThreadReplies(conversation.internalId, threadId)
}
.filterNotNull()
.distinctUntilChanged()
} ?: emptyFlow()

// ------------------------------
// Last read message cache
// ------------------------------
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,23 @@ interface ChatMessagesDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertChatMessages(chatMessages: List<ChatMessageEntity>)

/**
* 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<ChatMessageEntity>) {
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 }
Expand All @@ -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<Int?>

/**
* 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<Long, Int>) {
threadReplies.forEach { (threadId, replies) ->
updateThreadReplies(internalConversationId, threadId, replies)
}
}

@Query(
"""
SELECT EXISTS(
Expand Down Expand Up @@ -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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<Int?> = flowOf()

override suspend fun hasServerCopyOfReferenceId(internalConversationId: String, referenceId: String): Boolean =
false

Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading