forked from nextcloud/talk-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatViewModel.kt
More file actions
1944 lines (1673 loc) · 74.6 KB
/
Copy pathChatViewModel.kt
File metadata and controls
1944 lines (1673 loc) · 74.6 KB
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
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2024 Christian Reiner <foss@christian-reiner.info>
* SPDX-FileCopyrightText: 2023 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.chat.viewmodels
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.provider.OpenableColumns
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.nextcloud.talk.arbitrarystorage.ArbitraryStorageManager
import com.nextcloud.talk.chat.data.ChatMessageRepository
import com.nextcloud.talk.chat.data.io.AudioFocusRequestManager
import com.nextcloud.talk.chat.data.io.MediaPlayerManager
import com.nextcloud.talk.chat.data.io.MediaRecorderManager
import com.nextcloud.talk.chat.data.model.ChatMessage
import com.nextcloud.talk.chat.data.network.ChatNetworkDataSource
import com.nextcloud.talk.chat.ui.model.ChatMessageUi
import com.nextcloud.talk.chat.ui.model.MessageTypeContent
import com.nextcloud.talk.chat.ui.model.toUiModel
import com.nextcloud.talk.application.NextcloudTalkApplication
import com.nextcloud.talk.conversationlist.DirectShareHelper
import com.nextcloud.talk.conversationlist.data.OfflineConversationsRepository
import com.nextcloud.talk.conversationlist.data.network.OfflineFirstConversationsRepository
import com.nextcloud.talk.conversationlist.viewmodels.ConversationsListViewModel.Companion.FOLLOWED_THREADS_EXIST
import com.nextcloud.talk.data.database.mappers.toDomainModel
import com.nextcloud.talk.data.database.model.ChatMessageEntity
import com.nextcloud.talk.data.user.model.User
import com.nextcloud.talk.extensions.toIntOrZero
import androidx.lifecycle.asFlow
import androidx.work.WorkManager
import com.nextcloud.talk.jobs.UploadAndShareFilesWorker
import com.nextcloud.talk.models.MessageDraft
import com.nextcloud.talk.models.domain.ConversationModel
import com.nextcloud.talk.models.domain.ReactionAddedModel
import com.nextcloud.talk.models.domain.ReactionDeletedModel
import com.nextcloud.talk.models.json.capabilities.SpreedCapability
import com.nextcloud.talk.models.json.chat.ChatMessageJson
import com.nextcloud.talk.models.json.chat.ChatOverallSingleMessage
import com.nextcloud.talk.models.json.conversations.ConversationEnums
import com.nextcloud.talk.models.json.conversations.RoomOverall
import com.nextcloud.talk.models.json.generic.GenericOverall
import com.nextcloud.talk.models.json.opengraph.OpenGraphObject
import com.nextcloud.talk.models.json.reminder.Reminder
import com.nextcloud.talk.models.json.threads.ThreadInfo
import com.nextcloud.talk.models.json.upcomingEvents.UpcomingEvent
import com.nextcloud.talk.models.json.userAbsence.UserAbsenceData
import com.nextcloud.talk.repositories.reactions.ReactionsRepository
import com.nextcloud.talk.threadsoverview.data.ThreadsRepository
import com.nextcloud.talk.ui.PlaybackSpeed
import com.nextcloud.talk.utils.ApiUtils
import com.nextcloud.talk.utils.ParticipantPermissions
import com.nextcloud.talk.utils.UserIdUtils
import com.nextcloud.talk.utils.bundle.BundleKeys
import com.nextcloud.talk.utils.database.user.CurrentUserProvider
import com.nextcloud.talk.utils.preferences.AppPreferences
import com.nextcloud.talk.webrtc.WebSocketConnectionHelper
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import retrofit2.HttpException
import java.io.File
import java.io.IOException
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.util.UUID
import javax.inject.Inject
import androidx.core.net.toUri
@Suppress("TooManyFunctions", "LongParameterList")
class ChatViewModel @AssistedInject constructor(
// should be removed here. Use it via RetrofitChatNetwork
private val appPreferences: AppPreferences,
private val chatNetworkDataSource: ChatNetworkDataSource,
private val chatRepository: ChatMessageRepository,
private val threadsRepository: ThreadsRepository,
private val conversationRepository: OfflineConversationsRepository,
private val reactionsRepository: ReactionsRepository,
private val mediaRecorderManager: MediaRecorderManager,
private val audioFocusRequestManager: AudioFocusRequestManager,
private val currentUserProvider: CurrentUserProvider,
@Assisted private val chatRoomToken: String,
@Assisted private val conversationThreadId: Long?
) : ViewModel(),
DefaultLifecycleObserver {
@Inject
lateinit var arbitraryStorageManager: ArbitraryStorageManager
enum class LifeCycleFlag {
PAUSED,
RESUMED,
STOPPED
}
@Deprecated("use currentUserFlow")
lateinit var currentUser: User
private var localLastReadMessage: Int = 0
private var showUnreadMessagesMarker: Boolean = true
private val mediaPlayerManager: MediaPlayerManager = MediaPlayerManager.sharedInstance(appPreferences)
lateinit var currentLifeCycleFlag: LifeCycleFlag
val disposableSet = mutableSetOf<Disposable>()
var mediaPlayerDuration = mediaPlayerManager.mediaPlayerDuration
val mediaPlayerPosition = mediaPlayerManager.mediaPlayerPosition
var messageDraft: MessageDraft = MessageDraft()
var hiddenUpcomingEvent: String? = null
lateinit var participantPermissions: ParticipantPermissions
private val _uploadProgressMap = MutableStateFlow<Map<String, Int>>(emptyMap())
val uploadProgressMap: StateFlow<Map<String, Int>> = _uploadProgressMap
// Maps referenceId -> fileUri for cancellation support
private val uploadReferenceToUri = mutableMapOf<String, String>()
fun cancelUpload(referenceId: String) {
val fileUri = uploadReferenceToUri.remove(referenceId) ?: return
WorkManager.getInstance(NextcloudTalkApplication.sharedApplication!!).cancelUniqueWork(fileUri)
viewModelScope.launch {
chatRepository.deleteTempMessageByReferenceId(referenceId)
}
_uploadProgressMap.update { it - referenceId }
}
fun getChatRepository(): ChatMessageRepository = chatRepository
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
currentLifeCycleFlag = LifeCycleFlag.RESUMED
mediaRecorderManager.handleOnResume()
chatRepository.handleOnResume()
mediaPlayerManager.handleOnResume()
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
currentLifeCycleFlag = LifeCycleFlag.PAUSED
disposableSet.forEach { disposable -> disposable.dispose() }
disposableSet.clear()
mediaRecorderManager.handleOnPause()
chatRepository.handleOnPause()
mediaPlayerManager.handleOnPause()
saveMessageDraft()
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
currentLifeCycleFlag = LifeCycleFlag.STOPPED
mediaRecorderManager.handleOnStop()
chatRepository.handleOnStop()
mediaPlayerManager.handleOnStop()
}
fun onSignalingChatMessageReceived(chatMessages: List<ChatMessageJson>) {
viewModelScope.launch {
chatRepository.onSignalingChatMessageReceived(chatMessages)
}
}
fun setUnreadMessagesMarker(shouldShow: Boolean) {
showUnreadMessagesMarker = shouldShow
}
val backgroundPlayUIFlow = mediaPlayerManager.backgroundPlayUIFlow
val mediaPlayerSeekbarObserver: Flow<ChatMessage>
get() = mediaPlayerManager.mediaPlayerSeekBarPositionMsg
val managerStateFlow: Flow<MediaPlayerManager.MediaPlayerManagerState>
get() = mediaPlayerManager.managerState
val voiceMessagePlayBackUIFlow: Flow<PlaybackSpeed>
get() = _voiceMessagePlayBackUIFlow
private val _voiceMessagePlayBackUIFlow: MutableSharedFlow<PlaybackSpeed> = MutableSharedFlow()
val getAudioFocusChange: LiveData<AudioFocusRequestManager.ManagerState>
get() = audioFocusRequestManager.getManagerState
private val _recordTouchObserver: MutableLiveData<Float> = MutableLiveData()
val recordTouchObserver: LiveData<Float>
get() = _recordTouchObserver
private val _getVoiceRecordingInProgress: MutableLiveData<Boolean> = MutableLiveData()
val getVoiceRecordingInProgress: LiveData<Boolean>
get() = _getVoiceRecordingInProgress
private val _getVoiceRecordingLocked: MutableLiveData<Boolean> = MutableLiveData()
val getVoiceRecordingLocked: LiveData<Boolean>
get() = _getVoiceRecordingLocked
private val _outOfOfficeViewState = MutableLiveData<OutOfOfficeUIState>(OutOfOfficeUIState.None)
val outOfOfficeViewState: LiveData<OutOfOfficeUIState>
get() = _outOfOfficeViewState
private val _upcomingEventViewState = MutableLiveData<UpcomingEventUIState>(UpcomingEventUIState.None)
val upcomingEventViewState: LiveData<UpcomingEventUIState>
get() = _upcomingEventViewState
private val _unbindRoomResult = MutableLiveData<UnbindRoomUiState>(UnbindRoomUiState.None)
val unbindRoomResult: LiveData<UnbindRoomUiState>
get() = _unbindRoomResult
private val _voiceMessagePlaybackSpeedPreferences: MutableLiveData<Map<String, PlaybackSpeed>> = MutableLiveData()
val voiceMessagePlaybackSpeedPreferences: LiveData<Map<String, PlaybackSpeed>>
get() = _voiceMessagePlaybackSpeedPreferences
private val _threadRetrieveState = MutableStateFlow<ThreadRetrieveUiState>(ThreadRetrieveUiState.None)
val threadRetrieveState: StateFlow<ThreadRetrieveUiState> = _threadRetrieveState
private val _reactionsSheetMessageId = MutableStateFlow<Long?>(null)
val reactionsSheetMessageId: StateFlow<Long?> = _reactionsSheetMessageId
fun showReactionsSheet(messageId: Long) {
_reactionsSheetMessageId.value = messageId
}
fun dismissReactionsSheet() {
_reactionsSheetMessageId.value = null
}
val getLastCommonReadFlow = chatRepository.lastCommonReadFlow
sealed interface ViewState
object GetReminderStartState : ViewState
open class GetReminderExistState(val reminder: Reminder) : ViewState
object GetReminderStateSet : ViewState
private val _getReminderExistState: MutableLiveData<ViewState> = MutableLiveData(GetReminderStartState)
val getReminderExistState: LiveData<ViewState>
get() = _getReminderExistState
object GetCapabilitiesStartState : ViewState
object GetCapabilitiesErrorState : ViewState
open class GetCapabilitiesInitialLoadState(
val spreedCapabilities: SpreedCapability,
val conversationModel: ConversationModel
) : ViewState
open class GetCapabilitiesUpdateState(val spreedCapabilities: SpreedCapability) : ViewState
private val _getCapabilitiesViewState: MutableLiveData<ViewState> = MutableLiveData(GetCapabilitiesStartState)
val getCapabilitiesViewState: LiveData<ViewState>
get() = _getCapabilitiesViewState
object JoinRoomStartState : ViewState
object JoinRoomErrorState : ViewState
open class JoinRoomSuccessState(val conversationModel: ConversationModel) : ViewState
private val _joinRoomViewState: MutableLiveData<ViewState> = MutableLiveData(JoinRoomStartState)
val joinRoomViewState: LiveData<ViewState>
get() = _joinRoomViewState
object LeaveRoomStartState : ViewState
class LeaveRoomSuccessState(val funToCallWhenLeaveSuccessful: (() -> Unit)?) : ViewState
private val _leaveRoomViewState: MutableLiveData<ViewState> = MutableLiveData(LeaveRoomStartState)
val leaveRoomViewState: LiveData<ViewState>
get() = _leaveRoomViewState
object ScheduledMessagesIdleState : ViewState
object ScheduledMessagesLoadingState : ViewState
data class ScheduledMessagesSuccessState(val messages: List<ChatMessage>) : ViewState
object ScheduledMessagesErrorState : ViewState
private val _scheduledMessagesViewState: MutableLiveData<ViewState> = MutableLiveData(ScheduledMessagesIdleState)
val scheduledMessagesViewState: LiveData<ViewState>
get() = _scheduledMessagesViewState
private val _scheduledMessagesCount = MutableLiveData<Int>()
val scheduledMessagesCount: LiveData<Int> = _scheduledMessagesCount
object DeleteChatMessageStartState : ViewState
class DeleteChatMessageSuccessState(val msg: ChatOverallSingleMessage) : ViewState
object DeleteChatMessageErrorState : ViewState
private val _deleteChatMessageViewState: MutableLiveData<ViewState> = MutableLiveData(DeleteChatMessageStartState)
val deleteChatMessageViewState: LiveData<ViewState>
get() = _deleteChatMessageViewState
object CreateRoomStartState : ViewState
object CreateRoomErrorState : ViewState
class CreateRoomSuccessState(val roomOverall: RoomOverall) : ViewState
private val _createRoomViewState: MutableLiveData<ViewState> = MutableLiveData(CreateRoomStartState)
val createRoomViewState: LiveData<ViewState>
get() = _createRoomViewState
object ReactionAddedStartState : ViewState
class ReactionAddedSuccessState(val reactionAddedModel: ReactionAddedModel) : ViewState
private val _reactionAddedViewState: MutableLiveData<ViewState> = MutableLiveData(ReactionAddedStartState)
val reactionAddedViewState: LiveData<ViewState>
get() = _reactionAddedViewState
object ReactionDeletedStartState : ViewState
class ReactionDeletedSuccessState(val reactionDeletedModel: ReactionDeletedModel) : ViewState
private val _reactionDeletedViewState: MutableLiveData<ViewState> = MutableLiveData(ReactionDeletedStartState)
val reactionDeletedViewState: LiveData<ViewState>
get() = _reactionDeletedViewState
@Volatile private var firstUnreadMessageId: Int? = null
@Volatile private var oneOrMoreMessagesWereSent = false
// ------------------------------
// UI State. This should be the only UI state. Add more val here and update via copy whenever necessary.
// ------------------------------
data class ChatUiState(
val items: List<ChatItem> = emptyList(),
val isOneToOneConversation: Boolean = false,
// Adding the whole conversation is just an intermediate solution as it is used in the activity.
// For the future, only necessary vars from conversation should be in the ui state
val conversation: ConversationModel? = null,
val pinnedMessage: ChatMessage? = null
)
private val _uiState = MutableStateFlow(ChatUiState())
val uiState: StateFlow<ChatUiState> = _uiState
// ------------------------------
// Current user flows
// ------------------------------
private val currentUserFlow: StateFlow<User?> =
currentUserProvider.currentUserFlow
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
private val nonNullUserFlow = currentUserFlow.filterNotNull()
private val conversationFlow: Flow<ConversationModel> =
nonNullUserFlow
.flatMapLatest { user ->
val userId = requireNotNull(user.id)
conversationRepository.observeConversation(userId, chatRoomToken)
}
.mapNotNull { result ->
when (result) {
is OfflineFirstConversationsRepository.ConversationResult.Found ->
result.conversation
OfflineFirstConversationsRepository.ConversationResult.NotFound ->
null
}
}
.distinctUntilChangedBy { it.lastReadMessage }
.onEach {
println("Conversation changed: lastRead=${it.lastReadMessage}")
}
private val conversationAndUserFlow =
combine(conversationFlow, nonNullUserFlow) { c, u -> c to u }
.shareIn(
viewModelScope,
SharingStarted.WhileSubscribed(CONVERSATION_AND_USER_FLOW_SHARING_TIMEOUT_MS),
replay = 1
)
// ------------------------------
// Messages
// ------------------------------
private fun Flow<List<ChatMessageEntity>>.mapToChatMessages(userId: String): Flow<List<ChatMessage>> =
map { entities ->
entities.map { entity ->
entity.toDomainModel().apply {
avatarUrl = getAvatarUrl(this)
incoming = actorId != userId
}
}
}
private val messagesFlow: Flow<List<ChatMessage>> =
conversationAndUserFlow
.flatMapLatest { (conversation, user) ->
chatRepository
.observeMessages(conversation.internalId)
.distinctUntilChanged()
.mapToChatMessages(user.userId!!)
}
.map { messages ->
messages.let(::handleSystemMessages)
.let(::handleThreadMessages)
}
// .distinctUntilChangedBy { it.map { msg -> msg.jsonMessageId } }
private val trackedParentIds = MutableStateFlow<Set<Long>>(emptySet())
private val parentMessagesFlow: Flow<Map<Long, ChatMessage>> =
trackedParentIds
.flatMapLatest { ids ->
if (ids.isEmpty()) {
flowOf(emptyMap())
} else {
chatRepository.observeParentMessages(ids.toList())
.map { messages -> messages.associateBy { it.jsonMessageId.toLong() } }
}
}
// ------------------------------
// Last read message cache
// ------------------------------
private var lastReadMessage: Int = 0
// ------------------------------
// Initialization
// ------------------------------
init {
observeConversation()
observeMessages()
observeMediaPlayerProgressForCompose()
observePinnedMessage()
observeRoomRefresh()
observeIncomingMessages()
}
private fun observeMediaPlayerProgressForCompose() {
mediaPlayerSeekbarObserver
.onEach { message ->
syncVoiceMessageUiState(message)
}
.launchIn(viewModelScope)
}
fun pauseVoiceMessageUiState(messageId: Int) {
_uiState.update { current ->
val updatedItems = current.items.map { item ->
if (item is ChatItem.MessageItem && item.uiMessage.id == messageId) {
val voiceContent = item.uiMessage.content as? MessageTypeContent.Voice
if (voiceContent != null) {
item.copy(uiMessage = item.uiMessage.copy(content = voiceContent.copy(isPlaying = false)))
} else {
item
}
} else {
item
}
}
current.copy(items = updatedItems)
}
}
fun setVoiceMessageSpeed(messageId: Int, speed: PlaybackSpeed) {
_uiState.update { current ->
val updatedItems = current.items.map { item ->
if (item is ChatItem.MessageItem && item.uiMessage.id == messageId) {
val voiceContent = item.uiMessage.content as? MessageTypeContent.Voice
if (voiceContent != null) {
item.copy(uiMessage = item.uiMessage.copy(content = voiceContent.copy(playbackSpeed = speed)))
} else {
item
}
} else {
item
}
}
current.copy(items = updatedItems)
}
}
fun syncVoiceMessageUiState(message: ChatMessage) {
_uiState.update { current ->
val updatedItems = current.items.map { item ->
if (item is ChatItem.MessageItem && item.uiMessage.id == message.jsonMessageId) {
val voiceContent = item.uiMessage.content as? MessageTypeContent.Voice
if (voiceContent != null) {
val updatedVoiceContent = voiceContent.copy(
actorId = message.actorId,
isPlaying = message.isPlayingVoiceMessage,
wasPlayed = message.wasPlayedVoiceMessage,
isDownloading = message.isDownloadingVoiceMessage,
durationSeconds = message.voiceMessageDuration,
playedSeconds = message.voiceMessagePlayedSeconds,
seekbarProgress = message.voiceMessageSeekbarProgress,
waveform = message.voiceMessageFloatArray?.toList() ?: voiceContent.waveform
// playbackSpeed is preserved from existing voiceContent
)
item.copy(uiMessage = item.uiMessage.copy(content = updatedVoiceContent))
} else {
item
}
} else {
item
}
}
current.copy(items = updatedItems)
}
}
// ------------------------------
// Observe conversation
// ------------------------------
private fun observeConversation() {
conversationFlow
.onEach { conversation ->
lastReadMessage = conversation.lastReadMessage
_uiState.update { current ->
current.copy(
conversation = conversation,
isOneToOneConversation = !conversation.isOneToOneConversation()
)
}
}
.launchIn(viewModelScope)
}
private fun observePinnedMessage() {
nonNullUserFlow
.flatMapLatest { user ->
conversationRepository.observeConversation(requireNotNull(user.id), chatRoomToken)
.mapNotNull { result ->
(result as? OfflineFirstConversationsRepository.ConversationResult.Found)?.conversation
}
.distinctUntilChangedBy { it.lastPinnedId to it.hiddenPinnedId }
.flatMapLatest { conversation ->
val pinnedId = conversation.lastPinnedId
if (pinnedId != null && pinnedId != 0L && pinnedId != conversation.hiddenPinnedId) {
val bundle = Bundle().apply {
putString(
BundleKeys.KEY_CHAT_URL,
ApiUtils.getUrlForChat(1, user.baseUrl, chatRoomToken)
)
putString(
BundleKeys.KEY_CREDENTIALS,
ApiUtils.getCredentials(user.username, user.token)
)
putString(BundleKeys.KEY_ROOM_TOKEN, chatRoomToken)
}
chatRepository.getMessage(pinnedId, bundle)
.map { it as ChatMessage? }
.catch { emit(null) }
} else {
flowOf(null)
}
}
}
.onEach { pinnedMessage ->
_uiState.update { it.copy(pinnedMessage = pinnedMessage) }
}
.catch { Log.e(TAG, "Error observing pinned message", it) }
.launchIn(viewModelScope)
}
private fun observeRoomRefresh() {
chatRepository.roomRefreshFlow
.debounce(ROOM_REFRESH_DEBOUNCE_MS)
.onEach { getRoom(chatRoomToken) }
.launchIn(viewModelScope)
}
private fun observeIncomingMessages() {
chatRepository.incomingMessageFlow
.onEach {
val (conversation, user) = conversationAndUserFlow.first()
val context = NextcloudTalkApplication.sharedApplication!!
val isOneToOne = conversation.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL
DirectShareHelper.reportIncomingMessage(
context,
user,
conversation.token,
conversation.displayName ?: conversation.token,
isOneToOne
)
}
.launchIn(viewModelScope)
}
// val lastCommonReadMessageId = getLastCommonReadFlow.first()
// ------------------------------
// Observe messages
// ------------------------------
// private fun observeMessages() {
// combine(messagesFlow, getLastCommonReadFlow) { messages, lastRead ->
// messages.map {
// it.toUiModel(
// it,
// lastRead,
// getParentMessage(it.parentMessageId)
// )
// }
// }
// .onEach { messages ->
// val items = buildChatItems(messages, lastReadMessage)
// _uiState.update { current ->
// current.copy(items = items)
// }
// }
// .launchIn(viewModelScope)
// }
private data class CombinedInput(
val messages: List<ChatMessage>,
val lastCommonRead: Int,
val parentMap: Map<Long, ChatMessage>,
val conversationLastRead: Int
)
private data class ProcessedMessages(val items: List<ChatItem>, val missingParentIds: List<Long>)
private fun observeMessages() {
// conversationFlow provides the user's own lastReadMessage for the unread marker.
// getLastCommonReadFlow provides the "last read by all" value for read-receipt checkmarks.
// These are two different concepts that must not be conflated.
combine(
messagesFlow,
getLastCommonReadFlow.onStart { emit(0) },
parentMessagesFlow,
conversationFlow.map { it.lastReadMessage }
) { messages, lastCommonRead, parentMap, conversationLastRead ->
CombinedInput(messages, lastCommonRead, parentMap, conversationLastRead)
}
.map { (messages, lastCommonRead, parentMap, conversationLastRead) ->
val messageMap: Map<Long, ChatMessage> = messages.associateBy { it.jsonMessageId.toLong() }
val combinedMap: Map<Long, ChatMessage> = messageMap + parentMap
val parentIds: List<Long> = messages.mapNotNull { it.parentMessageId }
val missingParentIds: List<Long> =
parentIds.filterNot { parentId -> combinedMap.containsKey(parentId) }
.distinct()
val user = currentUserFlow.value
applyMessageGrouping(messages)
val uiMessages = messages.map { message ->
val parent: ChatMessage? = combinedMap[message.parentMessageId]
message.toUiModel(
user = user ?: currentUser,
chatMessage = message,
lastCommonReadMessageId = lastCommonRead,
parentMessage = parent
)
}
val items = buildChatItems(uiMessages, conversationLastRead)
ProcessedMessages(items = items, missingParentIds = missingParentIds)
}
.flowOn(Dispatchers.Default)
.onEach { (items, missingParentIds) ->
if (missingParentIds.isNotEmpty()) {
trackedParentIds.update { it + missingParentIds }
viewModelScope.launch {
val user = currentUserFlow.value ?: return@launch
chatRepository.fetchMissingParents(
"${user.id}@$chatRoomToken",
missingParentIds
)
}
}
_uiState.update { current ->
current.copy(items = items)
}
}
.launchIn(viewModelScope)
}
// ------------------------------
// Build chat items (pure)
// ------------------------------
private fun buildChatItems(uiMessages: List<ChatMessageUi>, lastReadMessage: Int): List<ChatItem> {
var lastDate: LocalDate? = null
return buildList {
if (firstUnreadMessageId == null && lastReadMessage > 0) {
firstUnreadMessageId =
uiMessages.firstOrNull {
it.id > lastReadMessage
}?.id
Log.d(TAG, "reversedMessages.size = ${uiMessages.size}")
Log.d(TAG, "firstUnreadMessageId = $firstUnreadMessageId")
Log.d(TAG, "conversation.lastReadMessage = $lastReadMessage")
}
for (uiMessage in uiMessages) {
val date = uiMessage.date
if (date != lastDate) {
add(ChatItem.DateHeaderItem(date))
lastDate = date
}
if (!oneOrMoreMessagesWereSent && uiMessage.id == firstUnreadMessageId) {
add(ChatItem.UnreadMessagesMarkerItem(date))
}
add(ChatItem.MessageItem(uiMessage))
}
}.asReversed()
}
private fun applyMessageGrouping(messages: List<ChatMessage>) {
messages.forEachIndexed { index, message ->
message.isGrouped = index > 0 && shouldGroupMessage(message, messages[index - 1])
message.isGroupedWithNext = index < messages.size - 1 && shouldGroupMessage(messages[index + 1], message)
}
}
private fun shouldGroupMessage(current: ChatMessage, previous: ChatMessage): Boolean {
val sameMessageKind = current.isSystemMessage == previous.isSystemMessage
val notUnclassifiedBot = current.actorType != "bots" || current.actorId == "changelog"
val sameActor = current.isSystemMessage ||
(current.actorType == previous.actorType && current.actorId == previous.actorId)
val currentDate = Instant.ofEpochMilli(current.timestamp * TIMESTAMP_TO_MILLIS)
.atZone(ZoneId.systemDefault()).toLocalDate()
val previousDate = Instant.ofEpochMilli(previous.timestamp * TIMESTAMP_TO_MILLIS)
.atZone(ZoneId.systemDefault()).toLocalDate()
val timeDifference = kotlin.math.abs(current.timestamp - previous.timestamp)
val neitherEdited = (current.lastEditTimestamp ?: 0L) == 0L || (previous.lastEditTimestamp ?: 0L) == 0L
return sameMessageKind &&
notUnclassifiedBot &&
sameActor &&
currentDate == previousDate &&
current.actorId == previous.actorId &&
timeDifference <= GROUPING_TIME_WINDOW_SECONDS &&
neitherEdited
}
fun onMessageSent() {
oneOrMoreMessagesWereSent = true
}
fun observeConversationAndUserFirstTime() {
conversationAndUserFlow
.take(1)
.onEach { (conversation, user) ->
val credentials =
ApiUtils.getCredentials(user.username, user.token) ?: return@onEach
val url =
ApiUtils.getUrlForChat(1, user.baseUrl, chatRoomToken)
chatRepository.updateConversation(conversation)
val isChatRelaySupported = withTimeoutOrNull(WEBSOCKET_CONNECT_TIMEOUT_MS) {
awaitChatRelaySupport(user)
} ?: false
loadInitialMessages(
withCredentials = credentials,
withUrl = url,
isChatRelaySupported = isChatRelaySupported
)
viewModelScope.launch {
startMessagePolling(isChatRelaySupported)
}
getCapabilities(user, chatRoomToken, conversation)
}
.launchIn(viewModelScope)
}
fun isChatRelaySupported(user: User): Boolean {
val websocketInstance = WebSocketConnectionHelper.getWebSocketInstanceForUser(user)
return websocketInstance?.supportsChatRelay() == true
}
private suspend fun awaitChatRelaySupport(user: User): Boolean {
val wsInstance = WebSocketConnectionHelper.getWebSocketInstanceForUser(user) ?: return false
while (!wsInstance.isConnected) {
delay(WEBSOCKET_POLL_INTERVAL_MS)
}
return wsInstance.supportsChatRelay()
}
fun observeConversationAndUserEveryTime() {
conversationAndUserFlow
.onEach { (conversation, user) ->
chatRepository.updateConversation(conversation)
getCapabilities(user, chatRoomToken, conversation)
advanceLocalLastReadMessageIfNeeded(
conversation.lastReadMessage
)
}
.launchIn(viewModelScope)
}
private fun handleSystemMessages(chatMessageList: List<ChatMessage>): List<ChatMessage> {
fun shouldRemoveMessage(currentMessage: MutableMap.MutableEntry<Int, ChatMessage>): Boolean =
isInfoMessageAboutDeletion(currentMessage) ||
isReactionsMessage(currentMessage) ||
isPollVotedMessage(currentMessage) ||
isEditMessage(currentMessage) ||
isThreadCreatedMessage(currentMessage)
val chatMessageMap = chatMessageList.associateBy { it.jsonMessageId }.toMutableMap()
val chatMessageIterator = chatMessageMap.iterator()
while (chatMessageIterator.hasNext()) {
val currentMessage = chatMessageIterator.next()
if (shouldRemoveMessage(currentMessage)) {
chatMessageIterator.remove()
}
}
return chatMessageMap.values.toList()
}
private fun isInfoMessageAboutDeletion(currentMessage: MutableMap.MutableEntry<Int, ChatMessage>): Boolean =
currentMessage.value.parentMessageId != null &&
currentMessage.value.systemMessageType == ChatMessage
.SystemMessageType.MESSAGE_DELETED
private fun isReactionsMessage(currentMessage: MutableMap.MutableEntry<Int, ChatMessage>): Boolean =
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION ||
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_DELETED ||
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_REVOKED
private fun isThreadCreatedMessage(currentMessage: MutableMap.MutableEntry<Int, ChatMessage>): Boolean =
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.THREAD_CREATED
private fun isEditMessage(currentMessage: MutableMap.MutableEntry<Int, ChatMessage>): Boolean =
currentMessage.value.parentMessageId != null &&
currentMessage.value.systemMessageType == ChatMessage
.SystemMessageType.MESSAGE_EDITED
private fun isPollVotedMessage(currentMessage: MutableMap.MutableEntry<Int, ChatMessage>): Boolean =
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.POLL_VOTED
private fun handleThreadMessages(chatMessageList: List<ChatMessage>): List<ChatMessage> {
fun isThreadChildMessage(currentMessage: MutableMap.MutableEntry<Int, ChatMessage>): Boolean =
currentMessage.value.isThread &&
currentMessage.value.threadId?.toInt() != currentMessage.value.jsonMessageId
val chatMessageMap = chatMessageList.associateBy { it.jsonMessageId }.toMutableMap()
if (conversationThreadId == null) {
val chatMessageIterator = chatMessageMap.iterator()
while (chatMessageIterator.hasNext()) {
val currentMessage = chatMessageIterator.next()
if (isThreadChildMessage(currentMessage)) {
chatMessageIterator.remove()
}
}
}
return chatMessageMap.values.toList()
}
// val timeString = DateUtils.getLocalTimeStringFromTimestamp(message.timestamp)
fun getAvatarUrl(message: ChatMessage): String =
if (this::currentUser.isInitialized) {
ApiUtils.getUrlForAvatar(
currentUser.baseUrl,
message.actorId,
false
)
} else {
""
}
fun initData(user: User, credentials: String, urlForChatting: String, threadId: Long?) {
currentUser = user
chatRepository.initData(
user,
credentials,
urlForChatting,
chatRoomToken,
threadId
)
observeConversationAndUserFirstTime()
observeConversationAndUserEveryTime()
}
fun ConversationModel?.isOneToOneConversation(): Boolean =
this?.type ==
ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL
@Deprecated("use observeConversation")
fun getRoom(token: String) {
// _getRoomViewState.value = GetRoomStartState
conversationRepository.getRoom(currentUser, token)
}
fun loadScheduledMessages(credentials: String, url: String) {
_scheduledMessagesViewState.value = ScheduledMessagesLoadingState
viewModelScope.launch {
chatRepository.getScheduledChatMessages(credentials, url).collect { result ->
if (result.isSuccess) {
_scheduledMessagesViewState.value =
ScheduledMessagesSuccessState(result.getOrNull().orEmpty())
_scheduledMessagesCount.value = result.getOrNull()?.size ?: 0
} else {
_scheduledMessagesViewState.value = ScheduledMessagesErrorState
}
}
}
}
fun getCapabilities(user: User, token: String, conversationModel: ConversationModel) {
Log.d(TAG, "Remote server ${conversationModel.remoteServer}")
if (conversationModel.remoteServer.isNullOrEmpty()) {
if (_getCapabilitiesViewState.value == GetCapabilitiesStartState) {
_getCapabilitiesViewState.value = GetCapabilitiesInitialLoadState(
user.capabilities!!.spreedCapability!!,
conversationModel
)
} else {
_getCapabilitiesViewState.value = GetCapabilitiesUpdateState(user.capabilities!!.spreedCapability!!)
}
participantPermissions = ParticipantPermissions(
user.capabilities!!.spreedCapability!!,
conversationModel
)
} else {
chatNetworkDataSource.getCapabilities(user, token)
.subscribeOn(Schedulers.io())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe(object : Observer<SpreedCapability> {
override fun onSubscribe(d: Disposable) {
disposableSet.add(d)
}
override fun onNext(spreedCapabilities: SpreedCapability) {
if (_getCapabilitiesViewState.value == GetCapabilitiesStartState) {
_getCapabilitiesViewState.value = GetCapabilitiesInitialLoadState(
spreedCapabilities,
conversationModel
)
} else {
_getCapabilitiesViewState.value = GetCapabilitiesUpdateState(spreedCapabilities)
}
participantPermissions = ParticipantPermissions(
spreedCapabilities,
conversationModel
)
}
override fun onError(e: Throwable) {
Log.e(TAG, "Error when fetching spreed capabilities", e)
_getCapabilitiesViewState.value = GetCapabilitiesErrorState
}
override fun onComplete() {
// unused atm
}
})
}
}
fun joinRoom(user: User, token: String, roomPassword: String) {
_joinRoomViewState.value = JoinRoomStartState