This repository has been archived by the owner on Jun 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 552
/
ChatRoomPresenter.kt
1413 lines (1322 loc) · 55.8 KB
/
ChatRoomPresenter.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package chat.rocket.android.chatroom.presentation
import android.graphics.Bitmap
import android.net.Uri
import chat.rocket.android.R
import chat.rocket.android.analytics.AnalyticsManager
import chat.rocket.android.analytics.event.SubscriptionTypeEvent
import chat.rocket.android.chatroom.adapter.AutoCompleteType
import chat.rocket.android.chatroom.adapter.PEOPLE
import chat.rocket.android.chatroom.adapter.ROOMS
import chat.rocket.android.chatroom.domain.UriInteractor
import chat.rocket.android.chatroom.uimodel.RoomUiModel
import chat.rocket.android.chatroom.uimodel.UiModelMapper
import chat.rocket.android.chatroom.uimodel.suggestion.ChatRoomSuggestionUiModel
import chat.rocket.android.chatroom.uimodel.suggestion.CommandSuggestionUiModel
import chat.rocket.android.chatroom.uimodel.suggestion.EmojiSuggestionUiModel
import chat.rocket.android.chatroom.uimodel.suggestion.PeopleSuggestionUiModel
import chat.rocket.android.chatrooms.adapter.RoomUiModelMapper
import chat.rocket.android.core.behaviours.showMessage
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.emoji.EmojiRepository
import chat.rocket.android.helper.MessageHelper
import chat.rocket.android.helper.UserHelper
import chat.rocket.android.infrastructure.LocalRepository
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.JobSchedulerInteractor
import chat.rocket.android.server.domain.MessagesRepository
import chat.rocket.android.server.domain.PermissionsInteractor
import chat.rocket.android.server.domain.PublicSettings
import chat.rocket.android.server.domain.TokenRepository
import chat.rocket.android.server.domain.UsersRepository
import chat.rocket.android.server.domain.uploadMaxFileSize
import chat.rocket.android.server.domain.uploadMimeTypeFilter
import chat.rocket.android.server.domain.useRealName
import chat.rocket.android.server.infrastructure.ConnectionManagerFactory
import chat.rocket.android.util.extension.getByteArray
import chat.rocket.android.util.extension.launchUI
import chat.rocket.android.util.extensions.avatarUrl
import chat.rocket.android.util.retryDB
import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatException
import chat.rocket.common.model.RoomType
import chat.rocket.common.model.SimpleUser
import chat.rocket.common.model.UserStatus
import chat.rocket.common.model.roomTypeOf
import chat.rocket.common.util.ifNull
import chat.rocket.core.internal.realtime.setTypingStatus
import chat.rocket.core.internal.realtime.socket.model.State
import chat.rocket.core.internal.realtime.subscribeRoomMessages
import chat.rocket.core.internal.realtime.subscribeTypingStatus
import chat.rocket.core.internal.realtime.unsubscribe
import chat.rocket.core.internal.rest.chatRoomRoles
import chat.rocket.core.internal.rest.commands
import chat.rocket.core.internal.rest.deleteMessage
import chat.rocket.core.internal.rest.getMembers
import chat.rocket.core.internal.rest.history
import chat.rocket.core.internal.rest.joinChat
import chat.rocket.core.internal.rest.markAsRead
import chat.rocket.core.internal.rest.messages
import chat.rocket.core.internal.rest.pinMessage
import chat.rocket.core.internal.rest.reportMessage
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.spotlight
import chat.rocket.core.internal.rest.starMessage
import chat.rocket.core.internal.rest.toggleReaction
import chat.rocket.core.internal.rest.unpinMessage
import chat.rocket.core.internal.rest.unstarMessage
import chat.rocket.core.internal.rest.updateMessage
import chat.rocket.core.internal.rest.uploadFile
import chat.rocket.core.model.ChatRoom
import chat.rocket.core.model.ChatRoomRole
import chat.rocket.core.model.Command
import chat.rocket.core.model.Message
import chat.rocket.core.model.Room
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.threeten.bp.Instant
import timber.log.Timber
import java.util.*
import javax.inject.Inject
class ChatRoomPresenter @Inject constructor(
private val view: ChatRoomView,
private val navigator: ChatRoomNavigator,
private val strategy: CancelStrategy,
private val permissions: PermissionsInteractor,
private val uriInteractor: UriInteractor,
private val messagesRepository: MessagesRepository,
private val usersRepository: UsersRepository,
private val localRepository: LocalRepository,
private val analyticsManager: AnalyticsManager,
private val userHelper: UserHelper,
private val mapper: UiModelMapper,
private val roomMapper: RoomUiModelMapper,
private val jobSchedulerInteractor: JobSchedulerInteractor,
private val messageHelper: MessageHelper,
private val dbManager: DatabaseManager,
tokenRepository: TokenRepository,
getSettingsInteractor: GetSettingsInteractor,
serverInteractor: GetCurrentServerInteractor,
factory: ConnectionManagerFactory
) {
private val currentServer = serverInteractor.get()!!
private val manager = factory.create(currentServer)
private val client = manager!!.client
private var settings: PublicSettings = getSettingsInteractor.get(serverInteractor.get()!!)
private val token = tokenRepository.get(currentServer)
private val currentLoggedUsername = userHelper.username()
private var chatRoomId: String? = null
private lateinit var chatRoomType: String
private lateinit var chatRoomName: String
private var isBroadcast: Boolean = false
private var chatRoles = emptyList<ChatRoomRole>()
private val stateChannel = Channel<State>()
private var roomMessagesSubscriptionId: String? = null
private var typingStatusSubscriptionId: String? = null
private var lastState = client.state
private var typingStatusList = arrayListOf<String>()
private val roomChangesChannel = Channel<Room>(Channel.CONFLATED)
private var lastMessageId: String? = null
private lateinit var draftKey: String
fun setupChatRoom(
roomId: String,
roomName: String,
roomType: String,
chatRoomMessage: String? = null
) {
draftKey = "${currentServer}_${LocalRepository.DRAFT_KEY}$roomId"
chatRoomId = roomId
chatRoomType = roomType
chatRoomName = roomName
chatRoles = emptyList()
var canModerate = isOwnerOrMod()
GlobalScope.launch(Dispatchers.IO + strategy.jobs) {
// Can post anyway if has the 'post-readonly' permission on server.
val room = dbManager.getRoom(roomId)
room?.let {
isBroadcast = it.chatRoom.broadcast ?: false
val roomUiModel = roomMapper.map(it, true)
launchUI(strategy) {
view.onRoomUpdated(
roomUiModel = roomUiModel.copy(
broadcast = isBroadcast,
canModerate = canModerate,
writable = roomUiModel.writable || canModerate
)
)
}
}
loadMessages(roomId, chatRoomType, clearDataSet = true)
loadActiveMembers(roomId, chatRoomType, filterSelfOut = true)
chatRoomMessage?.let { messageHelper.messageIdFromPermalink(it) }
?.let { messageId ->
val name = messageHelper.roomNameFromPermalink(chatRoomMessage)
citeMessage(
name!!,
messageHelper.roomTypeFromPermalink(chatRoomMessage)!!,
messageId,
true
)
}
/*FIXME: Get chat role can cause unresponsive problems especially on slower connections
We are updating the room again after the first step so that initial messages
get loaded in and the system appears more responsive. Something should be
done to either fix the load in speed of moderator roles or store the
information locally*/
if (getChatRole()) {
canModerate = isOwnerOrMod()
if (canModerate) {
//FIXME: add this in when moderator page is actually created
//view.updateModeration()
}
}
subscribeRoomChanges()
}
}
private suspend fun getChatRole(): Boolean {
try {
if (roomTypeOf(chatRoomType) !is RoomType.DirectMessage) {
chatRoles = withContext(Dispatchers.IO + strategy.jobs) {
client.chatRoomRoles(
roomType = roomTypeOf(chatRoomType),
roomName = chatRoomName
)
}
return true
} else {
chatRoles = emptyList()
}
} catch (ex: Exception) {
Timber.e(ex)
chatRoles = emptyList()
}
return false
}
private suspend fun subscribeRoomChanges() {
withContext(Dispatchers.IO + strategy.jobs) {
chatRoomId?.let {
manager?.addRoomChannel(it, roomChangesChannel)
for (room in roomChangesChannel) {
dbManager.getRoom(room.id)?.let { chatRoom ->
view.onRoomUpdated(
roomMapper.map(
chatRoom = chatRoom,
showLastMessage = true
)
)
}
}
}
}
}
private fun unsubscribeRoomChanges() {
chatRoomId?.let { manager?.removeRoomChannel(it) }
}
private fun isOwnerOrMod(): Boolean {
return chatRoles.firstOrNull { it.user.username == currentLoggedUsername }?.roles?.any {
it == "owner" || it == "moderator"
} ?: false
}
fun loadMessages(
chatRoomId: String,
chatRoomType: String,
offset: Long = 0,
clearDataSet: Boolean = false
) {
this.chatRoomId = chatRoomId
this.chatRoomType = chatRoomType
GlobalScope.launch(Dispatchers.IO + strategy.jobs) {
try {
if (offset == 0L) {
// FIXME - load just 50 messages from DB to speed up. We will reload from Network after that
// FIXME - We need to handle the pagination, first fetch from DB, then from network
val localMessages = messagesRepository.getRecentMessages(chatRoomId, 50)
val oldMessages = mapper.map(
localMessages, RoomUiModel(
roles = chatRoles,
// FIXME: Why are we fixing isRoom attribute to true here?
isBroadcast = isBroadcast, isRoom = true
)
)
lastMessageId = localMessages.firstOrNull()?.id
val lastSyncDate = messagesRepository.getLastSyncDate(chatRoomId)
if (oldMessages.isNotEmpty() && lastSyncDate != null) {
view.showMessages(oldMessages, clearDataSet)
loadMissingMessages()
} else {
loadAndShowMessages(chatRoomId, chatRoomType, offset, clearDataSet)
}
} else {
loadAndShowMessages(chatRoomId, chatRoomType, offset, clearDataSet)
}
// TODO: For now we are marking the room as read if we can get the messages (I mean, no exception occurs)
// but should mark only when the user sees the first unread message.
markRoomAsRead()
subscribeRoomMessages()
subscribeTypingStatus()
subscribeConnectionState()
} catch (ex: Exception) {
Timber.e(ex)
ex.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
}
}
}
private suspend fun loadAndShowMessages(
chatRoomId: String,
chatRoomType: String,
offset: Long = 0,
clearDataSet: Boolean
) {
val messages =
retryIO("loadAndShowMessages($chatRoomId, $chatRoomType, $offset") {
client.messages(chatRoomId, roomTypeOf(chatRoomType), offset, 30).result
}
messagesRepository.saveAll(messages)
//we are saving last sync date of latest synced chat room message
if (offset == 0L) {
//if success - saving last synced time
if (messages.isEmpty()) {
//chat history is empty - just saving current date
messagesRepository.saveLastSyncDate(chatRoomId, System.currentTimeMillis())
} else {
//assume that BE returns ordered messages, the first message is the latest one
messagesRepository.saveLastSyncDate(chatRoomId, messages.first().timestamp)
}
}
view.showMessages(
mapper.map(
messages,
RoomUiModel(roles = chatRoles, isBroadcast = isBroadcast, isRoom = true)
),
clearDataSet
)
}
fun searchMessages(chatRoomId: String, searchText: String) {
launchUI(strategy) {
try {
view.showLoading()
val messages = retryIO("searchMessages($chatRoomId, $searchText)") {
client.searchMessages(chatRoomId, searchText).result
}
view.showSearchedMessages(
mapper.map(
messages = messages,
roomUiModel = RoomUiModel(chatRoles, isBroadcast, true),
showDateAndHour = true
)
)
} catch (ex: Exception) {
Timber.e(ex)
ex.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun sendMessage(chatRoomId: String, text: String, messageId: String?) {
launchUI(strategy) {
try {
view.disableSendMessageButton()
// ignore message for now, will receive it on the stream
if (messageId == null) {
val id = UUID.randomUUID().toString()
val username = userHelper.username()
val user = userHelper.user()
val timestamp = maxOf(getTimeStampOfLastMessageInRoom() + 1,
Instant.now().toEpochMilli())
val newMessage = Message(
id = id,
roomId = chatRoomId,
message = text,
timestamp = timestamp,
sender = SimpleUser(user?.id, user?.username ?: username, user?.name),
attachments = null,
avatar = currentServer.avatarUrl(
username!!,
token?.userId,
token?.authToken
),
channels = null,
editedAt = null,
editedBy = null,
groupable = false,
parseUrls = false,
pinned = false,
starred = emptyList(),
mentions = emptyList(),
reactions = null,
senderAlias = null,
type = null,
updatedAt = null,
urls = null,
synced = false,
unread = true
)
try {
messagesRepository.save(newMessage)
view.showNewMessage(
mapper.map(
newMessage,
RoomUiModel(roles = chatRoles, isBroadcast = isBroadcast)
), false
)
client.sendMessage(id, chatRoomId, text)
messagesRepository.save(newMessage.copy(synced = true))
logMessageSent()
} catch (ex: Exception) {
// Ok, not very beautiful, but the backend sends us a not valid response
// When someone sends a message on a read-only channel, so we just ignore it
// and show a generic error message
// TODO - remove the generic message when we implement :userId:/message subscription
if (ex is IllegalStateException) {
Timber.d(ex, "Probably a read-only problem...")
view.showGenericErrorMessage()
} else {
// some other error, just rethrow it...
throw ex
}
}
lastMessageId = id
} else {
client.updateMessage(chatRoomId, messageId, text)
}
clearDraftMessage()
} catch (ex: Exception) {
Timber.e(ex, "Error sending message...")
jobSchedulerInteractor.scheduleSendingMessages()
} finally {
view.clearMessageComposition(true)
view.enableSendMessageButton()
}
}
}
fun reportMessage(messageId: String, description: String) {
launchUI(strategy) {
try {
retryIO("reportMessage($messageId, $description)") {
client.reportMessage(messageId = messageId, description = description)
}
view.showMessage(R.string.report_sent)
} catch (ex: RocketChatException) {
Timber.e(ex)
}
}
}
fun selectFile() {
view.showFileSelection(settings.uploadMimeTypeFilter())
}
fun uploadImage(roomId: String, mimeType: String, uri: Uri, bitmap: Bitmap, msg: String) {
launchUI(strategy) {
view.showLoading()
try {
withContext(Dispatchers.Default) {
val fileName = uriInteractor.getFileName(uri) ?: uri.toString()
if (fileName.isEmpty()) {
view.showInvalidFileMessage()
} else {
val byteArray =
bitmap.getByteArray(mimeType, 100, settings.uploadMaxFileSize())
retryIO("uploadFile($roomId, $fileName, $mimeType") {
client.uploadFile(
roomId,
fileName,
mimeType,
msg,
description = fileName
) {
byteArray.inputStream()
}
}
logMediaUploaded(mimeType)
}
}
} catch (ex: Exception) {
Timber.d(ex, "Error uploading image")
when (ex) {
is RocketChatException -> view.showMessage(ex)
else -> view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun uploadFile(roomId: String, mimeType: String, uri: Uri, msg: String) {
launchUI(strategy) {
view.showLoading()
try {
withContext(Dispatchers.Default) {
val fileName = uriInteractor.getFileName(uri) ?: uri.toString()
val fileSize = uriInteractor.getFileSize(uri)
val maxFileSizeAllowed = settings.uploadMaxFileSize()
when {
fileName.isEmpty() -> view.showInvalidFileMessage()
fileSize > maxFileSizeAllowed && maxFileSizeAllowed !in -1..0 ->
view.showInvalidFileSize(fileSize, maxFileSizeAllowed)
else -> {
retryIO("uploadFile($roomId, $fileName, $mimeType") {
client.uploadFile(
roomId,
fileName,
mimeType,
msg,
description = fileName
) {
uriInteractor.getInputStream(uri)
}
}
logMediaUploaded(mimeType)
}
}
}
} catch (ex: Exception) {
Timber.d(ex, "Error uploading file")
when (ex) {
is RocketChatException -> view.showMessage(ex)
else -> view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun uploadDrawingImage(roomId: String, byteArray: ByteArray, msg: String) {
launchUI(strategy) {
view.showLoading()
try {
withContext(Dispatchers.Default) {
val fileName = UUID.randomUUID().toString() + ".png"
val fileSize = byteArray.size
val mimeType = "image/png"
val maxFileSizeAllowed = settings.uploadMaxFileSize()
when {
fileSize > maxFileSizeAllowed && maxFileSizeAllowed !in -1..0 ->
view.showInvalidFileSize(fileSize, maxFileSizeAllowed)
else -> {
retryIO("uploadFile($roomId, $fileName, $mimeType") {
client.uploadFile(
roomId,
fileName,
mimeType,
msg,
description = fileName
) {
byteArray.inputStream()
}
}
}
}
}
} catch (ex: RocketChatException) {
Timber.d(ex)
ex.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun sendTyping() {
GlobalScope.launch(Dispatchers.IO + strategy.jobs) {
if (chatRoomId != null && currentLoggedUsername != null) {
client.setTypingStatus(chatRoomId.toString(), currentLoggedUsername, true)
}
}
}
fun sendNotTyping() {
GlobalScope.launch(Dispatchers.IO + strategy.jobs) {
if (chatRoomId != null && currentLoggedUsername != null) {
client.setTypingStatus(chatRoomId.toString(), currentLoggedUsername, false)
}
}
}
private fun markRoomAsRead() {
chatRoomId?.let { chatRoomId ->
launchUI(strategy) {
try {
retryIO(description = "markAsRead($chatRoomId)") { client.markAsRead(chatRoomId) }
} catch (ex: RocketChatException) {
view.showMessage(ex.message!!) // TODO Remove.
Timber.e(ex) // FIXME: Right now we are only catching the exception with Timber.
}
}
}
}
private suspend fun subscribeConnectionState() {
manager?.addStateChannel(stateChannel)
lastState = client.state
GlobalScope.launch(Dispatchers.IO + strategy.jobs) {
for (state in stateChannel) {
if (state != lastState) {
launch(Dispatchers.Main) { view.showConnectionState(state) }
if (state is State.Connected) {
jobSchedulerInteractor.scheduleSendingMessages()
loadMissingMessages()
}
}
lastState = state
}
}
}
private fun unsubscribeConnectionState() = manager?.removeStateChannel(stateChannel)
private fun loadMissingMessages() {
GlobalScope.launch(strategy.jobs) {
chatRoomId?.let { chatRoomId ->
val roomType = roomTypeOf(chatRoomType)
val lastSyncDate = messagesRepository.getLastSyncDate(chatRoomId)
// lastSyncDate or 0. LastSyncDate could be in case when we sent some messages offline(and saved them locally),
// but never has obtained chatMessages(or history) from remote. In this case we should sync all chat history from beginning
val instant = Instant.ofEpochMilli(lastSyncDate ?: 0).toString()
//
try {
val messages =
retryIO(description = "history($chatRoomId, $roomType, $instant)") {
client.history(
chatRoomId, roomType, count = 50,
oldest = instant
)
}
Timber.d("History: $messages")
if (messages.result.isNotEmpty()) {
val models = mapper.map(
messages.result, RoomUiModel(
roles = chatRoles,
isBroadcast = isBroadcast,
// FIXME: Why are we fixing isRoom attribute to true here?
isRoom = true
)
)
messagesRepository.saveAll(messages.result)
//if success - saving last synced time
//assume that BE returns ordered messages, the first message is the latest one
messagesRepository.saveLastSyncDate(
chatRoomId,
messages.result.first().timestamp
)
launchUI(strategy) {
view.showNewMessage(models, true)
}
if (messages.result.size == 50) {
// we loaded at least count messages, try one more to fetch more messages
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")
}
}
}
}
/**
* Delete the message with the given id.
*
* @param roomId The room id of the message to be deleted.
* @param id The id of the message to be deleted.
*/
fun deleteMessage(roomId: String, id: String) {
launchUI(strategy) {
if (!permissions.allowedMessageDeleting()) {
return@launchUI
}
//TODO: Default delete message always to true. Until we have the permissions system
//implemented, a user will only be able to delete his own messages.
try {
retryIO(description = "deleteMessage($roomId, $id)") {
client.deleteMessage(roomId, id, true)
}
// if Message_ShowDeletedStatus == true an update to that message will be dispatched.
// Otherwise we signalize that we just want the message removed.
if (!permissions.showDeletedStatus()) {
view.dispatchDeleteMessage(id)
}
} catch (e: RocketChatException) {
Timber.e(e)
}
}
}
/**
* Quote or reply a message.
*
* @param roomType The current room type.
* @param messageId The id of the message to make citation for.
* @param mentionAuthor true means the citation is a reply otherwise it's a quote.
*/
fun citeMessage(roomName: String, roomType: String, messageId: String, mentionAuthor: Boolean) {
launchUI(strategy) {
val message = messagesRepository.getById(messageId)
val currentUsername: String? = userHelper.user()?.username
message?.let { msg ->
val id = msg.id
val username = msg.sender?.username ?: ""
val mention = if (mentionAuthor && currentUsername != username) "@$username" else ""
val room =
if (roomTypeOf(roomType) is RoomType.DirectMessage) username else roomName
val chatRoomType = when (roomTypeOf(roomType)) {
is RoomType.DirectMessage -> "direct"
is RoomType.PrivateGroup -> "group"
is RoomType.Channel -> "channel"
is RoomType.LiveChat -> "livechat"
else -> "custom"
}
view.showReplyingAction(
username = getDisplayName(msg.sender),
replyMarkdown = "[ ]($currentServer/$chatRoomType/$room?msg=$id) $mention ",
quotedMessage = mapper.map(
message, RoomUiModel(
roles = chatRoles,
isBroadcast = isBroadcast
)
).last().preview?.message ?: ""
)
}
}
}
private fun getDisplayName(user: SimpleUser?): String {
val username = user?.username ?: ""
return if (settings.useRealName()) user?.name ?: "@$username" else "@$username"
}
/**
* Copy message to clipboard.
*
* @param messageId The id of the message to copy to clipboard.
*/
fun copyMessage(messageId: String) {
launchUI(strategy) {
try {
messagesRepository.getById(messageId)?.let { m ->
view.copyToClipboard(m.message)
view.showMessage(R.string.msg_message_copied)
}
} catch (e: RocketChatException) {
Timber.e(e)
}
}
}
/**
* Update message identified by given id with given text.
*
* @param roomId The id of the room of the message.
* @param messageId The id of the message to update.
* @param text The updated text.
*/
fun editMessage(roomId: String, messageId: String, text: String) {
launchUI(strategy) {
if (!permissions.allowedMessageEditing()) {
view.showMessage(R.string.permission_editing_not_allowed)
return@launchUI
}
view.showEditingAction(roomId, messageId, text)
}
}
fun starMessage(messageId: String) {
launchUI(strategy) {
if (!permissions.allowedMessageStarring()) {
view.showMessage(R.string.permission_starring_not_allowed)
return@launchUI
}
try {
retryIO("starMessage($messageId)") { client.starMessage(messageId) }
} catch (e: RocketChatException) {
Timber.e(e)
}
}
}
fun unstarMessage(messageId: String) {
launchUI(strategy) {
if (!permissions.allowedMessageStarring()) {
view.showMessage(R.string.permission_starring_not_allowed)
return@launchUI
}
try {
retryIO("unstarMessage($messageId)") { client.unstarMessage(messageId) }
} catch (e: RocketChatException) {
Timber.e(e)
}
}
}
fun pinMessage(messageId: String) {
launchUI(strategy) {
if (!permissions.allowedMessagePinning()) {
view.showMessage(R.string.permission_pinning_not_allowed)
return@launchUI
}
try {
retryIO("pinMessage($messageId)") { client.pinMessage(messageId) }
} catch (e: RocketChatException) {
Timber.e(e)
}
}
}
fun unpinMessage(messageId: String) {
launchUI(strategy) {
if (!permissions.allowedMessagePinning()) {
view.showMessage(R.string.permission_pinning_not_allowed)
return@launchUI
}
try {
retryIO("unpinMessage($messageId)") { client.unpinMessage(messageId) }
} catch (e: RocketChatException) {
Timber.e(e)
}
}
}
suspend fun loadActiveMembers(
chatRoomId: String,
chatRoomType: String,
offset: Long = 0,
filterSelfOut: Boolean = false
) {
val activeUsers = mutableListOf<PeopleSuggestionUiModel>()
withContext(Dispatchers.IO + strategy.jobs) {
try {
val members = retryIO("getMembers($chatRoomId, $chatRoomType, $offset)") {
client.getMembers(chatRoomId, roomTypeOf(chatRoomType), offset, 50).result
}.take(50) // Get only 50, the backend is returning 7k+ users
usersRepository.saveAll(members)
dbManager.processUsersBatch(members)
val self = localRepository.get(LocalRepository.CURRENT_USERNAME_KEY)
// Take at most the 100 most recent messages distinguished by user. Can return less.
val recentMessages = messagesRepository.getRecentMessages(chatRoomId, 100)
.filterNot { filterSelfOut && it.sender?.username == self }
recentMessages.forEach {
val sender = it.sender
val username = sender?.username ?: ""
val name = sender?.name ?: ""
val avatarUrl =
currentServer.avatarUrl(username, token?.userId, token?.authToken)
val found = members.firstOrNull { member -> member.username == username }
val status = if (found != null) found.status else UserStatus.Offline()
val searchList = mutableListOf(username, name)
activeUsers.add(
PeopleSuggestionUiModel(
avatarUrl, username, username, name, status,
true, searchList
)
)
}
// Filter out from members list the active users.
val others = members.filterNot { member ->
activeUsers.firstOrNull {
it.username == member.username
} != null
}
// Add found room members who're not active enough and add them in without pinning.
activeUsers.addAll(others.map {
val username = it.username ?: ""
val name = it.name ?: ""
val avatarUrl =
currentServer.avatarUrl(username, token?.userId, token?.authToken)
val searchList = mutableListOf(username, name)
PeopleSuggestionUiModel(
avatarUrl,
username,
username,
name,
it.status,
true,
searchList
)
})
} catch (e: RocketChatException) {
Timber.e(e)
}
}
launchUI(strategy) {
view.populatePeopleSuggestions(activeUsers)
}
}
fun spotlight(query: String, @AutoCompleteType type: Int, filterSelfOut: Boolean = false) {
launchUI(strategy) {
try {
val (users, rooms) = retryIO("spotlight($query)") { client.spotlight(query) }
when (type) {
PEOPLE -> {
if (users.isNotEmpty()) {
usersRepository.saveAll(users)
}
val self = localRepository.get(LocalRepository.CURRENT_USERNAME_KEY)
view.populatePeopleSuggestions(users.map {
val username = it.username ?: ""
val name = it.name ?: ""
val searchList = mutableListOf(username, name)
it.emails?.forEach { email -> searchList.add(email.address) }
PeopleSuggestionUiModel(
currentServer.avatarUrl(username, token?.userId, token?.authToken),
username, username, name, it.status, false, searchList
)
}.filterNot { filterSelfOut && self != null && self == it.text })
}
ROOMS -> {
view.populateRoomSuggestions(rooms.map {
val fullName = it.fullName ?: ""
val name = it.name ?: ""
val searchList = mutableListOf(fullName, name)
ChatRoomSuggestionUiModel(name, fullName, name, searchList)
})
}
}
} catch (e: RocketChatException) {
Timber.e(e)
}
}
}
fun toChatDetails(
chatRoomId: String,
chatRoomType: String,
isSubscribed: Boolean,
isFavorite: Boolean,
isMenuDisabled: Boolean
) {
navigator.toChatDetails(chatRoomId, chatRoomType, isSubscribed, isFavorite, isMenuDisabled)
}
fun loadChatRoomsSuggestions() {
launchUI(strategy) {
try {
val chatRooms = getChatRoomsAsync()
.filterNot {
it.type is RoomType.DirectMessage || it.type is RoomType.LiveChat
}
.map { chatRoom ->
val name = chatRoom.name ?: ""
val fullName = chatRoom.fullName ?: ""
ChatRoomSuggestionUiModel(
text = name,
name = name,
fullName = fullName,
searchList = listOf(name, fullName)
)
}
view.populateRoomSuggestions(chatRooms)
} catch (e: RocketChatException) {
Timber.e(e)
}
}
}
// TODO: move this to new interactor or FetchChatRoomsInteractor?
private suspend fun getChatRoomAsync(roomId: String): ChatRoom? = withContext(Dispatchers.IO) {
retryDB("getRoom($roomId)") {
dbManager.chatRoomDao().getSync(roomId)?.let {
with(it.chatRoom) {
ChatRoom(
id = id,
subscriptionId = subscriptionId,
parentId = parentId,
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,