Commit 1df80b20 authored by Leonardo Aramaki's avatar Leonardo Aramaki

Refactor app to use db to search for ChatRooms instead of the SharedPreferences

parent bf082dd4
{
"formatVersion": 1,
"database": {
"version": 4,
"identityHash": "e389d26bfb975f00c75dc6fc5d06d012",
"entities": [
{
"tableName": "users",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `username` TEXT, `name` TEXT, `status` TEXT NOT NULL, `utcOffset` REAL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "utcOffset",
"columnName": "utcOffset",
"affinity": "REAL",
"notNull": false
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": false
},
"indices": [
{
"name": "index_users_username",
"unique": false,
"columnNames": [
"username"
],
"createSql": "CREATE INDEX `index_users_username` ON `${TABLE_NAME}` (`username`)"
}
],
"foreignKeys": []
},
{
"tableName": "chatrooms",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `subscriptionId` TEXT NOT NULL, `type` TEXT NOT NULL, `name` TEXT NOT NULL, `fullname` TEXT, `userId` TEXT, `ownerId` TEXT, `readonly` INTEGER, `isDefault` INTEGER, `favorite` INTEGER, `open` INTEGER NOT NULL, `alert` INTEGER NOT NULL, `unread` INTEGER NOT NULL, `userMentions` INTEGER, `groupMentions` INTEGER, `updatedAt` INTEGER, `timestamp` INTEGER, `lastSeen` INTEGER, `lastMessageText` TEXT, `lastMessageUserId` TEXT, `lastMessageTimestamp` INTEGER, `broadcast` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`ownerId`) REFERENCES `users`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`userId`) REFERENCES `users`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`lastMessageUserId`) REFERENCES `users`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "subscriptionId",
"columnName": "subscriptionId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "type",
"columnName": "type",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "fullname",
"columnName": "fullname",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "userId",
"columnName": "userId",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "ownerId",
"columnName": "ownerId",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "readonly",
"columnName": "readonly",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "isDefault",
"columnName": "isDefault",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "favorite",
"columnName": "favorite",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "open",
"columnName": "open",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "alert",
"columnName": "alert",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unread",
"columnName": "unread",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "userMentions",
"columnName": "userMentions",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "groupMentions",
"columnName": "groupMentions",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "updatedAt",
"columnName": "updatedAt",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "lastSeen",
"columnName": "lastSeen",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "lastMessageText",
"columnName": "lastMessageText",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "lastMessageUserId",
"columnName": "lastMessageUserId",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "lastMessageTimestamp",
"columnName": "lastMessageTimestamp",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "broadcast",
"columnName": "broadcast",
"affinity": "INTEGER",
"notNull": false
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": false
},
"indices": [
{
"name": "index_chatrooms_userId",
"unique": false,
"columnNames": [
"userId"
],
"createSql": "CREATE INDEX `index_chatrooms_userId` ON `${TABLE_NAME}` (`userId`)"
},
{
"name": "index_chatrooms_ownerId",
"unique": false,
"columnNames": [
"ownerId"
],
"createSql": "CREATE INDEX `index_chatrooms_ownerId` ON `${TABLE_NAME}` (`ownerId`)"
},
{
"name": "index_chatrooms_subscriptionId",
"unique": true,
"columnNames": [
"subscriptionId"
],
"createSql": "CREATE UNIQUE INDEX `index_chatrooms_subscriptionId` ON `${TABLE_NAME}` (`subscriptionId`)"
},
{
"name": "index_chatrooms_updatedAt",
"unique": false,
"columnNames": [
"updatedAt"
],
"createSql": "CREATE INDEX `index_chatrooms_updatedAt` ON `${TABLE_NAME}` (`updatedAt`)"
}
],
"foreignKeys": [
{
"table": "users",
"onDelete": "NO ACTION",
"onUpdate": "NO ACTION",
"columns": [
"ownerId"
],
"referencedColumns": [
"id"
]
},
{
"table": "users",
"onDelete": "NO ACTION",
"onUpdate": "NO ACTION",
"columns": [
"userId"
],
"referencedColumns": [
"id"
]
},
{
"table": "users",
"onDelete": "NO ACTION",
"onUpdate": "NO ACTION",
"columns": [
"lastMessageUserId"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"e389d26bfb975f00c75dc6fc5d06d012\")"
]
}
}
\ No newline at end of file
...@@ -33,4 +33,4 @@ class ChatRoomFragmentModule { ...@@ -33,4 +33,4 @@ class ChatRoomFragmentModule {
fun provideCancelStrategy(owner: LifecycleOwner, jobs: Job): CancelStrategy { fun provideCancelStrategy(owner: LifecycleOwner, jobs: Job): CancelStrategy {
return CancelStrategy(owner, jobs) return CancelStrategy(owner, jobs)
} }
} }
\ No newline at end of file
package chat.rocket.android.chatroom.domain package chat.rocket.android.chatroom.domain
data class MessageReply( data class MessageReply(val roomName: String, val permalink: String)
val roomName: String, \ No newline at end of file
val permalink: String
)
\ No newline at end of file
...@@ -13,10 +13,10 @@ import chat.rocket.android.chatroom.uimodel.suggestion.CommandSuggestionUiModel ...@@ -13,10 +13,10 @@ import chat.rocket.android.chatroom.uimodel.suggestion.CommandSuggestionUiModel
import chat.rocket.android.chatroom.uimodel.suggestion.PeopleSuggestionUiModel import chat.rocket.android.chatroom.uimodel.suggestion.PeopleSuggestionUiModel
import chat.rocket.android.core.behaviours.showMessage import chat.rocket.android.core.behaviours.showMessage
import chat.rocket.android.core.lifecycle.CancelStrategy import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.helper.MessageHelper import chat.rocket.android.helper.MessageHelper
import chat.rocket.android.helper.UserHelper import chat.rocket.android.helper.UserHelper
import chat.rocket.android.infrastructure.LocalRepository import chat.rocket.android.infrastructure.LocalRepository
import chat.rocket.android.server.domain.ChatRoomsInteractor
import chat.rocket.android.server.domain.GetCurrentServerInteractor import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.domain.GetSettingsInteractor import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.JobSchedulerInteractor import chat.rocket.android.server.domain.JobSchedulerInteractor
...@@ -31,8 +31,8 @@ import chat.rocket.android.server.domain.useRealName ...@@ -31,8 +31,8 @@ import chat.rocket.android.server.domain.useRealName
import chat.rocket.android.server.infraestructure.ConnectionManagerFactory import chat.rocket.android.server.infraestructure.ConnectionManagerFactory
import chat.rocket.android.server.infraestructure.state import chat.rocket.android.server.infraestructure.state
import chat.rocket.android.util.extension.compressImageAndGetInputStream import chat.rocket.android.util.extension.compressImageAndGetInputStream
import chat.rocket.android.util.extensions.avatarUrl
import chat.rocket.android.util.extension.launchUI import chat.rocket.android.util.extension.launchUI
import chat.rocket.android.util.extensions.avatarUrl
import chat.rocket.android.util.retryIO import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatException import chat.rocket.common.RocketChatException
import chat.rocket.common.model.RoomType import chat.rocket.common.model.RoomType
...@@ -47,6 +47,7 @@ import chat.rocket.core.internal.realtime.unsubscribe ...@@ -47,6 +47,7 @@ import chat.rocket.core.internal.realtime.unsubscribe
import chat.rocket.core.internal.rest.chatRoomRoles import chat.rocket.core.internal.rest.chatRoomRoles
import chat.rocket.core.internal.rest.commands import chat.rocket.core.internal.rest.commands
import chat.rocket.core.internal.rest.deleteMessage import chat.rocket.core.internal.rest.deleteMessage
import chat.rocket.core.internal.rest.favorite
import chat.rocket.core.internal.rest.getMembers import chat.rocket.core.internal.rest.getMembers
import chat.rocket.core.internal.rest.history import chat.rocket.core.internal.rest.history
import chat.rocket.core.internal.rest.joinChat import chat.rocket.core.internal.rest.joinChat
...@@ -54,6 +55,7 @@ import chat.rocket.core.internal.rest.markAsRead ...@@ -54,6 +55,7 @@ import chat.rocket.core.internal.rest.markAsRead
import chat.rocket.core.internal.rest.messages import chat.rocket.core.internal.rest.messages
import chat.rocket.core.internal.rest.pinMessage import chat.rocket.core.internal.rest.pinMessage
import chat.rocket.core.internal.rest.runCommand import chat.rocket.core.internal.rest.runCommand
import chat.rocket.core.internal.rest.searchMessages
import chat.rocket.core.internal.rest.sendMessage import chat.rocket.core.internal.rest.sendMessage
import chat.rocket.core.internal.rest.spotlight import chat.rocket.core.internal.rest.spotlight
import chat.rocket.core.internal.rest.starMessage import chat.rocket.core.internal.rest.starMessage
...@@ -62,8 +64,7 @@ import chat.rocket.core.internal.rest.unpinMessage ...@@ -62,8 +64,7 @@ import chat.rocket.core.internal.rest.unpinMessage
import chat.rocket.core.internal.rest.unstarMessage import chat.rocket.core.internal.rest.unstarMessage
import chat.rocket.core.internal.rest.updateMessage import chat.rocket.core.internal.rest.updateMessage
import chat.rocket.core.internal.rest.uploadFile import chat.rocket.core.internal.rest.uploadFile
import chat.rocket.core.internal.rest.favorite import chat.rocket.core.model.ChatRoom
import chat.rocket.core.internal.rest.searchMessages
import chat.rocket.core.model.ChatRoomRole import chat.rocket.core.model.ChatRoomRole
import chat.rocket.core.model.Command import chat.rocket.core.model.Command
import chat.rocket.core.model.Message import chat.rocket.core.model.Message
...@@ -83,7 +84,6 @@ class ChatRoomPresenter @Inject constructor( ...@@ -83,7 +84,6 @@ class ChatRoomPresenter @Inject constructor(
private val view: ChatRoomView, private val view: ChatRoomView,
private val navigator: ChatRoomNavigator, private val navigator: ChatRoomNavigator,
private val strategy: CancelStrategy, private val strategy: CancelStrategy,
private val chatRoomsInteractor: ChatRoomsInteractor,
private val permissions: PermissionsInteractor, private val permissions: PermissionsInteractor,
private val uriInteractor: UriInteractor, private val uriInteractor: UriInteractor,
private val messagesRepository: MessagesRepository, private val messagesRepository: MessagesRepository,
...@@ -94,6 +94,7 @@ class ChatRoomPresenter @Inject constructor( ...@@ -94,6 +94,7 @@ class ChatRoomPresenter @Inject constructor(
private val mapper: UiModelMapper, private val mapper: UiModelMapper,
private val jobSchedulerInteractor: JobSchedulerInteractor, private val jobSchedulerInteractor: JobSchedulerInteractor,
private val messageHelper: MessageHelper, private val messageHelper: MessageHelper,
private val dbManager: DatabaseManager,
getSettingsInteractor: GetSettingsInteractor, getSettingsInteractor: GetSettingsInteractor,
serverInteractor: GetCurrentServerInteractor, serverInteractor: GetCurrentServerInteractor,
factory: ConnectionManagerFactory factory: ConnectionManagerFactory
...@@ -133,7 +134,7 @@ class ChatRoomPresenter @Inject constructor( ...@@ -133,7 +134,7 @@ class ChatRoomPresenter @Inject constructor(
val userCanMod = isOwnerOrMod() val userCanMod = isOwnerOrMod()
// Can post anyway if has the 'post-readonly' permission on server. // Can post anyway if has the 'post-readonly' permission on server.
val userCanPost = userCanMod || permissions.canPostToReadOnlyChannels() val userCanPost = userCanMod || permissions.canPostToReadOnlyChannels()
chatIsBroadcast = chatRoomsInteractor.getById(currentServer, roomId)?.run { chatIsBroadcast = dbManager.getRoom(roomId)?.chatRoom?.run {
broadcast broadcast
} ?: false } ?: false
view.onRoomUpdated(userCanPost, chatIsBroadcast, userCanMod) view.onRoomUpdated(userCanPost, chatIsBroadcast, userCanMod)
...@@ -174,6 +175,7 @@ class ChatRoomPresenter @Inject constructor( ...@@ -174,6 +175,7 @@ class ChatRoomPresenter @Inject constructor(
val oldMessages = mapper.map( val oldMessages = mapper.map(
localMessages, RoomUiModel( localMessages, RoomUiModel(
roles = chatRoles, roles = chatRoles,
// FIXME: Why are we fixing isRoom attribute to true here?
isBroadcast = chatIsBroadcast, isRoom = true isBroadcast = chatIsBroadcast, isRoom = true
) )
) )
...@@ -501,6 +503,7 @@ class ChatRoomPresenter @Inject constructor( ...@@ -501,6 +503,7 @@ class ChatRoomPresenter @Inject constructor(
val models = mapper.map(messages.result, RoomUiModel( val models = mapper.map(messages.result, RoomUiModel(
roles = chatRoles, roles = chatRoles,
isBroadcast = chatIsBroadcast, isBroadcast = chatIsBroadcast,
// FIXME: Why are we fixing isRoom attribute to true here?
isRoom = true isRoom = true
)) ))
messagesRepository.saveAll(messages.result) messagesRepository.saveAll(messages.result)
...@@ -823,7 +826,7 @@ class ChatRoomPresenter @Inject constructor( ...@@ -823,7 +826,7 @@ class ChatRoomPresenter @Inject constructor(
fun loadChatRooms() { fun loadChatRooms() {
launchUI(strategy) { launchUI(strategy) {
try { try {
val chatRooms = chatRoomsInteractor.getAll(currentServer) val chatRooms = getChatRoomsAsync()
.filterNot { .filterNot {
it.type is RoomType.DirectMessage || it.type is RoomType.LiveChat it.type is RoomType.DirectMessage || it.type is RoomType.LiveChat
} }
...@@ -844,6 +847,47 @@ class ChatRoomPresenter @Inject constructor( ...@@ -844,6 +847,47 @@ class ChatRoomPresenter @Inject constructor(
} }
} }
// TODO: move this to new interactor or FetchChatRoomsInteractor?
private suspend fun getChatRoomsAsync(name: String? = null): List<ChatRoom> = withContext(CommonPool) {
return@withContext dbManager.chatRoomDao().getAllSync().filter {
if (name == null) {
return@filter true
}
it.chatRoom.name == name || it.chatRoom.fullname == name
}.map {
with (it.chatRoom) {
ChatRoom(
id = id,
subscriptionId = subscriptionId,
type = roomTypeOf(type),
unread = unread,
broadcast = broadcast ?: false,
alert = alert,
fullName = fullname,
name = name ?: "",
favorite = favorite ?: false,
default = isDefault ?: false,
readonly = readonly,
open = open,
lastMessage = null,
archived = false,
status = null,
user = null,
userMentions = userMentions,
client = client,
announcement = null,
description = null,
groupMentions = groupMentions,
roles = null,
topic = null,
lastSeen = this.lastSeen,
timestamp = timestamp,
updatedAt = updatedAt
)
}
}
}
fun joinChat(chatRoomId: String) { fun joinChat(chatRoomId: String) {
launchUI(strategy) { launchUI(strategy) {
try { try {
...@@ -859,21 +903,23 @@ class ChatRoomPresenter @Inject constructor( ...@@ -859,21 +903,23 @@ class ChatRoomPresenter @Inject constructor(
fun openDirectMessage(roomName: String, message: String) { fun openDirectMessage(roomName: String, message: String) {
launchUI(strategy) { launchUI(strategy) {
try { try {
chatRoomsInteractor.getByName(currentServer, roomName)?.let { getChatRoomsAsync(roomName).let {
if (it.type is RoomType.DirectMessage) { if (it.isNotEmpty()) {
navigator.toDirectMessage( if (it.first().type is RoomType.DirectMessage) {
chatRoomId = it.id, navigator.toDirectMessage(
chatRoomType = it.type.toString(), chatRoomId = it.first().id,
chatRoomLastSeen = it.lastSeen ?: -1, chatRoomType = it.first().type.toString(),
chatRoomName = roomName, chatRoomLastSeen = it.first().lastSeen ?: -1,
isChatRoomCreator = false, chatRoomName = roomName,
isChatRoomFavorite = false, isChatRoomCreator = false,
isChatRoomReadOnly = false, isChatRoomFavorite = false,
isChatRoomSubscribed = it.open, isChatRoomReadOnly = false,
chatRoomMessage = message isChatRoomSubscribed = it.first().open,
) chatRoomMessage = message
} else { )
throw IllegalStateException("Not a direct-message") } else {
throw IllegalStateException("Not a direct-message")
}
} }
} }
} catch (ex: Exception) { } catch (ex: Exception) {
...@@ -1010,7 +1056,7 @@ class ChatRoomPresenter @Inject constructor( ...@@ -1010,7 +1056,7 @@ class ChatRoomPresenter @Inject constructor(
launchUI(strategy) { launchUI(strategy) {
val viewModelStreamedMessage = mapper.map( val viewModelStreamedMessage = mapper.map(
streamedMessage, RoomUiModel( streamedMessage, RoomUiModel(
roles = chatRoles, isBroadcast = chatIsBroadcast roles = chatRoles, isBroadcast = chatIsBroadcast, isRoom = true
) )
) )
......
...@@ -4,35 +4,35 @@ import DateTimeHelper ...@@ -4,35 +4,35 @@ import DateTimeHelper
import android.content.Context import android.content.Context
import android.graphics.Color import android.graphics.Color
import android.graphics.Typeface import android.graphics.Typeface
import androidx.core.content.ContextCompat
import android.text.SpannableStringBuilder import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan import android.text.style.StyleSpan
import androidx.core.content.ContextCompat
import androidx.core.text.bold import androidx.core.text.bold
import androidx.core.text.buildSpannedString import androidx.core.text.buildSpannedString
import androidx.core.text.color import androidx.core.text.color
import androidx.core.text.scale import androidx.core.text.scale
import chat.rocket.android.R import chat.rocket.android.R
import chat.rocket.android.app.RocketChatApplication.Companion.context
import chat.rocket.android.chatinformation.viewmodel.ReadReceiptViewModel import chat.rocket.android.chatinformation.viewmodel.ReadReceiptViewModel
import chat.rocket.android.chatroom.domain.MessageReply import chat.rocket.android.chatroom.domain.MessageReply
import chat.rocket.android.dagger.scope.PerFragment import chat.rocket.android.dagger.scope.PerFragment
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.emoji.EmojiParser
import chat.rocket.android.helper.MessageHelper import chat.rocket.android.helper.MessageHelper
import chat.rocket.android.helper.MessageParser import chat.rocket.android.helper.MessageParser
import chat.rocket.android.helper.UserHelper import chat.rocket.android.helper.UserHelper
import chat.rocket.android.infrastructure.LocalRepository import chat.rocket.android.infrastructure.LocalRepository
import chat.rocket.android.server.domain.ChatRoomsInteractor
import chat.rocket.android.server.domain.GetCurrentServerInteractor import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.domain.GetSettingsInteractor import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.TokenRepository import chat.rocket.android.server.domain.TokenRepository
import chat.rocket.android.server.domain.UsersRepository
import chat.rocket.android.server.domain.baseUrl import chat.rocket.android.server.domain.baseUrl
import chat.rocket.android.server.domain.messageReadReceiptEnabled import chat.rocket.android.server.domain.messageReadReceiptEnabled
import chat.rocket.android.server.domain.messageReadReceiptStoreUsers import chat.rocket.android.server.domain.messageReadReceiptStoreUsers
import chat.rocket.android.server.domain.useRealName import chat.rocket.android.server.domain.useRealName
import chat.rocket.android.server.infraestructure.ConnectionManagerFactory
import chat.rocket.android.util.extensions.avatarUrl import chat.rocket.android.util.extensions.avatarUrl
import chat.rocket.android.util.extensions.isNotNullNorEmpty import chat.rocket.android.util.extensions.isNotNullNorEmpty
import chat.rocket.android.emoji.EmojiParser import chat.rocket.common.model.roomTypeOf
import chat.rocket.core.model.ChatRoom import chat.rocket.core.model.ChatRoom
import chat.rocket.core.model.Message import chat.rocket.core.model.Message
import chat.rocket.core.model.MessageType import chat.rocket.core.model.MessageType
...@@ -60,17 +60,19 @@ import javax.inject.Inject ...@@ -60,17 +60,19 @@ import javax.inject.Inject
class UiModelMapper @Inject constructor( class UiModelMapper @Inject constructor(
private val context: Context, private val context: Context,
private val parser: MessageParser, private val parser: MessageParser,
private val roomsInteractor: ChatRoomsInteractor, private val dbManager: DatabaseManager,
private val usersRepository: UsersRepository,
private val messageHelper: MessageHelper, private val messageHelper: MessageHelper,
private val userHelper: UserHelper, private val userHelper: UserHelper,
tokenRepository: TokenRepository, tokenRepository: TokenRepository,
serverInteractor: GetCurrentServerInteractor, serverInteractor: GetCurrentServerInteractor,
getSettingsInteractor: GetSettingsInteractor, getSettingsInteractor: GetSettingsInteractor,
localRepository: LocalRepository localRepository: LocalRepository,
factory: ConnectionManagerFactory
) { ) {
private val currentServer = serverInteractor.get()!! private val currentServer = serverInteractor.get()!!
private val manager = factory.create(currentServer)
private val client = manager.client
private val settings = getSettingsInteractor.get(currentServer) private val settings = getSettingsInteractor.get(currentServer)
private val baseUrl = currentServer private val baseUrl = currentServer
private val token = tokenRepository.get(currentServer) private val token = tokenRepository.get(currentServer)
...@@ -149,7 +151,7 @@ class UiModelMapper @Inject constructor( ...@@ -149,7 +151,7 @@ class UiModelMapper @Inject constructor(
} }
if (isBroadcastReplyAvailable(roomUiModel, message)) { if (isBroadcastReplyAvailable(roomUiModel, message)) {
roomsInteractor.getById(currentServer, message.roomId)?.let { chatRoom -> getChatRoomAsync(message.roomId)?.let { chatRoom ->
val replyUiModel = mapMessageReply(message, chatRoom) val replyUiModel = mapMessageReply(message, chatRoom)
list.first().nextDownStreamMessage = replyUiModel list.first().nextDownStreamMessage = replyUiModel
list.add(0, replyUiModel) list.add(0, replyUiModel)
...@@ -159,6 +161,42 @@ class UiModelMapper @Inject constructor( ...@@ -159,6 +161,42 @@ class UiModelMapper @Inject constructor(
return@withContext list return@withContext list
} }
// TODO: move this to new interactor or FetchChatRoomsInteractor?
private suspend fun getChatRoomAsync(roomId: String): ChatRoom? = withContext(CommonPool) {
return@withContext dbManager.chatRoomDao().get(roomId)?.let {
with(it.chatRoom) {
ChatRoom(
id = id,
subscriptionId = subscriptionId,
type = roomTypeOf(type),
unread = unread,
broadcast = broadcast ?: false,
alert = alert,
fullName = fullname,
name = name ?: "",
favorite = favorite ?: false,
default = isDefault ?: false,
readonly = readonly,
open = open,
lastMessage = null,
archived = false,
status = null,
user = null,
userMentions = userMentions,
client = client,
announcement = null,
description = null,
groupMentions = groupMentions,
roles = null,
topic = null,
lastSeen = this.lastSeen,
timestamp = timestamp,
updatedAt = updatedAt
)
}
}
}
private fun mapVisibleActions(viewModel: BaseUiModel<*>) { private fun mapVisibleActions(viewModel: BaseUiModel<*>) {
if (!settings.messageReadReceiptStoreUsers()) { if (!settings.messageReadReceiptStoreUsers()) {
viewModel.menuItemsToHide.add(R.id.action_message_info) viewModel.menuItemsToHide.add(R.id.action_message_info)
...@@ -199,7 +237,7 @@ class UiModelMapper @Inject constructor( ...@@ -199,7 +237,7 @@ class UiModelMapper @Inject constructor(
} }
if (isBroadcastReplyAvailable(roomUiModel, message)) { if (isBroadcastReplyAvailable(roomUiModel, message)) {
roomsInteractor.getById(currentServer, message.roomId)?.let { chatRoom -> getChatRoomAsync(message.roomId)?.let { chatRoom ->
val replyUiModel = mapMessageReply(message, chatRoom) val replyUiModel = mapMessageReply(message, chatRoom)
list.first().nextDownStreamMessage = replyUiModel list.first().nextDownStreamMessage = replyUiModel
list.add(0, replyUiModel) list.add(0, replyUiModel)
...@@ -218,8 +256,8 @@ class UiModelMapper @Inject constructor( ...@@ -218,8 +256,8 @@ class UiModelMapper @Inject constructor(
private fun isBroadcastReplyAvailable(roomUiModel: RoomUiModel, message: Message): Boolean { private fun isBroadcastReplyAvailable(roomUiModel: RoomUiModel, message: Message): Boolean {
val senderUsername = message.sender?.username val senderUsername = message.sender?.username
return roomUiModel.isRoom && roomUiModel.isBroadcast && return roomUiModel.isRoom && roomUiModel.isBroadcast &&
!message.isSystemMessage() && !message.isSystemMessage() &&
senderUsername != currentUsername senderUsername != currentUsername
} }
private fun mapMessageReply(message: Message, chatRoom: ChatRoom): MessageReplyUiModel { private fun mapMessageReply(message: Message, chatRoom: ChatRoom): MessageReplyUiModel {
......
...@@ -9,9 +9,7 @@ import chat.rocket.android.chatrooms.ui.ChatRoomsFragment ...@@ -9,9 +9,7 @@ import chat.rocket.android.chatrooms.ui.ChatRoomsFragment
import chat.rocket.android.dagger.scope.PerFragment import chat.rocket.android.dagger.scope.PerFragment
import chat.rocket.android.db.ChatRoomDao import chat.rocket.android.db.ChatRoomDao
import chat.rocket.android.db.DatabaseManager import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.db.DatabaseManagerFactory
import chat.rocket.android.infrastructure.LocalRepository import chat.rocket.android.infrastructure.LocalRepository
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.domain.PublicSettings import chat.rocket.android.server.domain.PublicSettings
import chat.rocket.android.server.domain.SettingsRepository import chat.rocket.android.server.domain.SettingsRepository
import chat.rocket.android.server.infraestructure.ConnectionManager import chat.rocket.android.server.infraestructure.ConnectionManager
...@@ -37,13 +35,6 @@ class ChatRoomsFragmentModule { ...@@ -37,13 +35,6 @@ class ChatRoomsFragmentModule {
return frag return frag
} }
@Provides
@PerFragment
@Named("currentServer")
fun provideCurrentServer(currentServerInteractor: GetCurrentServerInteractor): String {
return currentServerInteractor.get()!!
}
@Provides @Provides
@PerFragment @PerFragment
fun provideRocketChatClient( fun provideRocketChatClient(
...@@ -53,15 +44,6 @@ class ChatRoomsFragmentModule { ...@@ -53,15 +44,6 @@ class ChatRoomsFragmentModule {
return factory.create(currentServer) return factory.create(currentServer)
} }
@Provides
@PerFragment
fun provideDatabaseManager(
factory: DatabaseManagerFactory,
@Named("currentServer") currentServer: String
): DatabaseManager {
return factory.create(currentServer)
}
@Provides @Provides
@PerFragment @PerFragment
fun provideChatRoomDao(manager: DatabaseManager): ChatRoomDao = manager.chatRoomDao() fun provideChatRoomDao(manager: DatabaseManager): ChatRoomDao = manager.chatRoomDao()
......
...@@ -18,7 +18,7 @@ class FetchChatRoomsInteractor( ...@@ -18,7 +18,7 @@ class FetchChatRoomsInteractor(
suspend fun refreshChatRooms() { suspend fun refreshChatRooms() {
val rooms = retryIO("fetch chatRooms", times = 10, val rooms = retryIO("fetch chatRooms", times = 10,
initialDelay = 200, maxDelay = 2000) { initialDelay = 200, maxDelay = 2000) {
client.chatRooms().update.map { room -> client.chatRooms().update.map { room ->
mapChatRoom(room) mapChatRoom(room)
} }
...@@ -50,27 +50,28 @@ class FetchChatRoomsInteractor( ...@@ -50,27 +50,28 @@ class FetchChatRoomsInteractor(
} }
} }
return ChatRoomEntity( return ChatRoomEntity(
id = id, id = id,
subscriptionId = subscriptionId, subscriptionId = subscriptionId,
type = type.toString(), type = type.toString(),
name = name, name = name,
fullname = fullName, fullname = fullName,
userId = userId, userId = userId,
ownerId = user?.id, ownerId = user?.id,
readonly = readonly, readonly = readonly,
isDefault = default, isDefault = default,
favorite = favorite, favorite = favorite,
open = open, open = open,
alert = alert, alert = alert,
unread = unread, unread = unread,
userMentions = userMentions, userMentions = userMentions,
groupMentions = groupMentions, groupMentions = groupMentions,
updatedAt = updatedAt, updatedAt = updatedAt,
timestamp = timestamp, timestamp = timestamp,
lastSeen = lastSeen, lastSeen = lastSeen,
lastMessageText = lastMessage?.message, lastMessageText = lastMessage?.message,
lastMessageUserId = lastMessage?.sender?.id, lastMessageUserId = lastMessage?.sender?.id,
lastMessageTimestamp = lastMessage?.timestamp lastMessageTimestamp = lastMessage?.timestamp,
broadcast = broadcast
) )
} }
} }
......
...@@ -14,6 +14,8 @@ import chat.rocket.android.authentication.infraestructure.SharedPreferencesToken ...@@ -14,6 +14,8 @@ import chat.rocket.android.authentication.infraestructure.SharedPreferencesToken
import chat.rocket.android.chatroom.service.MessageService import chat.rocket.android.chatroom.service.MessageService
import chat.rocket.android.dagger.qualifier.ForAuthentication import chat.rocket.android.dagger.qualifier.ForAuthentication
import chat.rocket.android.dagger.qualifier.ForMessages import chat.rocket.android.dagger.qualifier.ForMessages
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.db.DatabaseManagerFactory
import chat.rocket.android.helper.MessageParser import chat.rocket.android.helper.MessageParser
import chat.rocket.android.infrastructure.LocalRepository import chat.rocket.android.infrastructure.LocalRepository
import chat.rocket.android.infrastructure.SharedPreferencesLocalRepository import chat.rocket.android.infrastructure.SharedPreferencesLocalRepository
...@@ -68,6 +70,7 @@ import ru.noties.markwon.SpannableConfiguration ...@@ -68,6 +70,7 @@ import ru.noties.markwon.SpannableConfiguration
import ru.noties.markwon.spans.SpannableTheme import ru.noties.markwon.spans.SpannableTheme
import timber.log.Timber import timber.log.Timber
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.inject.Named
import javax.inject.Singleton import javax.inject.Singleton
@Module @Module
...@@ -82,7 +85,7 @@ class AppModule { ...@@ -82,7 +85,7 @@ class AppModule {
@Provides @Provides
@Singleton @Singleton
fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor { fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger { val interceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
override fun log(message: String) { override fun log(message: String) {
Timber.d(message) Timber.d(message)
} }
...@@ -254,7 +257,12 @@ class AppModule { ...@@ -254,7 +257,12 @@ class AppModule {
} }
@Provides @Provides
fun provideMessageParser(context: Application, configuration: SpannableConfiguration, serverInteractor: GetCurrentServerInteractor, settingsInteractor: GetSettingsInteractor): MessageParser { fun provideMessageParser(
context: Application,
configuration: SpannableConfiguration,
serverInteractor: GetCurrentServerInteractor,
settingsInteractor: GetSettingsInteractor
): MessageParser {
val url = serverInteractor.get()!! val url = serverInteractor.get()!!
return MessageParser(context, configuration, settingsInteractor.get(url)) return MessageParser(context, configuration, settingsInteractor.get(url))
} }
...@@ -301,4 +309,18 @@ class AppModule { ...@@ -301,4 +309,18 @@ class AppModule {
fun provideJobSchedulerInteractor(jobScheduler: JobScheduler, jobInfo: JobInfo): JobSchedulerInteractor { fun provideJobSchedulerInteractor(jobScheduler: JobScheduler, jobInfo: JobInfo): JobSchedulerInteractor {
return JobSchedulerInteractorImpl(jobScheduler, jobInfo) return JobSchedulerInteractorImpl(jobScheduler, jobInfo)
} }
}
\ No newline at end of file @Provides
@Named("currentServer")
fun provideCurrentServer(currentServerInteractor: GetCurrentServerInteractor): String {
return currentServerInteractor.get()!!
}
@Provides
fun provideDatabaseManager(
factory: DatabaseManagerFactory,
@Named("currentServer") currentServer: String
): DatabaseManager {
return factory.create(currentServer)
}
}
...@@ -295,7 +295,8 @@ class DatabaseManager(val context: Application, ...@@ -295,7 +295,8 @@ class DatabaseManager(val context: Application,
lastSeen = subscription.lastSeen, lastSeen = subscription.lastSeen,
lastMessageText = room.lastMessage?.message, lastMessageText = room.lastMessage?.message,
lastMessageUserId = room.lastMessage?.sender?.id, lastMessageUserId = room.lastMessage?.sender?.id,
lastMessageTimestamp = room.lastMessage?.timestamp lastMessageTimestamp = room.lastMessage?.timestamp,
broadcast = room.broadcast
) )
} }
......
...@@ -7,7 +7,7 @@ import chat.rocket.android.db.model.UserEntity ...@@ -7,7 +7,7 @@ import chat.rocket.android.db.model.UserEntity
@Database( @Database(
entities = [UserEntity::class, ChatRoomEntity::class], entities = [UserEntity::class, ChatRoomEntity::class],
version = 3, version = 4,
exportSchema = true exportSchema = true
) )
abstract class RCDatabase : RoomDatabase() { abstract class RCDatabase : RoomDatabase() {
......
...@@ -19,6 +19,7 @@ import androidx.room.PrimaryKey ...@@ -19,6 +19,7 @@ import androidx.room.PrimaryKey
ForeignKey(entity = UserEntity::class, parentColumns = ["id"], childColumns = ["lastMessageUserId"]) ForeignKey(entity = UserEntity::class, parentColumns = ["id"], childColumns = ["lastMessageUserId"])
] ]
) )
data class ChatRoomEntity( data class ChatRoomEntity(
@PrimaryKey var id: String, @PrimaryKey var id: String,
var subscriptionId: String, var subscriptionId: String,
...@@ -40,7 +41,8 @@ data class ChatRoomEntity( ...@@ -40,7 +41,8 @@ data class ChatRoomEntity(
var lastSeen: Long? = -1, var lastSeen: Long? = -1,
var lastMessageText: String? = null, var lastMessageText: String? = null,
var lastMessageUserId: String? = null, var lastMessageUserId: String? = null,
var lastMessageTimestamp: Long? = null var lastMessageTimestamp: Long? = null,
var broadcast: Boolean? = false
) )
data class ChatRoom( data class ChatRoom(
......
...@@ -22,22 +22,6 @@ class FavoriteMessagesFragmentModule { ...@@ -22,22 +22,6 @@ class FavoriteMessagesFragmentModule {
return frag return frag
} }
@Provides
@PerFragment
@Named("currentServer")
fun provideCurrentServer(currentServerInteractor: GetCurrentServerInteractor): String {
return currentServerInteractor.get()!!
}
@Provides
@PerFragment
fun provideDatabaseManager(
factory: DatabaseManagerFactory,
@Named("currentServer") currentServer: String
): DatabaseManager {
return factory.create(currentServer)
}
@Provides @Provides
@PerFragment @PerFragment
fun provideJob() = Job() fun provideJob() = Job()
......
...@@ -3,15 +3,11 @@ package chat.rocket.android.files.di ...@@ -3,15 +3,11 @@ package chat.rocket.android.files.di
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import chat.rocket.android.core.lifecycle.CancelStrategy import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.dagger.scope.PerFragment import chat.rocket.android.dagger.scope.PerFragment
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.db.DatabaseManagerFactory
import chat.rocket.android.files.presentation.FilesView import chat.rocket.android.files.presentation.FilesView
import chat.rocket.android.files.ui.FilesFragment import chat.rocket.android.files.ui.FilesFragment
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import kotlinx.coroutines.experimental.Job import kotlinx.coroutines.experimental.Job
import javax.inject.Named
@Module @Module
class FilesFragmentModule { class FilesFragmentModule {
...@@ -22,22 +18,6 @@ class FilesFragmentModule { ...@@ -22,22 +18,6 @@ class FilesFragmentModule {
return frag return frag
} }
@Provides
@PerFragment
@Named("currentServer")
fun provideCurrentServer(currentServerInteractor: GetCurrentServerInteractor): String {
return currentServerInteractor.get()!!
}
@Provides
@PerFragment
fun provideDatabaseManager(
factory: DatabaseManagerFactory,
@Named("currentServer") currentServer: String
): DatabaseManager {
return factory.create(currentServer)
}
@Provides @Provides
@PerFragment @PerFragment
fun provideJob() = Job() fun provideJob() = Job()
......
...@@ -4,16 +4,12 @@ import androidx.lifecycle.LifecycleOwner ...@@ -4,16 +4,12 @@ import androidx.lifecycle.LifecycleOwner
import chat.rocket.android.chatroom.ui.ChatRoomActivity import chat.rocket.android.chatroom.ui.ChatRoomActivity
import chat.rocket.android.core.lifecycle.CancelStrategy import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.dagger.scope.PerFragment import chat.rocket.android.dagger.scope.PerFragment
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.db.DatabaseManagerFactory
import chat.rocket.android.members.presentation.MembersNavigator import chat.rocket.android.members.presentation.MembersNavigator
import chat.rocket.android.members.presentation.MembersView import chat.rocket.android.members.presentation.MembersView
import chat.rocket.android.members.ui.MembersFragment import chat.rocket.android.members.ui.MembersFragment
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import kotlinx.coroutines.experimental.Job import kotlinx.coroutines.experimental.Job
import javax.inject.Named
@Module @Module
class MembersFragmentModule { class MembersFragmentModule {
...@@ -28,22 +24,6 @@ class MembersFragmentModule { ...@@ -28,22 +24,6 @@ class MembersFragmentModule {
@PerFragment @PerFragment
fun provideChatRoomNavigator(activity: ChatRoomActivity) = MembersNavigator(activity) fun provideChatRoomNavigator(activity: ChatRoomActivity) = MembersNavigator(activity)
@Provides
@PerFragment
@Named("currentServer")
fun provideCurrentServer(currentServerInteractor: GetCurrentServerInteractor): String {
return currentServerInteractor.get()!!
}
@Provides
@PerFragment
fun provideDatabaseManager(
factory: DatabaseManagerFactory,
@Named("currentServer") currentServer: String
): DatabaseManager {
return factory.create(currentServer)
}
@Provides @Provides
@PerFragment @PerFragment
fun provideJob() = Job() fun provideJob() = Job()
......
...@@ -5,11 +5,9 @@ import chat.rocket.android.core.lifecycle.CancelStrategy ...@@ -5,11 +5,9 @@ import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.dagger.scope.PerFragment import chat.rocket.android.dagger.scope.PerFragment
import chat.rocket.android.mentions.presentention.MentionsView import chat.rocket.android.mentions.presentention.MentionsView
import chat.rocket.android.mentions.ui.MentionsFragment import chat.rocket.android.mentions.ui.MentionsFragment
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import kotlinx.coroutines.experimental.Job import kotlinx.coroutines.experimental.Job
import javax.inject.Named
@Module @Module
class MentionsFragmentModule { class MentionsFragmentModule {
...@@ -20,13 +18,6 @@ class MentionsFragmentModule { ...@@ -20,13 +18,6 @@ class MentionsFragmentModule {
return frag return frag
} }
@Provides
@PerFragment
@Named("currentServer")
fun provideCurrentServer(currentServerInteractor: GetCurrentServerInteractor): String {
return currentServerInteractor.get()!!
}
@Provides @Provides
@PerFragment @PerFragment
fun provideJob() = Job() fun provideJob() = Job()
......
...@@ -3,15 +3,11 @@ package chat.rocket.android.pinnedmessages.di ...@@ -3,15 +3,11 @@ package chat.rocket.android.pinnedmessages.di
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import chat.rocket.android.core.lifecycle.CancelStrategy import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.dagger.scope.PerFragment import chat.rocket.android.dagger.scope.PerFragment
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.db.DatabaseManagerFactory
import chat.rocket.android.pinnedmessages.presentation.PinnedMessagesView import chat.rocket.android.pinnedmessages.presentation.PinnedMessagesView
import chat.rocket.android.pinnedmessages.ui.PinnedMessagesFragment import chat.rocket.android.pinnedmessages.ui.PinnedMessagesFragment
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import kotlinx.coroutines.experimental.Job import kotlinx.coroutines.experimental.Job
import javax.inject.Named
@Module @Module
class PinnedMessagesFragmentModule { class PinnedMessagesFragmentModule {
...@@ -22,22 +18,6 @@ class PinnedMessagesFragmentModule { ...@@ -22,22 +18,6 @@ class PinnedMessagesFragmentModule {
return frag return frag
} }
@Provides
@PerFragment
@Named("currentServer")
fun provideCurrentServer(currentServerInteractor: GetCurrentServerInteractor): String {
return currentServerInteractor.get()!!
}
@Provides
@PerFragment
fun provideDatabaseManager(
factory: DatabaseManagerFactory,
@Named("currentServer") currentServer: String
): DatabaseManager {
return factory.create(currentServer)
}
@Provides @Provides
@PerFragment @PerFragment
fun provideJob() = Job() fun provideJob() = Job()
......
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