Commit 6b157720 authored by Leonardo Aramaki's avatar Leonardo Aramaki

Sort saved local messages according to their timestamps

parent 903ca99c
...@@ -73,21 +73,14 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView, ...@@ -73,21 +73,14 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView,
launchUI(strategy) { launchUI(strategy) {
view.showLoading() view.showLoading()
try { try {
val oldMessages = messagesRepository.getByRoomId(chatRoomId).sortedWith(compareBy(Message::timestamp)).reversed() val oldMessages = messagesRepository.getByRoomId(chatRoomId)
view.showMessages(mapper.map(oldMessages)) view.showMessages(mapper.map(oldMessages))
val messages = val messages =
retryIO(description = "messages chatRoom: $chatRoomId, type: $chatRoomType, offset: $offset") { retryIO(description = "messages chatRoom: $chatRoomId, type: $chatRoomType, offset: $offset") {
client.messages(chatRoomId, roomTypeOf(chatRoomType), offset, 30).result client.messages(chatRoomId, roomTypeOf(chatRoomType), offset, 30).result
} }
messagesRepository.saveAll(messages) messagesRepository.saveAll(messages)
val messagesViewModels = mapper.map(messages)
val unsentMessages = messagesRepository.getUnsentByRoomId(chatRoomId)
var mergedMessages = messages.toMutableList()
mergedMessages.addAll(unsentMessages)
val allMessages = mergedMessages.toList().filterNot { message ->
unsentMessages.find { it.id == message.id } != null
}
val messagesViewModels = mapper.map(allMessages)
view.showMessages(messagesViewModels) view.showMessages(messagesViewModels)
// TODO: For now we are marking the room as read if we can get the messages (I mean, no exception occurs) // TODO: For now we are marking the room as read if we can get the messages (I mean, no exception occurs)
...@@ -120,26 +113,26 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView, ...@@ -120,26 +113,26 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView,
val message = if (messageId == null) { val message = if (messageId == null) {
val username = localRepository.username() val username = localRepository.username()
val newMessage = Message( val newMessage = Message(
id = id, id = id,
roomId = chatRoomId, roomId = chatRoomId,
message = text, message = text,
timestamp = Instant.now().toEpochMilli(), timestamp = Instant.now().toEpochMilli(),
sender = SimpleUser(null, username, username), sender = SimpleUser(null, username, username),
attachments = null, attachments = null,
avatar = currentServer.avatarUrl(username!!), avatar = currentServer.avatarUrl(username!!),
channels = null, channels = null,
editedAt = null, editedAt = null,
editedBy = null, editedBy = null,
groupable = false, groupable = false,
parseUrls = false, parseUrls = false,
pinned = false, pinned = false,
mentions = emptyList(), mentions = emptyList(),
reactions = null, reactions = null,
senderAlias = null, senderAlias = null,
type = null, type = null,
updatedAt = null, updatedAt = null,
urls = null, urls = null,
isTemporary = true isTemporary = true
) )
messagesRepository.save(newMessage) messagesRepository.save(newMessage)
view.showNewMessage(mapper.map(newMessage)) view.showNewMessage(mapper.map(newMessage))
...@@ -244,35 +237,35 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView, ...@@ -244,35 +237,35 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView,
if (chatRoomId != null && chatRoomType != null) { if (chatRoomId != null && chatRoomType != null) {
val roomType = roomTypeOf(chatRoomType!!) val roomType = roomTypeOf(chatRoomType!!)
messagesRepository.getByRoomId(chatRoomId!!) messagesRepository.getByRoomId(chatRoomId!!)
.sortedByDescending { it.timestamp }.firstOrNull()?.let { lastMessage -> .sortedByDescending { it.timestamp }.firstOrNull()?.let { lastMessage ->
val instant = Instant.ofEpochMilli(lastMessage.timestamp).toString() val instant = Instant.ofEpochMilli(lastMessage.timestamp).toString()
try { try {
val messages = retryIO(description = "history($chatRoomId, $roomType, $instant)") { val messages = retryIO(description = "history($chatRoomId, $roomType, $instant)") {
client.history(chatRoomId!!, roomType, count = 50, client.history(chatRoomId!!, roomType, count = 50,
oldest = instant) oldest = instant)
} }
Timber.d("History: $messages") Timber.d("History: $messages")
if (messages.result.isNotEmpty()) { if (messages.result.isNotEmpty()) {
val models = mapper.map(messages.result) val models = mapper.map(messages.result)
messagesRepository.saveAll(messages.result) messagesRepository.saveAll(messages.result)
launchUI(strategy) { launchUI(strategy) {
view.showNewMessage(models) view.showNewMessage(models)
} }
if (messages.result.size == 50) { if (messages.result.size == 50) {
// we loaded at least count messages, try one more to fetch more messages // we loaded at least count messages, try one more to fetch more messages
loadMissingMessages() loadMissingMessages()
}
} }
} catch (ex: Exception) {
// TODO - we need to better treat connection problems here, but no let gaps
// on the messages list
Timber.d(ex, "Error fetching channel history")
ex.printStackTrace()
} }
} catch (ex: Exception) {
// TODO - we need to better treat connection problems here, but no let gaps
// on the messages list
Timber.d(ex, "Error fetching channel history")
ex.printStackTrace()
} }
}
} }
} }
} }
...@@ -335,7 +328,7 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView, ...@@ -335,7 +328,7 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView,
val id = m.id val id = m.id
val username = m.sender?.username val username = m.sender?.username
val user = "@" + if (settings.useRealName()) m.sender?.name val user = "@" + if (settings.useRealName()) m.sender?.name
?: m.sender?.username else m.sender?.username ?: m.sender?.username else m.sender?.username
val mention = if (mentionAuthor && me?.username != username) user else "" val mention = if (mentionAuthor && me?.username != username) user else ""
val type = roomTypeOf(roomType) val type = roomTypeOf(roomType)
val room = when (type) { val room = when (type) {
...@@ -346,9 +339,9 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView, ...@@ -346,9 +339,9 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView,
is RoomType.Custom -> "custom" //TODO: put appropriate callback string here. is RoomType.Custom -> "custom" //TODO: put appropriate callback string here.
} }
view.showReplyingAction( view.showReplyingAction(
username = user, username = user,
replyMarkdown = "[ ]($currentServer/$room/$roomName?msg=$id) $mention ", replyMarkdown = "[ ]($currentServer/$room/$roomName?msg=$id) $mention ",
quotedMessage = mapper.map(message).last().preview?.message ?: "" quotedMessage = mapper.map(message).last().preview?.message ?: ""
) )
} }
} }
...@@ -426,7 +419,7 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView, ...@@ -426,7 +419,7 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView,
val self = localRepository.get(LocalRepository.CURRENT_USERNAME_KEY) val self = localRepository.get(LocalRepository.CURRENT_USERNAME_KEY)
// Take at most the 100 most recent messages distinguished by user. Can return less. // Take at most the 100 most recent messages distinguished by user. Can return less.
val recentMessages = messagesRepository.getRecentMessages(chatRoomId, 100) val recentMessages = messagesRepository.getRecentMessages(chatRoomId, 100)
.filterNot { filterSelfOut && it.sender?.username == self } .filterNot { filterSelfOut && it.sender?.username == self }
val activeUsers = mutableListOf<PeopleSuggestionViewModel>() val activeUsers = mutableListOf<PeopleSuggestionViewModel>()
recentMessages.forEach { recentMessages.forEach {
val sender = it.sender!! val sender = it.sender!!
...@@ -437,7 +430,7 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView, ...@@ -437,7 +430,7 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView,
val status = if (found != null) found.status else UserStatus.Offline() val status = if (found != null) found.status else UserStatus.Offline()
val searchList = mutableListOf(username, name) val searchList = mutableListOf(username, name)
activeUsers.add(PeopleSuggestionViewModel(avatarUrl, username, username, name, status, activeUsers.add(PeopleSuggestionViewModel(avatarUrl, username, username, name, status,
true, searchList)) true, searchList))
} }
// Filter out from members list the active users. // Filter out from members list the active users.
val others = members.filterNot { member -> val others = members.filterNot { member ->
...@@ -477,7 +470,7 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView, ...@@ -477,7 +470,7 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView,
val searchList = mutableListOf(username, name) val searchList = mutableListOf(username, name)
it.emails?.forEach { email -> searchList.add(email.address) } it.emails?.forEach { email -> searchList.add(email.address) }
PeopleSuggestionViewModel(currentServer.avatarUrl(username), PeopleSuggestionViewModel(currentServer.avatarUrl(username),
username, username, name, it.status, false, searchList) username, username, name, it.status, false, searchList)
}.filterNot { filterSelfOut && self != null && self == it.text }) }.filterNot { filterSelfOut && self != null && self == it.text })
} }
ROOMS -> { ROOMS -> {
...@@ -504,19 +497,19 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView, ...@@ -504,19 +497,19 @@ class ChatRoomPresenter @Inject constructor(private val view: ChatRoomView,
launchUI(strategy) { launchUI(strategy) {
try { try {
val chatRooms = getChatRoomsInteractor.get(currentServer) val chatRooms = getChatRoomsInteractor.get(currentServer)
.filterNot { .filterNot {
it.type is RoomType.DirectMessage || it.type is RoomType.Livechat it.type is RoomType.DirectMessage || it.type is RoomType.Livechat
} }
.map { chatRoom -> .map { chatRoom ->
val name = chatRoom.name val name = chatRoom.name
val fullName = chatRoom.fullName ?: "" val fullName = chatRoom.fullName ?: ""
ChatRoomSuggestionViewModel( ChatRoomSuggestionViewModel(
text = name, text = name,
name = name, name = name,
fullName = fullName, fullName = fullName,
searchList = listOf(name, fullName) searchList = listOf(name, fullName)
) )
} }
view.populateRoomSuggestions(chatRooms) view.populateRoomSuggestions(chatRooms)
} catch (e: RocketChatException) { } catch (e: RocketChatException) {
Timber.e(e) Timber.e(e)
......
...@@ -29,7 +29,7 @@ class SharedPreferencesMessagesRepository( ...@@ -29,7 +29,7 @@ class SharedPreferencesMessagesRepository(
val values = prefs.all.values as Collection<String> val values = prefs.all.values as Collection<String>
return@withContext values.mapNotNull { adapter.fromJson(it) }.filter { return@withContext values.mapNotNull { adapter.fromJson(it) }.filter {
it.roomId == rid it.roomId == rid
}.toList() }.toList().sortedWith(compareBy(Message::timestamp)).reversed()
} }
override suspend fun getRecentMessages(rid: String, count: Long): List<Message> { override suspend fun getRecentMessages(rid: String, count: Long): List<Message> {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment