Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetch messages in background #4475

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ interface ChatMessageRepository : LifecycleAwareManager {
withNetworkParams: Bundle
): Job

suspend fun updateRoomMessages(internalConversationId: String, limit: Int)

/**
* Long polls the server for any updates to the chat, if found, it synchronizes
* the database with the server and emits the new messages to [messageFlow],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package com.nextcloud.talk.chat.data.network

import android.os.Bundle
import android.util.Log
import androidx.core.os.bundleOf
import com.nextcloud.talk.chat.ChatActivity
import com.nextcloud.talk.chat.data.ChatMessageRepository
import com.nextcloud.talk.chat.data.model.ChatMessage
Expand All @@ -28,6 +29,8 @@ import com.nextcloud.talk.models.json.chat.ChatOverall
import com.nextcloud.talk.models.json.chat.ChatOverallSingleMessage
import com.nextcloud.talk.models.json.converters.EnumActorTypeConverter
import com.nextcloud.talk.models.json.participants.Participant
import com.nextcloud.talk.utils.CapabilitiesUtil
import com.nextcloud.talk.utils.SpreedFeatures
import com.nextcloud.talk.utils.bundle.BundleKeys
import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew
import com.nextcloud.talk.utils.message.SendMessageUtils
Expand Down Expand Up @@ -292,6 +295,24 @@ class OfflineFirstChatRepository @Inject constructor(
updateUiForLastCommonRead()
}

override suspend fun updateRoomMessages(internalConversationId: String, limit: Int) {
val lastKnown = chatDao.getNewestMessageId(internalConversationId)

Log.d(TAG, "---- updateRoomMessages ------------ with lastKnown: $lastKnown")
val fieldMap = getFieldMap(
lookIntoFuture = true,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lookIntoFuture = true
is wrong. It would trigger the long polling which is not wanted in this case.

timeout = 0,
includeLastKnown = false,
setReadMarker = false,
lastKnown = lastKnown.toInt(),
markNotificationAsRead = false
)

val networkParams = bundleOf()
networkParams.putSerializable(BundleKeys.KEY_FIELD_MAP, fieldMap)
sync(networkParams)
}

override fun initMessagePolling(initialMessageId: Long): Job =
scope.launch {
Log.d(TAG, "---- initMessagePolling ------------")
Expand Down Expand Up @@ -430,7 +451,8 @@ class OfflineFirstChatRepository @Inject constructor(
includeLastKnown: Boolean,
setReadMarker: Boolean,
lastKnown: Int?,
limit: Int = DEFAULT_MESSAGES_LIMIT
limit: Int = DEFAULT_MESSAGES_LIMIT,
markNotificationAsRead: Boolean = true
): HashMap<String, Int> {
val fieldMap = HashMap<String, Int>()

Expand All @@ -449,6 +471,11 @@ class OfflineFirstChatRepository @Inject constructor(
fieldMap["lookIntoFuture"] = if (lookIntoFuture) 1 else 0
fieldMap["setReadMarker"] = if (setReadMarker) 1 else 0

val spreedCapabilities = currentUser.capabilities?.spreedCapability!!
if (CapabilitiesUtil.hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.CHAT_KEEP_NOTIFICATIONS)) {
fieldMap["markNotificationsAsRead"] = if (markNotificationAsRead) 1 else 0
}

return fieldMap
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,9 @@ class ConversationsListActivity :
}

private fun setConversationList(list: List<ConversationModel>) {
// Refreshes conversation messages in the background asynchronously
conversationsListViewModel.updateRoomMessages(list)

// Update Conversations
conversationItems.clear()
conversationItemsWithHeader.clear()
Expand Down Expand Up @@ -828,7 +831,7 @@ class ConversationsListActivity :
if (!hasFilterEnabled()) filterableConversationItems = searchableConversationItems
adapter!!.updateDataSet(filterableConversationItems, false)
adapter!!.showAllHeaders()
binding.swipeRefreshLayoutView?.isEnabled = false
binding.swipeRefreshLayoutView.isEnabled = false
searchBehaviorSubject.onNext(true)
return true
}
Expand Down Expand Up @@ -2077,7 +2080,8 @@ class ConversationsListActivity :

private fun onMessageSearchError(throwable: Throwable) {
handleHttpExceptions(throwable)
binding.swipeRefreshLayoutView?.isRefreshing = false
binding.swipeRefreshLayoutView.isRefreshing = false
showErrorDialog()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

showErrorDialog is already called in handleHttpExceptions

}

fun updateFilterState(mention: Boolean, unread: Boolean) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,27 @@ import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.nextcloud.talk.chat.data.ChatMessageRepository
import com.nextcloud.talk.conversationlist.data.OfflineConversationsRepository
import com.nextcloud.talk.invitation.data.InvitationsModel
import com.nextcloud.talk.invitation.data.InvitationsRepository
import com.nextcloud.talk.models.domain.ConversationModel
import com.nextcloud.talk.users.UserManager
import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import javax.inject.Inject

class ConversationsListViewModel @Inject constructor(
private val repository: OfflineConversationsRepository,
private val chatRepository: ChatMessageRepository,
var userManager: UserManager
) :
ViewModel() {
Expand Down Expand Up @@ -88,6 +94,20 @@ class ConversationsListViewModel @Inject constructor(
repository.getRooms()
}

fun updateRoomMessages(list: List<ConversationModel>) {
val current = list.associateWith { model ->
val unreadMessages = model.unreadMessages
unreadMessages
}
viewModelScope.launch(Dispatchers.IO) {
for ((model, unreadMessages) in current) {
if (unreadMessages > 0) {
chatRepository.updateRoomMessages(model.internalId, unreadMessages)
}
}
}
}

Copy link
Collaborator

@mahibi mahibi Mar 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be simplified to this?:

fun updateRoomMessages(list: List<ConversationModel>) {
    viewModelScope.launch(Dispatchers.IO) {
        list.filter { it.unreadMessages > 0 }
            .forEach { chatRepository.updateRoomMessages(it.internalId, it.unreadMessages) }
    }
}

inner class FederatedInvitationsObserver : Observer<InvitationsModel> {
override fun onSubscribe(d: Disposable) {
// unused atm
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ enum class SpreedFeatures(val value: String) {
DELETE_MESSAGES_UNLIMITED("delete-messages-unlimited"),
BAN_V1("ban-v1"),
EDIT_MESSAGES_NOTE_TO_SELF("edit-messages-note-to-self"),
ARCHIVE_CONVERSATIONS("archived-conversations-v2")
ARCHIVE_CONVERSATIONS("archived-conversations-v2"),
CHAT_KEEP_NOTIFICATIONS("chat-keep-notifications")
}

@Suppress("TooManyFunctions")
Expand Down
Loading