refactoring and logging

Signed-off-by: Marcel Hibbe <dev@mhibbe.de>
This commit is contained in:
Marcel Hibbe 2024-10-17 11:54:02 +02:00
parent c81b1fa62f
commit 7e3a4e4a83
No known key found for this signature in database
GPG Key ID: C793F8B59F43CE7B
2 changed files with 91 additions and 95 deletions

View File

@ -1250,9 +1250,7 @@ class ChatActivity :
@Suppress("MagicNumber", "LongMethod") @Suppress("MagicNumber", "LongMethod")
private fun updateTypingIndicator() { private fun updateTypingIndicator() {
fun ellipsize(text: String): String { fun ellipsize(text: String): String = DisplayUtils.ellipsize(text, TYPING_INDICATOR_MAX_NAME_LENGTH)
return DisplayUtils.ellipsize(text, TYPING_INDICATOR_MAX_NAME_LENGTH)
}
val participantNames = ArrayList<String>() val participantNames = ArrayList<String>()
@ -1326,10 +1324,9 @@ class ChatActivity :
} }
} }
private fun isTypingStatusEnabled(): Boolean { private fun isTypingStatusEnabled(): Boolean =
return webSocketInstance != null && webSocketInstance != null &&
!CapabilitiesUtil.isTypingStatusPrivate(conversationUser!!) !CapabilitiesUtil.isTypingStatusPrivate(conversationUser!!)
}
private fun setupSwipeToReply() { private fun setupSwipeToReply() {
if (this::participantPermissions.isInitialized && if (this::participantPermissions.isInitialized &&
@ -1428,15 +1425,18 @@ class ChatActivity :
} }
fun isOneToOneConversation() = fun isOneToOneConversation() =
currentConversation != null && currentConversation?.type != null && currentConversation != null &&
currentConversation?.type != null &&
currentConversation?.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL currentConversation?.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL
private fun isGroupConversation() = private fun isGroupConversation() =
currentConversation != null && currentConversation?.type != null && currentConversation != null &&
currentConversation?.type != null &&
currentConversation?.type == ConversationEnums.ConversationType.ROOM_GROUP_CALL currentConversation?.type == ConversationEnums.ConversationType.ROOM_GROUP_CALL
private fun isPublicConversation() = private fun isPublicConversation() =
currentConversation != null && currentConversation?.type != null && currentConversation != null &&
currentConversation?.type != null &&
currentConversation?.type == ConversationEnums.ConversationType.ROOM_PUBLIC_CALL currentConversation?.type == ConversationEnums.ConversationType.ROOM_PUBLIC_CALL
private fun updateRoomTimerHandler() { private fun updateRoomTimerHandler() {
@ -1674,11 +1674,10 @@ class ChatActivity :
adapter?.notifyDataSetChanged() adapter?.notifyDataSetChanged()
} }
private fun isChildOfExpandableSystemMessage(chatMessage: ChatMessage): Boolean { private fun isChildOfExpandableSystemMessage(chatMessage: ChatMessage): Boolean =
return isSystemMessage(chatMessage) && isSystemMessage(chatMessage) &&
!chatMessage.expandableParent && !chatMessage.expandableParent &&
chatMessage.lastItemOfExpandableGroup != 0 chatMessage.lastItemOfExpandableGroup != 0
}
@SuppressLint("NotifyDataSetChanged") @SuppressLint("NotifyDataSetChanged")
override fun expandSystemMessage(chatMessageToExpand: ChatMessage) { override fun expandSystemMessage(chatMessageToExpand: ChatMessage) {
@ -1764,12 +1763,11 @@ class ChatActivity :
} }
} }
fun isRecordAudioPermissionGranted(): Boolean { fun isRecordAudioPermissionGranted(): Boolean =
return PermissionChecker.checkSelfPermission( PermissionChecker.checkSelfPermission(
context, context,
Manifest.permission.RECORD_AUDIO Manifest.permission.RECORD_AUDIO
) == PERMISSION_GRANTED ) == PERMISSION_GRANTED
}
fun requestRecordAudioPermissions() { fun requestRecordAudioPermissions() {
requestPermissions( requestPermissions(
@ -1876,11 +1874,10 @@ class ChatActivity :
} }
} }
private fun isReadOnlyConversation(): Boolean { private fun isReadOnlyConversation(): Boolean =
return currentConversation?.conversationReadOnlyState != null && currentConversation?.conversationReadOnlyState != null &&
currentConversation?.conversationReadOnlyState == currentConversation?.conversationReadOnlyState ==
ConversationEnums.ConversationReadOnlyState.CONVERSATION_READ_ONLY ConversationEnums.ConversationReadOnlyState.CONVERSATION_READ_ONLY
}
private fun checkLobbyState() { private fun checkLobbyState() {
if (currentConversation != null && if (currentConversation != null &&
@ -1896,7 +1893,8 @@ class ChatActivity :
sb.append(resources!!.getText(R.string.nc_lobby_waiting)) sb.append(resources!!.getText(R.string.nc_lobby_waiting))
.append("\n\n") .append("\n\n")
if (currentConversation?.lobbyTimer != null && currentConversation?.lobbyTimer != if (currentConversation?.lobbyTimer != null &&
currentConversation?.lobbyTimer !=
0L 0L
) { ) {
val timestampMS = (currentConversation?.lobbyTimer ?: 0) * DateConstants.SECOND_DIVIDER val timestampMS = (currentConversation?.lobbyTimer ?: 0) * DateConstants.SECOND_DIVIDER
@ -2095,7 +2093,7 @@ class ChatActivity :
if (position != null && position >= 0) { if (position != null && position >= 0) {
binding.messagesListView.scrollToPosition(position) binding.messagesListView.scrollToPosition(position)
} else { } else {
// TODO show error that we don't have that message? Log.d(TAG, "message $messageId that should be scrolled to was not found (scrollToMessageWithId)")
} }
} }
@ -2107,6 +2105,12 @@ class ChatActivity :
position, position,
binding.messagesListView.height / 2 binding.messagesListView.height / 2
) )
} else {
Log.d(
TAG,
"message $messageId that should be scrolled to was not found " +
"(scrollToAndCenterMessageWithId)"
)
} }
} }
} }
@ -2270,11 +2274,10 @@ class ChatActivity :
startActivity(intent) startActivity(intent)
} }
private fun validSessionId(): Boolean { private fun validSessionId(): Boolean =
return currentConversation != null && currentConversation != null &&
sessionIdAfterRoomJoined?.isNotEmpty() == true && sessionIdAfterRoomJoined?.isNotEmpty() == true &&
sessionIdAfterRoomJoined != "0" sessionIdAfterRoomJoined != "0"
}
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught")
private fun cancelNotificationsForCurrentConversation() { private fun cancelNotificationsForCurrentConversation() {
@ -2327,14 +2330,11 @@ class ChatActivity :
} }
} }
private fun isActivityNotChangingConfigurations(): Boolean { private fun isActivityNotChangingConfigurations(): Boolean = !isChangingConfigurations
return !isChangingConfigurations
}
private fun isNotInCall(): Boolean { private fun isNotInCall(): Boolean =
return !ApplicationWideCurrentRoomHolder.getInstance().isInCall && !ApplicationWideCurrentRoomHolder.getInstance().isInCall &&
!ApplicationWideCurrentRoomHolder.getInstance().isDialing !ApplicationWideCurrentRoomHolder.getInstance().isDialing
}
private fun setActionBarTitle() { private fun setActionBarTitle() {
val title = binding.chatToolbar.findViewById<TextView>(R.id.chat_toolbar_title) val title = binding.chatToolbar.findViewById<TextView>(R.id.chat_toolbar_title)
@ -2775,11 +2775,10 @@ class ChatActivity :
} }
} }
private fun isSameDayNonSystemMessages(messageLeft: ChatMessage, messageRight: ChatMessage): Boolean { private fun isSameDayNonSystemMessages(messageLeft: ChatMessage, messageRight: ChatMessage): Boolean =
return TextUtils.isEmpty(messageLeft.systemMessage) && TextUtils.isEmpty(messageLeft.systemMessage) &&
TextUtils.isEmpty(messageRight.systemMessage) && TextUtils.isEmpty(messageRight.systemMessage) &&
DateFormatter.isSameDay(messageLeft.createdAt, messageRight.createdAt) DateFormatter.isSameDay(messageLeft.createdAt, messageRight.createdAt)
}
override fun onLoadMore(page: Int, totalItemsCount: Int) { override fun onLoadMore(page: Int, totalItemsCount: Int) {
val id = ( val id = (
@ -2799,15 +2798,14 @@ class ChatActivity :
) )
} }
override fun format(date: Date): String { override fun format(date: Date): String =
return if (DateFormatter.isToday(date)) { if (DateFormatter.isToday(date)) {
resources!!.getString(R.string.nc_date_header_today) resources!!.getString(R.string.nc_date_header_today)
} else if (DateFormatter.isYesterday(date)) { } else if (DateFormatter.isYesterday(date)) {
resources!!.getString(R.string.nc_date_header_yesterday) resources!!.getString(R.string.nc_date_header_yesterday)
} else { } else {
DateFormatter.format(date, DateFormatter.Template.STRING_DAY_MONTH_YEAR) DateFormatter.format(date, DateFormatter.Template.STRING_DAY_MONTH_YEAR)
} }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean { override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu) super.onCreateOptionsMenu(menu)
@ -2869,8 +2867,8 @@ class ChatActivity :
return true return true
} }
override fun onOptionsItemSelected(item: MenuItem): Boolean { override fun onOptionsItemSelected(item: MenuItem): Boolean =
return when (item.itemId) { when (item.itemId) {
R.id.conversation_video_call -> { R.id.conversation_video_call -> {
startACall(false, false) startACall(false, false)
true true
@ -2898,7 +2896,6 @@ class ChatActivity :
else -> super.onOptionsItemSelected(item) else -> super.onOptionsItemSelected(item)
} }
}
private fun showSharedItems() { private fun showSharedItems() {
val intent = Intent(this, SharedItemsActivity::class.java) val intent = Intent(this, SharedItemsActivity::class.java)
@ -2960,25 +2957,23 @@ class ChatActivity :
return chatMessageMap.values.toList() return chatMessageMap.values.toList()
} }
private fun isInfoMessageAboutDeletion(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean { private fun isInfoMessageAboutDeletion(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean =
return currentMessage.value.parentMessageId != null && currentMessage.value.systemMessageType == ChatMessage currentMessage.value.parentMessageId != null &&
.SystemMessageType.MESSAGE_DELETED currentMessage.value.systemMessageType == ChatMessage
} .SystemMessageType.MESSAGE_DELETED
private fun isReactionsMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean { private fun isReactionsMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean =
return currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION || currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION ||
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_DELETED || currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_DELETED ||
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_REVOKED currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_REVOKED
}
private fun isEditMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean { private fun isEditMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean =
return currentMessage.value.parentMessageId != null && currentMessage.value.systemMessageType == ChatMessage currentMessage.value.parentMessageId != null &&
.SystemMessageType.MESSAGE_EDITED currentMessage.value.systemMessageType == ChatMessage
} .SystemMessageType.MESSAGE_EDITED
private fun isPollVotedMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean { private fun isPollVotedMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean =
return currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.POLL_VOTED currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.POLL_VOTED
}
private fun startACall(isVoiceOnlyCall: Boolean, callWithoutNotification: Boolean) { private fun startACall(isVoiceOnlyCall: Boolean, callWithoutNotification: Boolean) {
currentConversation?.let { currentConversation?.let {
@ -3082,9 +3077,8 @@ class ChatActivity :
} }
} }
private fun isSystemMessage(message: ChatMessage): Boolean { private fun isSystemMessage(message: ChatMessage): Boolean =
return ChatMessage.MessageType.SYSTEM_MESSAGE == message.getCalculateMessageType() ChatMessage.MessageType.SYSTEM_MESSAGE == message.getCalculateMessageType()
}
fun deleteMessage(message: IMessage) { fun deleteMessage(message: IMessage) {
if (!participantPermissions.hasChatPermission()) { if (!participantPermissions.hasChatPermission()) {
@ -3327,20 +3321,26 @@ class ChatActivity :
fileViewerUtils.openFileInFilesApp(link!!, keyID!!) fileViewerUtils.openFileInFilesApp(link!!, keyID!!)
} }
private fun hasVisibleItems(message: ChatMessage): Boolean { private fun hasVisibleItems(message: ChatMessage): Boolean =
return !message.isDeleted || // copy message !message.isDeleted ||
message.replyable || // reply to // copy message
message.replyable && // reply privately message.replyable ||
conversationUser?.userId?.isNotEmpty() == true && conversationUser!!.userId != "?" && // reply to
message.replyable &&
// reply privately
conversationUser?.userId?.isNotEmpty() == true &&
conversationUser!!.userId != "?" &&
message.user.id.startsWith("users/") && message.user.id.startsWith("users/") &&
message.user.id.substring(ACTOR_LENGTH) != currentConversation?.actorId && message.user.id.substring(ACTOR_LENGTH) != currentConversation?.actorId &&
currentConversation?.type != ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL || currentConversation?.type != ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL ||
isShowMessageDeletionButton(message) || // delete isShowMessageDeletionButton(message) ||
ChatMessage.MessageType.REGULAR_TEXT_MESSAGE == message.getCalculateMessageType() || // forward // delete
message.previousMessageId > NO_PREVIOUS_MESSAGE_ID && // mark as unread ChatMessage.MessageType.REGULAR_TEXT_MESSAGE == message.getCalculateMessageType() ||
// forward
message.previousMessageId > NO_PREVIOUS_MESSAGE_ID &&
// mark as unread
ChatMessage.MessageType.SYSTEM_MESSAGE != message.getCalculateMessageType() && ChatMessage.MessageType.SYSTEM_MESSAGE != message.getCalculateMessageType() &&
BuildConfig.DEBUG BuildConfig.DEBUG
}
private fun setMessageAsDeleted(message: IMessage?) { private fun setMessageAsDeleted(message: IMessage?) {
val messageTemp = message as ChatMessage val messageTemp = message as ChatMessage
@ -3458,8 +3458,8 @@ class ChatActivity :
return isUserAllowedByPrivileges return isUserAllowedByPrivileges
} }
override fun hasContentFor(message: ChatMessage, type: Byte): Boolean { override fun hasContentFor(message: ChatMessage, type: Byte): Boolean =
return when (type) { when (type) {
CONTENT_TYPE_LOCATION -> message.hasGeoLocation() CONTENT_TYPE_LOCATION -> message.hasGeoLocation()
CONTENT_TYPE_VOICE_MESSAGE -> message.isVoiceMessage CONTENT_TYPE_VOICE_MESSAGE -> message.isVoiceMessage
CONTENT_TYPE_POLL -> message.isPoll() CONTENT_TYPE_POLL -> message.isPoll()
@ -3470,7 +3470,6 @@ class ChatActivity :
else -> false else -> false
} }
}
private fun processMostRecentMessage(recent: ChatMessage, chatMessageList: List<ChatMessage>) { private fun processMostRecentMessage(recent: ChatMessage, chatMessageList: List<ChatMessage>) {
when (recent.systemMessageType) { when (recent.systemMessageType) {

View File

@ -108,35 +108,36 @@ class OfflineFirstChatRepository @Inject constructor(
override fun loadInitialMessages(withNetworkParams: Bundle): Job = override fun loadInitialMessages(withNetworkParams: Bundle): Job =
scope.launch { scope.launch {
Log.d(TAG, "---- loadInitialMessages ------------") Log.d(TAG, "---- loadInitialMessages ------------")
Log.d(TAG, "conversationModel.internalId: " + conversationModel.internalId)
newXChatLastCommonRead = conversationModel.lastCommonReadMessage newXChatLastCommonRead = conversationModel.lastCommonReadMessage
Log.d(TAG, "conversationModel.internalId: " + conversationModel.internalId)
Log.d(TAG, "conversationModel.lastReadMessage:" + conversationModel.lastReadMessage) Log.d(TAG, "conversationModel.lastReadMessage:" + conversationModel.lastReadMessage)
var newestMessageIdFromDb = chatDao.getNewestMessageId(internalConversationId) var newestMessageIdFromDb = chatDao.getNewestMessageId(internalConversationId)
Log.d(TAG, "newestMessageId: $newestMessageIdFromDb") Log.d(TAG, "newestMessageIdFromDb: $newestMessageIdFromDb")
if (newestMessageIdFromDb.toInt() == 0) {
Log.d(TAG, "newestMessageId from db was 0. Must only happen when chat is loaded for the first time")
}
// infos from Ivan to val weAlreadyHaveSomeOfflineMessages = newestMessageIdFromDb > 0
// "Why is it lastReadMessageId that is checked? Shouldn't it be lastMessage instead? val weHaveAtLeastTheLastReadMessage = newestMessageIdFromDb >= conversationModel.lastReadMessage.toLong()
// https://github.com/nextcloud/talk-ios/blob/master/NextcloudTalk/NCChatController.m#L473 " Log.d(TAG, "weAlreadyHaveSomeOfflineMessages:$weAlreadyHaveSomeOfflineMessages")
// Log.d(TAG, "weHaveAtLeastTheLastReadMessage:$weHaveAtLeastTheLastReadMessage")
// answer:
// "I guess we do it with the lastReadMessageId in order to place the separator of "Unread messages" when you enter the chat"
//
// if it turns out lastMessage can be used instead lastReadMessage, use this:
// val doInitialLoadFromServer = conversationModel.lastMessage?.let {
// newestMessageIdFromDb < it.id
// } ?: true
// Log.d(TAG, "doInitialLoadFromServer:$doInitialLoadFromServer")
//
// if (doInitialLoadFromServer) {
if (newestMessageIdFromDb < conversationModel.lastReadMessage.toLong()) { if (weAlreadyHaveSomeOfflineMessages && weHaveAtLeastTheLastReadMessage) {
Log.d(TAG, "An online request is made because chat is not up to date") Log.d(
TAG,
"Initial online request is skipped because offline messages are up to date" +
" until lastReadMessage"
)
Log.d(TAG, "For messages newer than lastRead, lookIntoFuture will load them.")
} else {
if (!weAlreadyHaveSomeOfflineMessages) {
Log.d(TAG, "An online request for newest 100 messages is made because offline chat is empty")
} else {
Log.d(
TAG,
"An online request for newest 100 messages is made because we don't have the lastReadMessage " +
"(gaps could be closed by scrolling up to merge the chatblocks)"
)
}
// set up field map to load the newest messages // set up field map to load the newest messages
val fieldMap = getFieldMap( val fieldMap = getFieldMap(
@ -155,11 +156,7 @@ class OfflineFirstChatRepository @Inject constructor(
} }
newestMessageIdFromDb = chatDao.getNewestMessageId(internalConversationId) newestMessageIdFromDb = chatDao.getNewestMessageId(internalConversationId)
Log.d(TAG, "newestMessageId after sync: $newestMessageIdFromDb") Log.d(TAG, "newestMessageIdFromDb after sync: $newestMessageIdFromDb")
} else {
Log.d(TAG, "Initial online request is skipped because offline messages are up to date")
// if conversationModel was not up to date and there are new messages, they will just get pulled with
// look into future.. Old messages will be displayed immediately beforehand.
} }
val limit = getCappedMessagesAmountOfChatBlock(newestMessageIdFromDb) val limit = getCappedMessagesAmountOfChatBlock(newestMessageIdFromDb)
@ -367,7 +364,7 @@ class OfflineFirstChatRepository @Inject constructor(
.map(ChatMessageEntity::asModel) .map(ChatMessageEntity::asModel)
} }
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST", "MagicNumber")
private fun getMessagesFromServer(bundle: Bundle): Pair<Int, List<ChatMessageJson>>? { private fun getMessagesFromServer(bundle: Bundle): Pair<Int, List<ChatMessageJson>>? {
val fieldMap = bundle.getSerializable(BundleKeys.KEY_FIELD_MAP) as HashMap<String, Int> val fieldMap = bundle.getSerializable(BundleKeys.KEY_FIELD_MAP) as HashMap<String, Int>