Repository navigation
Expand file tree
/
Copy pathHomeActivity.kt
More file actions
993 lines (882 loc) · 40.6 KB
/
Copy pathHomeActivity.kt
File metadata and controls
993 lines (882 loc) · 40.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
package org.thoughtcrime.securesms.home
import android.Manifest
import android.app.NotificationManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.offset
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.squareup.phrase.Phrase
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import network.loki.messenger.BuildConfig
import network.loki.messenger.R
import network.loki.messenger.databinding.ActivityHomeBinding
import network.loki.messenger.libsession_util.PRIORITY_HIDDEN
import org.session.libsession.messaging.groups.GroupManagerV2
import org.session.libsession.messaging.groups.LegacyGroupDeprecationManager
import org.session.libsession.messaging.jobs.JobQueue
import org.session.libsession.messaging.sending_receiving.notifications.MessageNotifier
import org.session.libsession.network.SnodeClock
import org.session.libsession.network.model.PathStatus
import org.session.libsession.network.onion.PathManager
import org.session.libsession.utilities.Address
import org.session.libsession.utilities.StringSubstitutionConstants.GROUP_NAME_KEY
import org.session.libsession.utilities.StringSubstitutionConstants.NAME_KEY
import org.session.libsession.utilities.TextSecurePreferences
import org.session.libsession.utilities.recipients.RecipientData
import org.session.libsession.utilities.recipients.displayName
import org.session.libsession.utilities.updateContact
import org.session.libsession.utilities.withMutableUserConfigs
import org.session.libsignal.utilities.Log
import org.thoughtcrime.securesms.ScreenLockActionBarActivity
import org.thoughtcrime.securesms.auth.LoginStateRepository
import org.thoughtcrime.securesms.conversation.v2.ConversationActivityV2
import org.thoughtcrime.securesms.conversation.v2.messages.MessageFormatter
import org.thoughtcrime.securesms.conversation.v2.settings.notification.NotificationSettingsActivity
import org.thoughtcrime.securesms.crypto.IdentityKeyUtil
import org.thoughtcrime.securesms.database.GroupDatabase
import org.thoughtcrime.securesms.database.MmsSmsDatabase
import org.thoughtcrime.securesms.database.RecipientRepository
import org.thoughtcrime.securesms.database.Storage
import org.thoughtcrime.securesms.database.ThreadDatabase
import org.thoughtcrime.securesms.database.model.ThreadRecord
import org.thoughtcrime.securesms.dependencies.ConfigFactory
import org.thoughtcrime.securesms.groups.OpenGroupManager
import org.thoughtcrime.securesms.home.search.GlobalSearchAdapter
import org.thoughtcrime.securesms.home.search.GlobalSearchInputLayout
import org.thoughtcrime.securesms.home.search.GlobalSearchResult
import org.thoughtcrime.securesms.home.search.GlobalSearchViewModel
import org.thoughtcrime.securesms.home.search.SearchContactActionBottomSheet
import org.thoughtcrime.securesms.messagerequests.MessageRequestsActivity
import org.thoughtcrime.securesms.permissions.Permissions
import org.thoughtcrime.securesms.preferences.SettingsActivity
import org.thoughtcrime.securesms.preferences.prosettings.ProSettingsActivity
import org.thoughtcrime.securesms.pro.ProStatusManager
import org.thoughtcrime.securesms.recoverypassword.RecoveryPasswordActivity
import org.thoughtcrime.securesms.reviews.StoreReviewManager
import org.thoughtcrime.securesms.reviews.ui.InAppReview
import org.thoughtcrime.securesms.reviews.ui.InAppReviewViewModel
import org.thoughtcrime.securesms.showSessionDialog
import org.thoughtcrime.securesms.tokenpage.TokenPageNotificationManager
import org.thoughtcrime.securesms.ui.PathDot
import org.thoughtcrime.securesms.ui.components.Avatar
import org.thoughtcrime.securesms.ui.requestDozeWhitelist
import org.thoughtcrime.securesms.ui.setThemedContent
import org.thoughtcrime.securesms.ui.theme.LocalColors
import org.thoughtcrime.securesms.ui.theme.LocalDimensions
import org.thoughtcrime.securesms.ui.theme.primaryGreen
import org.thoughtcrime.securesms.util.AvatarBadge
import org.thoughtcrime.securesms.util.AvatarUtils
import org.thoughtcrime.securesms.util.DateUtils
import org.thoughtcrime.securesms.util.applyBottomInsetMargin
import org.thoughtcrime.securesms.util.applySafeInsetsPaddings
import org.thoughtcrime.securesms.util.disableClipping
import org.thoughtcrime.securesms.util.fadeIn
import org.thoughtcrime.securesms.util.fadeOut
import org.thoughtcrime.securesms.util.push
import org.thoughtcrime.securesms.util.show
import org.thoughtcrime.securesms.util.start
import org.thoughtcrime.securesms.webrtc.WebRtcCallActivity
import javax.inject.Inject
// Intent extra keys so we know where we came from
private const val NEW_ACCOUNT = "HomeActivity_NEW_ACCOUNT"
private const val FROM_ONBOARDING = "HomeActivity_FROM_ONBOARDING"
@AndroidEntryPoint
class HomeActivity : ScreenLockActionBarActivity(),
ConversationClickListener,
GlobalSearchInputLayout.GlobalSearchInputLayoutListener,
SearchContactActionBottomSheet.Callbacks{
private val TAG = "HomeActivity"
private lateinit var binding: ActivityHomeBinding
private lateinit var glide: RequestManager
@Inject lateinit var threadDb: ThreadDatabase
@Inject lateinit var mmsSmsDatabase: MmsSmsDatabase
@Inject lateinit var storage: Storage
@Inject lateinit var groupDatabase: GroupDatabase
@Inject lateinit var textSecurePreferences: TextSecurePreferences
@Inject lateinit var configFactory: ConfigFactory
@Inject lateinit var tokenPageNotificationManager: TokenPageNotificationManager
@Inject lateinit var groupManagerV2: GroupManagerV2
@Inject lateinit var deprecationManager: LegacyGroupDeprecationManager
@Inject lateinit var clock: SnodeClock
@Inject lateinit var messageNotifier: MessageNotifier
@Inject lateinit var dateUtils: DateUtils
@Inject lateinit var openGroupManager: OpenGroupManager
@Inject lateinit var storeReviewManager: StoreReviewManager
@Inject lateinit var proStatusManager: ProStatusManager
@Inject lateinit var recipientRepository: RecipientRepository
@Inject lateinit var avatarUtils: AvatarUtils
@Inject lateinit var loginStateRepository: LoginStateRepository
@Inject lateinit var messageFormatter: MessageFormatter
@Inject lateinit var pathManager: PathManager
private val globalSearchViewModel by viewModels<GlobalSearchViewModel>()
private val homeViewModel by viewModels<HomeViewModel>()
private val inAppReviewViewModel by viewModels<InAppReviewViewModel>()
private val publicKey: String by lazy { loginStateRepository.requireLocalNumber() }
private val homeAdapter: HomeAdapter by lazy {
HomeAdapter(
context = this,
messageFormatter = messageFormatter,
listener = this,
showMessageRequests = ::showMessageRequests,
hideMessageRequests = ::hideMessageRequests,
)
}
private val globalSearchAdapter by lazy {
GlobalSearchAdapter(
dateUtils = dateUtils,
onContactClicked = { model ->
val intent = when (model) {
is GlobalSearchAdapter.Model.Message -> ConversationActivityV2
.createIntent(
this,
address = model.messageResult.conversationRecipient.address as Address.Conversable,
scrollToMessage = model.messageResult.sentTimestampMs to model.messageResult.messageRecipient.address
)
is GlobalSearchAdapter.Model.SavedMessages -> ConversationActivityV2
.createIntent(
this,
address = Address.fromSerialized(model.currentUserPublicKey) as Address.Conversable
)
is GlobalSearchAdapter.Model.Contact -> ConversationActivityV2
.createIntent(
this,
address = model.contact
)
is GlobalSearchAdapter.Model.GroupConversation -> ConversationActivityV2
.createIntent(
this,
address = model.address
)
else -> {
Log.d("Loki", "callback with model: $model")
return@GlobalSearchAdapter
}
}
push(intent)
},
onContactLongPressed = { model ->
onSearchContactLongPress(model.contact, model.name)
}
)
}
private fun onSearchContactLongPress(address: Address, contactName: String) {
val bottomSheet = SearchContactActionBottomSheet.newInstance(address, contactName)
bottomSheet.show(supportFragmentManager, bottomSheet.tag)
}
private val isFromOnboarding: Boolean get() = intent.getBooleanExtra(FROM_ONBOARDING, false)
private val isNewAccount: Boolean get() = intent.getBooleanExtra(NEW_ACCOUNT, false)
override val applyDefaultWindowInsets: Boolean
get() = false
// region Lifecycle
override fun onCreate(savedInstanceState: Bundle?, ready: Boolean) {
super.onCreate(savedInstanceState, ready)
// Set content view
binding = ActivityHomeBinding.inflate(layoutInflater)
setContentView(binding.root)
// Set custom toolbar
setSupportActionBar(binding.toolbar)
// Set up Glide
glide = Glide.with(this)
// Set up toolbar buttons
binding.profileButton.setThemedContent {
val recipient by recipientRepository.observeSelf()
.collectAsState(null)
val pathStatus by pathManager.status.collectAsState()
Avatar(
size = LocalDimensions.current.iconMediumAvatar,
data = avatarUtils.getUIDataFromRecipient(recipient),
modifier = Modifier.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = ::openSettings
),
badge = AvatarBadge.ComposeBadge(
content = {
val glowSize = LocalDimensions.current.xxxsSpacing
Crossfade(
targetState = when (pathStatus){
PathStatus.BUILDING -> LocalColors.current.warning
PathStatus.ERROR -> LocalColors.current.danger
else -> primaryGreen
}, label = "path") {
PathDot(
modifier = Modifier.offset(glowSize*0.5f, glowSize*0.5f),
dotSize = LocalDimensions.current.xxsSpacing,
glowSize = glowSize,
color = it
)
}
}
)
)
}
binding.searchViewContainer.setOnClickListener {
homeViewModel.onSearchClicked()
}
binding.sessionToolbar.disableClipping()
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
val searchHandled = homeViewModel.isSearchOpen.value &&
binding.globalSearchInputLayout.handleBackPressed()
if (searchHandled) return
if (homeViewModel.onBackPressed()) {
return
}
finish()
}
})
lifecycleScope.launch {
homeViewModel.shouldShowCurrentUserProBadge
.collectLatest {
binding.sessionHeaderProBadge.isVisible = it
}
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
homeViewModel.uiEvents.collect { event ->
when (event) {
is HomeViewModel.UiEvent.OpenProSettings -> {
startActivity(
ProSettingsActivity.createIntent(
this@HomeActivity,
event.start
)
)
}
is HomeViewModel.UiEvent.ShowWhiteListSystemDialog -> {
requestDozeWhitelist()
}
}
}
}
}
// Set up seed reminder view
lifecycleScope.launchWhenStarted {
binding.seedReminderView.setThemedContent {
if (!textSecurePreferences.getHasViewedSeed()) SeedReminder { start<RecoveryPasswordActivity>() }
}
}
// Set up recycler view
binding.globalSearchInputLayout.listener = this
homeAdapter.setHasStableIds(true)
homeAdapter.glide = glide
binding.conversationsRecyclerView.adapter = homeAdapter
binding.globalSearchRecycler.adapter = globalSearchAdapter
binding.configOutdatedView.setOnClickListener {
textSecurePreferences.setHasLegacyConfig(false)
updateLegacyConfigView()
}
// in case a phone call is in progress, this banner is visible and should bring the user back to the call
binding.callInProgress.setOnClickListener {
startActivity(WebRtcCallActivity.getCallActivityIntent(this))
}
// Set up empty state view
binding.emptyStateContainer.setThemedContent {
EmptyView(isNewAccount)
}
// set the compose dialog content
binding.dialogs.apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setThemedContent {
val dialogsState by homeViewModel.dialogsState.collectAsStateWithLifecycle()
HomeDialogs(
dialogsState = dialogsState,
sendCommand = homeViewModel::onCommand
)
}
}
// Set up new conversation button
binding.newConversationButton.setOnClickListener { showStartConversation() }
// subscribe to outdated config updates, this should be removed after long enough time for device migration
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
TextSecurePreferences.events.filter { it == TextSecurePreferences.HAS_RECEIVED_LEGACY_CONFIG }.collect {
updateLegacyConfigView()
}
}
}
// Subscribe to threads and update the UI
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
homeViewModel.data
.filterNotNull() // We don't actually want the null value here as it indicates a loading state (maybe we need a loading state?)
.collectLatest { data ->
val manager = binding.conversationsRecyclerView.layoutManager as LinearLayoutManager
val firstPos = manager.findFirstCompletelyVisibleItemPosition()
val offsetTop = if(firstPos >= 0) {
manager.findViewByPosition(firstPos)?.let { view ->
manager.getDecoratedTop(view) - manager.getTopDecorationHeight(view)
} ?: 0
} else 0
homeAdapter.data = data
if(firstPos >= 0) { manager.scrollToPositionWithOffset(firstPos, offsetTop) }
binding.emptyStateContainer.isVisible = homeAdapter.itemCount == 0
}
}
}
lifecycleScope.launchWhenStarted {
launch(Dispatchers.Default) {
// update things based on TextSecurePrefs (profile info etc)
// Set up remaining components if needed
if (loginStateRepository.getLocalNumber() != null) {
JobQueue.shared.resumePendingJobs()
}
}
// sync view -> viewModel
launch {
binding.globalSearchInputLayout.query()
.collect(globalSearchViewModel::setQuery)
}
// Get group results and display them
launch {
globalSearchViewModel.result.map { result ->
result.query to when {
result.query.isEmpty() -> buildList {
add(GlobalSearchAdapter.Model.Header(R.string.contactContacts))
add(GlobalSearchAdapter.Model.SavedMessages(publicKey))
addAll(result.groupedContacts)
}
else -> buildList {
val conversations = result.contactAndGroupList.toMutableList()
if(result.showNoteToSelf){
conversations.add(GlobalSearchAdapter.Model.SavedMessages(publicKey))
}
conversations.takeUnless { it.isEmpty() }?.let {
add(GlobalSearchAdapter.Model.Header(R.string.sessionConversations))
addAll(it)
}
result.messageResults.takeUnless { it.isEmpty() }?.let {
add(GlobalSearchAdapter.Model.Header(R.string.messages))
addAll(it)
}
}
}
}.collectLatest(globalSearchAdapter::setNewData)
}
}
if (isFromOnboarding) {
if (Build.VERSION.SDK_INT >= 33 &&
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager).areNotificationsEnabled().not()) {
Permissions.with(this)
.request(Manifest.permission.POST_NOTIFICATIONS)
.execute()
}
configFactory.withMutableUserConfigs {
if (!it.userProfile.isBlockCommunityMessageRequestsSet()) {
it.userProfile.setCommunityMessageRequests(false)
}
}
}
// Schedule a notification about the new Token Page for 1 hour after running the updated app for the first time.
// Note: We do NOT schedule a debug notification on startup - but one may be triggered from the Debug Menu.
if (BuildConfig.BUILD_TYPE == "release") {
tokenPageNotificationManager.scheduleTokenPageNotification(constructDebugNotification = false)
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
homeViewModel.callBanner.collect { callBanner ->
when (callBanner) {
null -> binding.callInProgress.fadeOut()
else -> {
binding.callInProgress.text = callBanner
binding.callInProgress.fadeIn()
}
}
}
}
}
// Set up search layout
lifecycleScope.launch {
homeViewModel.isSearchOpen.collect { open ->
setSearchShown(open)
}
}
// Set up in-app review
binding.inAppReviewView.setThemedContent {
InAppReview(
uiStateFlow = inAppReviewViewModel.uiState,
storeReviewManager = storeReviewManager,
sendCommands = inAppReviewViewModel::sendUiCommand,
)
}
rewireConversationOptionsCallbacksIfPresent()
applyViewInsets()
}
override fun onCancelClicked() {
homeViewModel.onCancelSearchClicked()
}
override fun onBlockContact(address: Address) {
if (address is Address.Standard) {
homeViewModel.blockContact(address.address)
}
}
override fun onDeleteContact(address: Address) {
if (address is Address.WithAccountId) {
homeViewModel.deleteContact(address)
}
}
private val GlobalSearchResult.groupedContacts: List<GlobalSearchAdapter.Model> get() {
class NamedValue<T>(val name: String?, val value: T)
// Unknown is temporarily to be grouped together with numbers title - see: SES-2287
val numbersTitle = "#"
val unknownTitle = numbersTitle
return contacts
// Remove ourself, we're shown above.
.filter { it.address.address != publicKey }
// Get the name that we will display and sort by, and uppercase it to
// help with sorting and we need the char uppercased later.
.map { NamedValue(it.displayName().uppercase(), it) }
// Digits are all grouped under a #, the rest are grouped by their first character.uppercased()
// If there is no name, they go under Unknown
.groupBy { it.name?.run { first().takeUnless(Char::isDigit)?.toString() ?: numbersTitle } ?: unknownTitle }
// place the # at the end, after all the names starting with alphabetic chars
.toSortedMap(compareBy {
when (it) {
unknownTitle -> Char.MAX_VALUE
numbersTitle -> Char.MAX_VALUE - 1
else -> it.first()
}
})
// Flatten the map of char to lists into an actual List that can be displayed.
.flatMap { (key, contacts) ->
listOf(
GlobalSearchAdapter.Model.SubHeader(key)
) + contacts.sortedBy { it.name ?: it.value.address.address }
.map {
GlobalSearchAdapter.Model.Contact(
contact = it.value,
isSelf = it.value.isSelf,
showProBadge = it.value.shouldShowProBadge
)
}
}
}
private val GlobalSearchResult.contactAndGroupList: List<GlobalSearchAdapter.Model> get() =
contacts.map { GlobalSearchAdapter.Model.Contact(
contact = it,
isSelf = it.isSelf,
showProBadge = it.shouldShowProBadge
) } +
threads.mapNotNull {
if(it.address is Address.GroupLike)
GlobalSearchAdapter.Model.GroupConversation(it)
else null
}
private val GlobalSearchResult.messageResults: List<GlobalSearchAdapter.Model> get() {
val unreadThreadMap = messages
.map { it.threadId }.toSet()
.associateWith { mmsSmsDatabase.getUnreadCount(it) }
return messages.map {
GlobalSearchAdapter.Model.Message(
messageResult = it,
unread = unreadThreadMap[it.threadId] ?: 0,
isSelf = it.conversationRecipient.isLocalNumber,
showProBadge = it.conversationRecipient.shouldShowProBadge
)
}
}
private fun setSearchShown(isSearchShown: Boolean) {
// Request focus immediately so the user can start typing
if (isSearchShown) {
binding.globalSearchInputLayout.requestFocus()
}
binding.searchToolbar.isVisible = isSearchShown
binding.sessionToolbar.isVisible = !isSearchShown
binding.seedReminderView.isVisible = !TextSecurePreferences.getHasViewedSeed(this) && !isSearchShown
binding.globalSearchRecycler.isVisible = isSearchShown
// Show a fade in animation for the conversation list upon re-appearing
val shouldShowHomeAnimation = !isSearchShown && !binding.conversationListContainer.isVisible
binding.conversationListContainer.isVisible = !isSearchShown
if (shouldShowHomeAnimation) {
binding.conversationListContainer.animate().cancel()
binding.conversationListContainer.alpha = 0f
binding.conversationListContainer.animate().alpha(1f).start()
}
}
private fun updateLegacyConfigView() {
binding.configOutdatedView.isVisible = textSecurePreferences.getHasLegacyConfig()
}
override fun onResume() {
super.onResume()
messageNotifier.setHomeScreenVisible(true)
if (loginStateRepository.getLocalNumber() == null) { return; } // This can be the case after a secondary device is auto-cleared
IdentityKeyUtil.checkUpdate(this)
if (textSecurePreferences.getHasViewedSeed()) {
binding.seedReminderView.isVisible = false
}
updateLegacyConfigView()
}
override fun onPause() {
super.onPause()
messageNotifier.setHomeScreenVisible(false)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults)
}
// endregion
// region Interaction
override fun onConversationClick(thread: ThreadRecord) {
push(ConversationActivityV2.createIntent(this, address = thread.recipient.address as Address.Conversable))
}
override fun onLongConversationClick(thread: ThreadRecord) {
val threadRecipient = thread.recipient
val bottomSheet = ConversationOptionsBottomSheet.newInstance(
publicKey = publicKey,
threadId = thread.threadId,
address = threadRecipient.address.toString()
)
attachConversationOptionsCallbacks(bottomSheet, thread)
bottomSheet.show(supportFragmentManager, ConversationOptionsBottomSheet.FRAGMENT_TAG)
}
/**
* If a ConversationOptionsBottomSheet was restored by FragmentManager after a
* configuration change, re-attach its callbacks and refresh the ThreadRecord.
*/
private fun rewireConversationOptionsCallbacksIfPresent() {
val sheet = supportFragmentManager
.findFragmentByTag(ConversationOptionsBottomSheet.FRAGMENT_TAG)
as? ConversationOptionsBottomSheet ?: return
val threadId = sheet.requireArguments()
.getLong(ConversationOptionsBottomSheet.ARG_THREAD_ID)
val threadRecord = homeViewModel.data.value?.items?.asSequence()
?.filterIsInstance<HomeViewModel.Item.Thread>()
?.firstOrNull { it.thread.threadId == threadId }?.thread
threadRecord?.let {
attachConversationOptionsCallbacks(sheet, it)
}
}
private fun attachConversationOptionsCallbacks(
sheet: ConversationOptionsBottomSheet,
thread: ThreadRecord
) {
val threadRecipient = thread.recipient
sheet.onViewDetailsTapped = {
sheet.dismiss()
homeViewModel.showUserProfileModal(thread)
}
sheet.onCopyConversationId = {
sheet.dismiss()
if (threadRecipient.address is Address.WithAccountId && !threadRecipient.isSelf) {
val clip = ClipData.newPlainText(
"Account ID",
threadRecipient.address.accountId.hexString
)
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(clip)
Toast.makeText(this@HomeActivity, R.string.copied, Toast.LENGTH_SHORT).show()
} else if (threadRecipient.data is RecipientData.Community) {
val clip = ClipData.newPlainText("Community URL", threadRecipient.data.joinURL)
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(clip)
Toast.makeText(this@HomeActivity, R.string.copied, Toast.LENGTH_SHORT).show()
}
}
sheet.onBlockTapped = {
sheet.dismiss()
if (!threadRecipient.blocked) blockConversation(thread)
}
sheet.onUnblockTapped = {
sheet.dismiss()
if (threadRecipient.blocked) unblockConversation(thread)
}
sheet.onAdminLeaveTapped = {
sheet.dismiss()
deleteConversation(thread, false)
}
sheet.onDeleteTapped = {
sheet.dismiss()
deleteConversation(thread, true)
}
sheet.onNotificationTapped = {
sheet.dismiss()
startActivity(Intent(this, NotificationSettingsActivity::class.java).apply {
putExtra(NotificationSettingsActivity.ARG_ADDRESS, threadRecipient.address)
})
}
sheet.onPinTapped = {
sheet.dismiss()
setConversationPinned(threadRecipient.address, true)
}
sheet.onUnpinTapped = {
sheet.dismiss()
setConversationPinned(threadRecipient.address, false)
}
sheet.onMarkAllAsReadTapped = {
sheet.dismiss()
markAllAsRead(thread)
}
sheet.onMarkAsUnreadTapped = {
sheet.dismiss()
markAsUnread(thread)
}
sheet.onDeleteContactTapped = {
sheet.dismiss()
confirmDeleteContact(thread)
}
}
private fun blockConversation(thread: ThreadRecord) {
showSessionDialog {
title(R.string.block)
text(Phrase.from(context, R.string.blockDescription)
.put(NAME_KEY, thread.recipient.displayName())
.format())
dangerButton(R.string.block, R.string.AccessibilityId_blockConfirm) {
lifecycleScope.launch(Dispatchers.Default) {
storage.setBlocked(listOf(thread.recipient.address), true)
withContext(Dispatchers.Main) {
binding.conversationsRecyclerView.adapter!!.notifyDataSetChanged()
}
}
// Block confirmation toast added as per SS-64
val txt = Phrase.from(context, R.string.blockBlockedUser).put(NAME_KEY, thread.recipient.displayName()).format().toString()
Toast.makeText(context, txt, Toast.LENGTH_LONG).show()
}
cancelButton()
}
}
private fun unblockConversation(thread: ThreadRecord) {
showSessionDialog {
title(R.string.blockUnblock)
text(Phrase.from(context, R.string.blockUnblockName).put(NAME_KEY, thread.recipient.displayName()).format())
dangerButton(R.string.blockUnblock, R.string.AccessibilityId_unblockConfirm) {
lifecycleScope.launch(Dispatchers.Default) {
storage.setBlocked(listOf(thread.recipient.address), false)
withContext(Dispatchers.Main) {
binding.conversationsRecyclerView.adapter!!.notifyDataSetChanged()
}
}
}
cancelButton()
}
}
private fun confirmDeleteContact(thread: ThreadRecord) {
showSessionDialog {
title(R.string.contactDelete)
text(
Phrase.from(context, R.string.deleteContactDescription)
.put(NAME_KEY, thread.recipient?.displayName().orEmpty())
.format()
)
dangerButton(R.string.delete, R.string.qa_conversation_settings_dialog_delete_contact_confirm) {
homeViewModel.deleteContact(thread.recipient.address as Address.WithAccountId)
}
cancelButton()
}
}
private fun setConversationPinned(address: Address, pinned: Boolean) {
homeViewModel.setPinned(address, pinned)
}
private fun markAllAsRead(thread: ThreadRecord) {
lifecycleScope.launch(Dispatchers.Default) {
storage.markConversationAsRead(thread.threadId, clock.currentTimeMillis())
}
}
private fun markAsUnread(thread : ThreadRecord){
lifecycleScope.launch(Dispatchers.Default) {
storage.markConversationAsUnread(thread.threadId)
}
}
/**
* @param isAdminDeleteGroup will determine if the group will be deleted by admin
* false : admin will only leave the group (group has > 1 admin)
* true : admin will delete the group (can delete even if > 1 admin)
*/
private fun deleteConversation(thread: ThreadRecord, isAdminDeleteGroup : Boolean) {
val recipient = thread.recipient
if (recipient.address is Address.Group) {
confirmAndLeaveGroup(
dialogData = homeViewModel.getLeaveGroupConfirmationDialog(thread, isAdminDeleteGroup)
) {
homeViewModel.leaveGroup(recipient.address.accountId, isAdminDeleteGroup)
}
return
}
val title: String
val message: CharSequence
var positiveButtonId: Int = R.string.delete
val negativeButtonId: Int = R.string.cancel
// default delete action
val deleteAction: () -> Unit = {
lifecycleScope.launch(Dispatchers.Main) {
val context = this@HomeActivity
// Delete the conversation
when (recipient.address) {
is Address.Community -> {
openGroupManager.delete(recipient.address.serverUrl, recipient.address.room)
}
is Address.Standard -> {
configFactory.withMutableUserConfigs { configs ->
if (recipient.isSelf) {
configs.userProfile.setNtsPriority(PRIORITY_HIDDEN)
} else {
configs.contacts.updateContact(recipient.address) {
priority = PRIORITY_HIDDEN
}
}
}
}
is Address.LegacyGroup -> {
configFactory.withMutableUserConfigs { configs ->
configs.userGroups.eraseLegacyGroup(recipient.address.groupPublicKeyHex)
}
}
is Address.CommunityBlindedId -> {
configFactory.withMutableUserConfigs { configs ->
configs.contacts.eraseBlinded(
communityServerUrl = recipient.address.serverUrl,
blindedId = recipient.address.blindedId.blindedId.hexString
)
}
}
is Address.Blinded,
is Address.Group,
is Address.Unknown -> {
error("Unexpected address to delete")
}
}
// Update the badge count
messageNotifier.updateNotification(context)
// Notify the user
val toastMessage = if (recipient.isGroupOrCommunityRecipient) R.string.groupMemberYouLeft else R.string.conversationsDeleted
Toast.makeText(context, toastMessage, Toast.LENGTH_LONG).show()
}
}
if (recipient.isLegacyGroupRecipient || recipient.isCommunityRecipient) {
positiveButtonId = R.string.leave
// If you are an admin of this group you can delete it
// we do not want admin related messaging once legacy groups are deprecated
val isGroupAdmin = if(deprecationManager.isDeprecated){
false
} else { // prior to the deprecated state, calculate admin rights properly
recipient.currentUserRole.canModerate
}
if (isGroupAdmin) {
title = getString(R.string.groupLeave)
message = Phrase.from(this, R.string.groupLeaveDescriptionAdmin)
.put(GROUP_NAME_KEY, recipient.displayName())
.format()
} else {
// Otherwise this is either a community, or it's a group you're not an admin of
title = if (recipient.isCommunityRecipient) getString(R.string.communityLeave) else getString(R.string.groupLeave)
message = Phrase.from(this.applicationContext, R.string.groupLeaveDescription)
.put(GROUP_NAME_KEY, recipient.displayName())
.format()
}
} else {
// Note to self
if (recipient.isLocalNumber) {
title = getString(R.string.noteToSelfHide)
message = getText(R.string.hideNoteToSelfDescription)
positiveButtonId = R.string.hide
}
else { // If this is a 1-on-1 conversation
title = getString(R.string.conversationsDelete)
message = Phrase.from(this, R.string.deleteConversationDescription)
.put(NAME_KEY, recipient.displayName())
.format()
}
}
showSessionDialog {
title(title)
text(message)
dangerButton(positiveButtonId) {
deleteAction()
}
button(negativeButtonId)
}
}
private fun confirmAndLeaveGroup(
dialogData: GroupManagerV2.ConfirmDialogData?,
doLeave: suspend () -> Unit,
) {
if (dialogData == null) return
showSessionDialog {
title(dialogData.title)
text(dialogData.message)
dangerButton(
dialogData.positiveText,
contentDescriptionRes = dialogData.positiveQaTag ?: dialogData.positiveText
) {
GlobalScope.launch(Dispatchers.Default) {
doLeave()
}
}
button(
dialogData.negativeText,
contentDescriptionRes = dialogData.negativeQaTag ?: dialogData.negativeText
)
}
}
private fun openSettings() {
val intent = Intent(this, SettingsActivity::class.java)
show(intent, isForResult = true)
}
private fun showMessageRequests() {
val intent = Intent(this, MessageRequestsActivity::class.java)
push(intent)
}
private fun hideMessageRequests() {
showSessionDialog {
text(getString(R.string.hide))
button(R.string.yes) {
textSecurePreferences.setHasHiddenMessageRequests(true)
homeViewModel.tryReload()
}
button(R.string.no)
}
}
private fun showStartConversation() {
homeViewModel.onCommand(HomeViewModel.Commands.ShowStartConversationSheet)
}
private fun applyViewInsets() {
binding.root.applySafeInsetsPaddings(
applyBottom = false,
consumeInsets = false,
alsoApply = { insets ->
binding.globalSearchRecycler.updatePadding(bottom = insets.bottom)
}
)
binding.newConversationButton.applyBottomInsetMargin(
typeMask = WindowInsetsCompat.Type.navigationBars(),
extraBottom = resources.getDimensionPixelSize(R.dimen.new_conversation_button_bottom_offset)
)
}
}
fun Context.startHomeActivity(isFromOnboarding: Boolean, isNewAccount: Boolean) {
Intent(this, HomeActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
putExtra(NEW_ACCOUNT, isNewAccount)
putExtra(FROM_ONBOARDING, isFromOnboarding)
}.also(::startActivity)
}