-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMainActivity.kt
554 lines (472 loc) · 21 KB
/
MainActivity.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
/*
* Infomaniak Mail - Android
* Copyright (C) 2022-2024 Infomaniak Network SA
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.infomaniak.mail.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import androidx.activity.addCallback
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.activity.viewModels
import androidx.annotation.FloatRange
import androidx.core.view.isVisible
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Lifecycle.State
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.NavDestination
import androidx.navigation.fragment.NavHostFragment
import androidx.work.Data
import com.infomaniak.lib.core.MatomoCore.TrackerAction
import com.infomaniak.lib.core.networking.LiveDataNetworkStatus
import com.infomaniak.lib.core.utils.*
import com.infomaniak.lib.core.utils.Utils
import com.infomaniak.lib.core.utils.Utils.toEnumOrThrow
import com.infomaniak.lib.core.utils.UtilsUi.openUrl
import com.infomaniak.lib.stores.StoreUtils
import com.infomaniak.lib.stores.StoreUtils.checkUpdateIsRequired
import com.infomaniak.lib.stores.StoreUtils.launchInAppReview
import com.infomaniak.lib.stores.updatemanagers.InAppUpdateManager
import com.infomaniak.mail.BuildConfig
import com.infomaniak.mail.MatomoMail
import com.infomaniak.mail.MatomoMail.trackAppReviewEvent
import com.infomaniak.mail.MatomoMail.trackDestination
import com.infomaniak.mail.MatomoMail.trackEasterEggEvent
import com.infomaniak.mail.MatomoMail.trackEvent
import com.infomaniak.mail.MatomoMail.trackInAppUpdateEvent
import com.infomaniak.mail.MatomoMail.trackMenuDrawerEvent
import com.infomaniak.mail.R
import com.infomaniak.mail.data.LocalSettings
import com.infomaniak.mail.data.models.draft.Draft.DraftAction
import com.infomaniak.mail.databinding.ActivityMainBinding
import com.infomaniak.mail.firebase.RegisterFirebaseBroadcastReceiver
import com.infomaniak.mail.ui.alertDialogs.DescriptionAlertDialog
import com.infomaniak.mail.ui.alertDialogs.TitleAlertDialog
import com.infomaniak.mail.ui.main.SnackbarManager
import com.infomaniak.mail.ui.main.folder.TwoPaneFragment
import com.infomaniak.mail.ui.main.menu.MenuDrawerFragment
import com.infomaniak.mail.ui.main.onboarding.PermissionsOnboardingPagerFragment
import com.infomaniak.mail.ui.newMessage.NewMessageActivity
import com.infomaniak.mail.ui.sync.SyncAutoConfigActivity
import com.infomaniak.mail.utils.*
import com.infomaniak.mail.utils.UiUtils.progressivelyColorSystemBars
import com.infomaniak.mail.utils.extensions.isUserAlreadySynchronized
import com.infomaniak.mail.workers.DraftsActionsWorker
import dagger.hilt.android.AndroidEntryPoint
import io.sentry.Breadcrumb
import io.sentry.Sentry
import io.sentry.SentryLevel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.Date
import java.util.UUID
import javax.inject.Inject
import com.infomaniak.lib.core.R as RCore
@AndroidEntryPoint
class MainActivity : BaseActivity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
private val mainViewModel: MainViewModel by viewModels()
private val backgroundColor: Int by lazy { getColor(R.color.backgroundColor) }
private val backgroundHeaderColor: Int by lazy { getColor(R.color.backgroundHeaderColor) }
private val menuDrawerBackgroundColor: Int by lazy { getColor(R.color.menuDrawerBackgroundColor) }
private val registerFirebaseBroadcastReceiver by lazy { RegisterFirebaseBroadcastReceiver() }
private var previousDestinationId: Int? = null
private val navController by lazy {
(supportFragmentManager.findFragmentById(R.id.mainHostFragment) as NavHostFragment).navController
}
private val showSendingSnackbarTimer: CountDownTimer by lazy {
Utils.createRefreshTimer(1_000L) { snackbarManager.setValue(getString(R.string.snackbarEmailSending)) }
}
private val newMessageActivityResultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
val draftAction = result.data?.getStringExtra(DRAFT_ACTION_KEY)?.let(DraftAction::valueOf)
if (draftAction == DraftAction.SEND) {
showEasterXMas()
showSendingSnackbarTimer.start()
showAppReview()
}
}
private val syncAutoConfigActivityResultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
result.data?.getStringExtra(SYNC_AUTO_CONFIG_KEY)?.let { reason ->
if (reason == SYNC_AUTO_CONFIG_ALREADY_SYNC) {
snackbarManager.setValue(getString(R.string.errorUserAlreadySynchronized))
}
navController.popBackStack(destinationId = R.id.threadListFragment, inclusive = false)
}
}
private val currentFragment
get() = supportFragmentManager
.findFragmentById(R.id.mainHostFragment)
?.childFragmentManager
?.primaryNavigationFragment
@Inject
lateinit var draftsActionsWorkerScheduler: DraftsActionsWorker.Scheduler
@Inject
lateinit var playServicesUtils: PlayServicesUtils
@Inject
lateinit var descriptionDialog: DescriptionAlertDialog
@Inject
lateinit var titleDialog: TitleAlertDialog
@Inject
lateinit var permissionUtils: PermissionUtils
@Inject
lateinit var snackbarManager: SnackbarManager
@Inject
lateinit var inAppUpdateManager: InAppUpdateManager
private val drawerListener = object : DrawerLayout.DrawerListener {
var hasDragged = false
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
colorSystemBarsWithMenuDrawer(slideOffset)
}
override fun onDrawerOpened(drawerView: View) {
if (hasDragged) trackMenuDrawerEvent("openByGesture", TrackerAction.DRAG)
colorSystemBarsWithMenuDrawer(UiUtils.FULLY_SLID)
binding.menuDrawerFragmentContainer.getFragment<MenuDrawerFragment?>()?.onDrawerOpened()
}
override fun onDrawerClosed(drawerView: View) {
if (hasDragged) trackMenuDrawerEvent("closeByGesture", TrackerAction.DRAG)
binding.menuDrawerFragmentContainer.getFragment<MenuDrawerFragment?>()?.closeDropdowns()
}
override fun onDrawerStateChanged(newState: Int) {
when (newState) {
DrawerLayout.STATE_DRAGGING -> hasDragged = true
DrawerLayout.STATE_IDLE -> hasDragged = false
else -> Unit
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG)
setContentView(binding.root)
handleOnBackPressed()
registerMainPermissions()
checkUpdateIsRequired(
BuildConfig.APPLICATION_ID,
BuildConfig.VERSION_NAME,
BuildConfig.VERSION_CODE,
localSettings.accentColor.theme,
)
observeNetworkStatus()
observeDeletedMessages()
observeDeleteThreadTrigger()
observeDraftWorkerResults()
binding.drawerLayout.addDrawerListener(drawerListener)
registerFirebaseBroadcastReceiver.initFirebaseBroadcastReceiver(this, mainViewModel)
setupSnackbar()
setupNavController()
setupMenuDrawerCallbacks()
mainViewModel.updateUserInfo()
loadCurrentMailbox()
managePermissionsRequesting()
initAppUpdateManager()
}
private fun observeNetworkStatus() {
LiveDataNetworkStatus(context = this).distinctUntilChanged().observe(this) { isAvailable ->
SentryLog.d("Internet availability", if (isAvailable) "Available" else "Unavailable")
Sentry.addBreadcrumb(Breadcrumb().apply {
category = "Network"
message = "Internet access is available : $isAvailable"
level = if (isAvailable) SentryLevel.INFO else SentryLevel.WARNING
})
mainViewModel.isInternetAvailable.value = isAvailable
}
}
private fun observeDeletedMessages() = with(mainViewModel) {
deletedMessages.observe(owner = this@MainActivity) {
if (it.isNotEmpty()) {
handleDeletedMessages(it)
deletedMessages.value = emptySet()
}
}
}
private fun observeDeleteThreadTrigger() {
mainViewModel.deleteThreadOrMessageTrigger.observe(this) { descriptionDialog.resetLoadingAndDismiss() }
}
private fun observeDraftWorkerResults() {
WorkerUtils.flushWorkersBefore(context = this, lifecycleOwner = this) {
val treatedWorkInfoUuids = mutableSetOf<UUID>()
draftsActionsWorkerScheduler.getCompletedWorkInfoLiveData().observe(this) {
it.forEach { workInfo ->
if (!treatedWorkInfoUuids.add(workInfo.id)) return@forEach
with(workInfo.outputData) {
refreshDraftFolderIfNeeded()
displayCompletedDraftWorkerResults()
}
}
}
val treatedFailedWorkInfoUuids = mutableSetOf<UUID>()
draftsActionsWorkerScheduler.getFailedWorkInfoLiveData().observe(this) {
it.forEach { workInfo ->
if (!treatedFailedWorkInfoUuids.add(workInfo.id)) return@forEach
with(workInfo.outputData) {
refreshDraftFolderIfNeeded()
val errorRes = getInt(DraftsActionsWorker.ERROR_MESSAGE_RESID_KEY, 0)
if (errorRes > 0) {
showSendingSnackbarTimer.cancel()
snackbarManager.setValue(getString(errorRes))
}
}
}
}
}
}
private fun Data.displayCompletedDraftWorkerResults() {
getString(DraftsActionsWorker.RESULT_DRAFT_ACTION_KEY)?.let { draftAction ->
when (draftAction.toEnumOrThrow<DraftAction>()) {
DraftAction.SAVE -> {
val associatedMailboxUuid = getString(DraftsActionsWorker.ASSOCIATED_MAILBOX_UUID_KEY)
val remoteDraftUuid = getString(DraftsActionsWorker.REMOTE_DRAFT_UUID_KEY)
if (associatedMailboxUuid != null && remoteDraftUuid != null) {
showSavedDraftSnackbar(associatedMailboxUuid, remoteDraftUuid)
}
}
DraftAction.SEND -> showSentDraftSnackbar()
}
}
}
private fun Data.refreshDraftFolderIfNeeded() {
val userId = getInt(DraftsActionsWorker.RESULT_USER_ID_KEY, 0)
if (userId != AccountUtils.currentUserId) return
getLong(DraftsActionsWorker.BIGGEST_SCHEDULED_DATE_KEY, 0).takeIf { it > 0 }?.let { scheduledDate ->
mainViewModel.refreshDraftFolderWhenDraftArrives(scheduledDate)
}
}
private fun showSavedDraftSnackbar(associatedMailboxUuid: String, remoteDraftUuid: String) {
snackbarManager.setValue(
title = getString(R.string.snackbarDraftSaved),
buttonTitle = R.string.actionDelete,
customBehavior = {
trackEvent("snackbar", "deleteDraft")
mainViewModel.deleteDraft(associatedMailboxUuid, remoteDraftUuid)
},
)
}
// Still display the Snackbar even if it took three times 10 seconds of timeout to succeed
private fun showSentDraftSnackbar() {
showSendingSnackbarTimer.cancel()
snackbarManager.setValue(getString(R.string.snackbarEmailSent))
}
private fun loadCurrentMailbox() {
mainViewModel.loadCurrentMailboxFromLocal().observe(this) {
lifecycleScope.launch {
repeatOnLifecycle(State.STARTED) {
mainViewModel.refreshEverything()
}
}
scheduleDraftActionsWorkWithDelay()
}
}
/**
* We want to scheduleWork after a delay in the off chance where we came back from NewMessageActivity while an Activity
* recreation got triggered.
*
* We need to give time to the NewMessageActivity to save the last state of the draft in Realm and then scheduleWork on its
* own. Not waiting would scheduleWork before NewMessageActivity has time to write to Realm and schedule its own worker. This
* would result in an attempt to save any temporary Draft saved to Realm because of saveDraftDebouncing() effectively sending
* a second unwanted Draft.
*/
private fun scheduleDraftActionsWorkWithDelay() = lifecycleScope.launch(Dispatchers.IO) {
delay(1_000L)
draftsActionsWorkerScheduler.scheduleWork()
}
override fun onStart() {
super.onStart()
localSettings.apply {
appLaunches++
appReviewLaunches--
}
showSyncDiscovery()
}
override fun onResume() {
super.onResume()
playServicesUtils.checkPlayServices(this)
if (binding.drawerLayout.isOpen) colorSystemBarsWithMenuDrawer(UiUtils.FULLY_SLID)
}
private fun handleOnBackPressed() = with(binding) {
fun closeDrawer() {
menuDrawerFragmentContainer.getFragment<MenuDrawerFragment?>()?.closeDrawer()
}
fun closeMultiSelect() {
mainViewModel.isMultiSelectOn = false
}
fun popBack() {
when (val fragment = currentFragment) {
is TwoPaneFragment -> fragment.handleOnBackPressed()
is PermissionsOnboardingPagerFragment -> fragment.leaveOnboarding()
else -> navController.popBackStack()
}
}
onBackPressedDispatcher.addCallback(this@MainActivity) {
when {
drawerLayout.isOpen -> closeDrawer()
mainViewModel.isMultiSelectOn -> closeMultiSelect()
else -> popBack()
}
}
}
override fun onStop() {
descriptionDialog.resetLoadingAndDismiss()
super.onStop()
}
override fun onDestroy() {
binding.drawerLayout.removeDrawerListener(drawerListener)
super.onDestroy()
}
private fun setupSnackbar() {
fun getAnchor(): View? {
val fragment = currentFragment
return if (fragment is TwoPaneFragment) fragment.getAnchor() else null
}
snackbarManager.setup(
view = binding.root,
activity = this,
getAnchor = ::getAnchor,
onUndoData = {
trackEvent("snackbar", "undo")
mainViewModel.undoAction(it)
},
)
}
private fun setupNavController() {
navController.addOnDestinationChangedListener { _, destination, arguments ->
onDestinationChanged(destination, arguments)
}
}
private fun setupMenuDrawerCallbacks() = with(binding) {
menuDrawerFragmentContainer.getFragment<MenuDrawerFragment?>()?.exitDrawer = { drawerLayout.close() }
}
private fun registerMainPermissions() {
permissionUtils.registerMainPermissions { permissionsResults ->
if (permissionsResults[PermissionUtils.READ_CONTACTS_PERMISSION] == true) mainViewModel.updateUserInfo()
}
}
// This `SuppressLint` seems useless, but it's for the CI. Don't remove it.
@SuppressLint("RestrictedApi")
private fun onDestinationChanged(destination: NavDestination, arguments: Bundle?) {
SentryDebug.addNavigationBreadcrumb(destination.displayName, arguments)
trackDestination(destination)
setDrawerLockMode(isLocked = destination.id != R.id.threadListFragment)
previousDestinationId = destination.id
}
fun setDrawerLockMode(isLocked: Boolean) {
val drawerLockMode = if (isLocked) DrawerLayout.LOCK_MODE_LOCKED_CLOSED else DrawerLayout.LOCK_MODE_UNLOCKED
binding.drawerLayout.setDrawerLockMode(drawerLockMode)
}
private fun colorSystemBarsWithMenuDrawer(@FloatRange(0.0, 1.0) slideOffset: Float) {
window.progressivelyColorSystemBars(
slideOffset = slideOffset,
statusBarColorFrom = backgroundHeaderColor,
statusBarColorTo = menuDrawerBackgroundColor,
navBarColorFrom = backgroundColor,
navBarColorTo = menuDrawerBackgroundColor,
)
}
private fun managePermissionsRequesting() {
if (hasPermissions(PermissionUtils.getMainPermissions(mustRequireNotification = true))) return
if (localSettings.showPermissionsOnboarding) {
if (currentFragment !is PermissionsOnboardingPagerFragment) {
navController.navigate(R.id.permissionsOnboardingPagerFragment)
}
} else {
permissionUtils.requestMainPermissionsIfNeeded()
}
}
private fun initAppUpdateManager() {
inAppUpdateManager.init(
onUserChoice = { isWantingUpdate ->
trackInAppUpdateEvent(if (isWantingUpdate) MatomoMail.DISCOVER_NOW else MatomoMail.DISCOVER_LATER)
},
onInstallStart = { trackInAppUpdateEvent("installUpdate") },
onInstallFailure = {
Sentry.captureException(it)
snackbarManager.setValue(getString(RCore.string.errorUpdateInstall))
},
onInAppUpdateUiChange = { isUpdateDownloaded ->
SentryLog.d(StoreUtils.APP_UPDATE_TAG, "Must display update button : $isUpdateDownloaded")
mainViewModel.canInstallUpdate.value = isUpdateDownloaded
},
onFDroidResult = { updateIsAvailable ->
if (updateIsAvailable) navController.navigate(R.id.updateAvailableBottomSheetDialog)
},
)
}
private fun showSyncDiscovery() = with(localSettings) {
if (!showPermissionsOnboarding && showSyncDiscoveryBottomSheet && appLaunches > 1 && !isUserAlreadySynchronized()) {
showSyncDiscoveryBottomSheet = false
navController.navigate(R.id.syncDiscoveryBottomSheetDialog)
}
}
private fun showAppReview() = with(localSettings) {
if (showAppReviewDialog && appReviewLaunches < 0) {
appReviewLaunches = LocalSettings.DEFAULT_APP_REVIEW_LAUNCHES
trackAppReviewEvent("presentAlert", TrackerAction.DATA)
titleDialog.show(
title = R.string.reviewAlertTitle,
onPositiveButtonClicked = {
trackAppReviewEvent("like")
showAppReviewDialog = false
launchInAppReview()
},
onNegativeButtonClicked = {
trackAppReviewEvent("dislike")
openUrl(getString(R.string.urlUserReportAndroid))
},
)
}
}
private fun showEasterXMas() {
val calendar = Calendar.getInstance()
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
if (month == Calendar.DECEMBER && day <= 25) {
binding.easterEggXMas.apply {
isVisible = true
playAnimation()
}
Sentry.withScope { scope ->
scope.level = SentryLevel.INFO
Sentry.captureMessage("Easter egg XMas has been triggered! Woohoo!")
}
trackEasterEggEvent("xmas${Date().year()}")
}
}
fun navigateToNewMessageActivity(args: Bundle? = null) {
val intent = Intent(this, NewMessageActivity::class.java)
args?.let(intent::putExtras)
newMessageActivityResultLauncher.launch(intent)
}
fun navigateToSyncAutoConfigActivity() {
syncAutoConfigActivityResultLauncher.launch(Intent(this, SyncAutoConfigActivity::class.java))
}
fun openDrawerLayout() {
binding.drawerLayout.open()
}
fun getConfettiContainer(): ViewGroup = binding.easterEggConfettiContainer
companion object {
const val DRAFT_ACTION_KEY = "draftAction"
const val SYNC_AUTO_CONFIG_KEY = "syncAutoConfigKey"
const val SYNC_AUTO_CONFIG_SUCCESS = "syncAutoConfigSuccess"
const val SYNC_AUTO_CONFIG_ALREADY_SYNC = "syncAutoConfigAlreadySync"
}
}