Inject constructor of `BackgroundSyncStarter` and `FcmHelper`

This commit is contained in:
Benoit Marty 2022-06-08 17:04:26 +02:00 committed by Benoit Marty
parent 3c72ee6e0c
commit 5846ad5768
10 changed files with 59 additions and 63 deletions

View File

@ -23,14 +23,14 @@ import im.vector.app.fdroid.receiver.AlarmSyncBroadcastReceiver
import im.vector.app.features.settings.BackgroundSyncMode import im.vector.app.features.settings.BackgroundSyncMode
import im.vector.app.features.settings.VectorPreferences import im.vector.app.features.settings.VectorPreferences
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
object BackgroundSyncStarter { class BackgroundSyncStarter @Inject constructor(
fun start( private val context: Context,
context: Context, private val vectorPreferences: VectorPreferences,
vectorPreferences: VectorPreferences, private val clock: Clock
activeSessionHolder: ActiveSessionHolder, ) {
clock: Clock fun start(activeSessionHolder: ActiveSessionHolder) {
) {
if (vectorPreferences.areNotificationEnabledForDevice()) { if (vectorPreferences.areNotificationEnabledForDevice()) {
val activeSession = activeSessionHolder.getSafeActiveSession() ?: return val activeSession = activeSessionHolder.getSafeActiveSession() ?: return
when (vectorPreferences.getFdroidSyncBackgroundMode()) { when (vectorPreferences.getFdroidSyncBackgroundMode()) {

View File

@ -20,20 +20,20 @@ package im.vector.app.fdroid.receiver
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import im.vector.app.core.extensions.singletonEntryPoint import dagger.hilt.android.AndroidEntryPoint
import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.fdroid.BackgroundSyncStarter import im.vector.app.fdroid.BackgroundSyncStarter
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint
class OnApplicationUpgradeOrRebootReceiver : BroadcastReceiver() { class OnApplicationUpgradeOrRebootReceiver : BroadcastReceiver() {
@Inject lateinit var activeSessionHolder: ActiveSessionHolder
@Inject lateinit var backgroundSyncStarter: BackgroundSyncStarter
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
Timber.v("## onReceive() ${intent.action}") Timber.v("## onReceive() ${intent.action}")
val singletonEntryPoint = context.singletonEntryPoint() backgroundSyncStarter.start(activeSessionHolder)
BackgroundSyncStarter.start(
context,
singletonEntryPoint.vectorPreferences(),
singletonEntryPoint.activeSessionHolder(),
singletonEntryPoint.clock()
)
} }
} }

View File

@ -21,15 +21,17 @@ import android.app.Activity
import android.content.Context import android.content.Context
import im.vector.app.core.di.ActiveSessionHolder import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.core.pushers.PushersManager import im.vector.app.core.pushers.PushersManager
import im.vector.app.core.time.Clock
import im.vector.app.fdroid.BackgroundSyncStarter import im.vector.app.fdroid.BackgroundSyncStarter
import im.vector.app.fdroid.receiver.AlarmSyncBroadcastReceiver import im.vector.app.fdroid.receiver.AlarmSyncBroadcastReceiver
import im.vector.app.features.settings.VectorPreferences import javax.inject.Inject
/** /**
* This class has an alter ego in the gplay variant. * This class has an alter ego in the gplay variant.
*/ */
object FcmHelper { class FcmHelper @Inject constructor(
private val context: Context,
private val backgroundSyncStarter: BackgroundSyncStarter,
) {
fun isFirebaseAvailable(): Boolean = false fun isFirebaseAvailable(): Boolean = false
@ -38,17 +40,16 @@ object FcmHelper {
* *
* @return the FCM token or null if not received from FCM * @return the FCM token or null if not received from FCM
*/ */
fun getFcmToken(context: Context): String? { fun getFcmToken(): String? {
return null return null
} }
/** /**
* Store FCM token to the SharedPrefs * Store FCM token to the SharedPrefs
* *
* @param context android context
* @param token the token to store * @param token the token to store
*/ */
fun storeFcmToken(context: Context, token: String?) { fun storeFcmToken(token: String?) {
// No op // No op
} }
@ -61,18 +62,13 @@ object FcmHelper {
// No op // No op
} }
fun onEnterForeground(context: Context, activeSessionHolder: ActiveSessionHolder) { fun onEnterForeground(activeSessionHolder: ActiveSessionHolder) {
// try to stop all regardless of background mode // try to stop all regardless of background mode
activeSessionHolder.getSafeActiveSession()?.syncService()?.stopAnyBackgroundSync() activeSessionHolder.getSafeActiveSession()?.syncService()?.stopAnyBackgroundSync()
AlarmSyncBroadcastReceiver.cancelAlarm(context) AlarmSyncBroadcastReceiver.cancelAlarm(context)
} }
fun onEnterBackground( fun onEnterBackground(activeSessionHolder: ActiveSessionHolder) {
context: Context, backgroundSyncStarter.start(activeSessionHolder)
vectorPreferences: VectorPreferences,
activeSessionHolder: ActiveSessionHolder,
clock: Clock
) {
BackgroundSyncStarter.start(context, vectorPreferences, activeSessionHolder, clock)
} }
} }

View File

@ -32,7 +32,8 @@ import javax.inject.Inject
*/ */
class TestFirebaseToken @Inject constructor( class TestFirebaseToken @Inject constructor(
private val context: FragmentActivity, private val context: FragmentActivity,
private val stringProvider: StringProvider private val stringProvider: StringProvider,
private val fcmHelper: FcmHelper,
) : TroubleshootTest(R.string.settings_troubleshoot_test_fcm_title) { ) : TroubleshootTest(R.string.settings_troubleshoot_test_fcm_title) {
override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
@ -68,7 +69,7 @@ class TestFirebaseToken @Inject constructor(
description = stringProvider.getString(R.string.settings_troubleshoot_test_fcm_success, tok) description = stringProvider.getString(R.string.settings_troubleshoot_test_fcm_success, tok)
Timber.e("Retrieved FCM token success [$tok].") Timber.e("Retrieved FCM token success [$tok].")
// Ensure it is well store in our local storage // Ensure it is well store in our local storage
FcmHelper.storeFcmToken(context, token) fcmHelper.storeFcmToken(token)
} }
status = TestStatus.SUCCESS status = TestStatus.SUCCESS
} }

View File

@ -37,13 +37,14 @@ class TestTokenRegistration @Inject constructor(
private val context: FragmentActivity, private val context: FragmentActivity,
private val stringProvider: StringProvider, private val stringProvider: StringProvider,
private val pushersManager: PushersManager, private val pushersManager: PushersManager,
private val activeSessionHolder: ActiveSessionHolder private val activeSessionHolder: ActiveSessionHolder,
private val fcmHelper: FcmHelper,
) : ) :
TroubleshootTest(R.string.settings_troubleshoot_test_token_registration_title) { TroubleshootTest(R.string.settings_troubleshoot_test_token_registration_title) {
override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
// Check if we have a registered pusher for this token // Check if we have a registered pusher for this token
val fcmToken = FcmHelper.getFcmToken(context) ?: run { val fcmToken = fcmHelper.getFcmToken() ?: run {
status = TestStatus.FAILED status = TestStatus.FAILED
return return
} }

View File

@ -26,16 +26,21 @@ import im.vector.app.R
import im.vector.app.core.di.ActiveSessionHolder import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.core.di.DefaultSharedPreferences import im.vector.app.core.di.DefaultSharedPreferences
import im.vector.app.core.pushers.PushersManager import im.vector.app.core.pushers.PushersManager
import im.vector.app.core.time.Clock
import im.vector.app.features.settings.VectorPreferences
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject
/** /**
* This class store the FCM token in SharedPrefs and ensure this token is retrieved. * This class store the FCM token in SharedPrefs and ensure this token is retrieved.
* It has an alter ego in the fdroid variant. * It has an alter ego in the fdroid variant.
*/ */
object FcmHelper { class FcmHelper @Inject constructor(
private val PREFS_KEY_FCM_TOKEN = "FCM_TOKEN" context: Context,
) {
companion object {
private const val PREFS_KEY_FCM_TOKEN = "FCM_TOKEN"
}
private val sharedPrefs = DefaultSharedPreferences.getInstance(context)
fun isFirebaseAvailable(): Boolean = true fun isFirebaseAvailable(): Boolean = true
@ -44,22 +49,18 @@ object FcmHelper {
* *
* @return the FCM token or null if not received from FCM * @return the FCM token or null if not received from FCM
*/ */
fun getFcmToken(context: Context): String? { fun getFcmToken(): String? {
return DefaultSharedPreferences.getInstance(context).getString(PREFS_KEY_FCM_TOKEN, null) return sharedPrefs.getString(PREFS_KEY_FCM_TOKEN, null)
} }
/** /**
* Store FCM token to the SharedPrefs * Store FCM token to the SharedPrefs
* TODO Store in realm * TODO Store in realm
* *
* @param context android context
* @param token the token to store * @param token the token to store
*/ */
fun storeFcmToken( fun storeFcmToken(token: String?) {
context: Context, sharedPrefs.edit {
token: String?
) {
DefaultSharedPreferences.getInstance(context).edit {
putString(PREFS_KEY_FCM_TOKEN, token) putString(PREFS_KEY_FCM_TOKEN, token)
} }
} }
@ -76,7 +77,7 @@ object FcmHelper {
try { try {
FirebaseMessaging.getInstance().token FirebaseMessaging.getInstance().token
.addOnSuccessListener { token -> .addOnSuccessListener { token ->
storeFcmToken(activity, token) storeFcmToken(token)
if (registerPusher) { if (registerPusher) {
pushersManager.enqueueRegisterPusherWithFcmKey(token) pushersManager.enqueueRegisterPusherWithFcmKey(token)
} }
@ -98,24 +99,19 @@ object FcmHelper {
* it doesn't, display a dialog that allows users to download the APK from * it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings. * the Google Play Store or enable it in the device's system settings.
*/ */
fun checkPlayServices(context: Context): Boolean { private fun checkPlayServices(context: Context): Boolean {
val apiAvailability = GoogleApiAvailability.getInstance() val apiAvailability = GoogleApiAvailability.getInstance()
val resultCode = apiAvailability.isGooglePlayServicesAvailable(context) val resultCode = apiAvailability.isGooglePlayServicesAvailable(context)
return resultCode == ConnectionResult.SUCCESS return resultCode == ConnectionResult.SUCCESS
} }
@Suppress("UNUSED_PARAMETER") @Suppress("UNUSED_PARAMETER")
fun onEnterForeground(context: Context, activeSessionHolder: ActiveSessionHolder) { fun onEnterForeground(activeSessionHolder: ActiveSessionHolder) {
// No op // No op
} }
@Suppress("UNUSED_PARAMETER") @Suppress("UNUSED_PARAMETER")
fun onEnterBackground( fun onEnterBackground(activeSessionHolder: ActiveSessionHolder) {
context: Context,
vectorPreferences: VectorPreferences,
activeSessionHolder: ActiveSessionHolder,
clock: Clock
) {
// No op // No op
} }
} }

View File

@ -43,7 +43,6 @@ import dagger.hilt.android.HiltAndroidApp
import im.vector.app.core.di.ActiveSessionHolder import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.core.extensions.configureAndStart import im.vector.app.core.extensions.configureAndStart
import im.vector.app.core.extensions.startSyncing import im.vector.app.core.extensions.startSyncing
import im.vector.app.core.time.Clock
import im.vector.app.features.analytics.VectorAnalytics import im.vector.app.features.analytics.VectorAnalytics
import im.vector.app.features.call.webrtc.WebRtcCallManager import im.vector.app.features.call.webrtc.WebRtcCallManager
import im.vector.app.features.configuration.VectorConfiguration import im.vector.app.features.configuration.VectorConfiguration
@ -86,7 +85,6 @@ class VectorApplication :
@Inject lateinit var emojiCompatWrapper: EmojiCompatWrapper @Inject lateinit var emojiCompatWrapper: EmojiCompatWrapper
@Inject lateinit var vectorUncaughtExceptionHandler: VectorUncaughtExceptionHandler @Inject lateinit var vectorUncaughtExceptionHandler: VectorUncaughtExceptionHandler
@Inject lateinit var activeSessionHolder: ActiveSessionHolder @Inject lateinit var activeSessionHolder: ActiveSessionHolder
@Inject lateinit var clock: Clock
@Inject lateinit var notificationDrawerManager: NotificationDrawerManager @Inject lateinit var notificationDrawerManager: NotificationDrawerManager
@Inject lateinit var vectorPreferences: VectorPreferences @Inject lateinit var vectorPreferences: VectorPreferences
@Inject lateinit var versionProvider: VersionProvider @Inject lateinit var versionProvider: VersionProvider
@ -100,6 +98,7 @@ class VectorApplication :
@Inject lateinit var vectorFileLogger: VectorFileLogger @Inject lateinit var vectorFileLogger: VectorFileLogger
@Inject lateinit var vectorAnalytics: VectorAnalytics @Inject lateinit var vectorAnalytics: VectorAnalytics
@Inject lateinit var matrix: Matrix @Inject lateinit var matrix: Matrix
@Inject lateinit var fcmHelper: FcmHelper
// font thread handler // font thread handler
private var fontThreadHandler: Handler? = null private var fontThreadHandler: Handler? = null
@ -174,7 +173,7 @@ class VectorApplication :
ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver { ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onResume(owner: LifecycleOwner) { override fun onResume(owner: LifecycleOwner) {
Timber.i("App entered foreground") Timber.i("App entered foreground")
FcmHelper.onEnterForeground(appContext, activeSessionHolder) fcmHelper.onEnterForeground(activeSessionHolder)
activeSessionHolder.getSafeActiveSession()?.also { activeSessionHolder.getSafeActiveSession()?.also {
it.syncService().stopAnyBackgroundSync() it.syncService().stopAnyBackgroundSync()
} }
@ -182,7 +181,7 @@ class VectorApplication :
override fun onPause(owner: LifecycleOwner) { override fun onPause(owner: LifecycleOwner) {
Timber.i("App entered background") Timber.i("App entered background")
FcmHelper.onEnterBackground(appContext, vectorPreferences, activeSessionHolder, clock) fcmHelper.onEnterBackground(activeSessionHolder)
} }
}) })
ProcessLifecycleOwner.get().lifecycle.addObserver(appStateHandler) ProcessLifecycleOwner.get().lifecycle.addObserver(appStateHandler)

View File

@ -45,6 +45,7 @@ class UnifiedPushHelper @Inject constructor(
private val vectorPreferences: VectorPreferences, private val vectorPreferences: VectorPreferences,
private val matrix: Matrix, private val matrix: Matrix,
private val vectorFeatures: VectorFeatures, private val vectorFeatures: VectorFeatures,
private val fcmHelper: FcmHelper,
) { ) {
private val up = UnifiedPush private val up = UnifiedPush
@ -132,7 +133,7 @@ class UnifiedPushHelper @Inject constructor(
cancellable: Boolean, cancellable: Boolean,
) { ) {
val internalDistributorName = stringProvider.getString( val internalDistributorName = stringProvider.getString(
if (FcmHelper.isFirebaseAvailable()) { if (fcmHelper.isFirebaseAvailable()) {
R.string.unifiedpush_distributor_fcm_fallback R.string.unifiedpush_distributor_fcm_fallback
} else { } else {
R.string.unifiedpush_distributor_background_sync R.string.unifiedpush_distributor_background_sync
@ -244,11 +245,11 @@ class UnifiedPushHelper @Inject constructor(
} }
fun isEmbeddedDistributor(): Boolean { fun isEmbeddedDistributor(): Boolean {
return up.getDistributor(context) == context.packageName && FcmHelper.isFirebaseAvailable() return up.getDistributor(context) == context.packageName && fcmHelper.isFirebaseAvailable()
} }
fun isBackgroundSync(): Boolean { fun isBackgroundSync(): Boolean {
return up.getDistributor(context) == context.packageName && !FcmHelper.isFirebaseAvailable() return up.getDistributor(context) == context.packageName && !fcmHelper.isFirebaseAvailable()
} }
fun getPrivacyFriendlyUpEndpoint(): String? { fun getPrivacyFriendlyUpEndpoint(): String? {

View File

@ -129,6 +129,7 @@ class HomeActivity :
@Inject lateinit var initSyncStepFormatter: InitSyncStepFormatter @Inject lateinit var initSyncStepFormatter: InitSyncStepFormatter
@Inject lateinit var appStateHandler: AppStateHandler @Inject lateinit var appStateHandler: AppStateHandler
@Inject lateinit var unifiedPushHelper: UnifiedPushHelper @Inject lateinit var unifiedPushHelper: UnifiedPushHelper
@Inject lateinit var fcmHelper: FcmHelper
private val createSpaceResultLauncher = registerStartForActivityResult { activityResult -> private val createSpaceResultLauncher = registerStartForActivityResult { activityResult ->
if (activityResult.resultCode == Activity.RESULT_OK) { if (activityResult.resultCode == Activity.RESULT_OK) {
@ -191,7 +192,7 @@ class HomeActivity :
supportFragmentManager.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, false) supportFragmentManager.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, false)
unifiedPushHelper.register(this) { unifiedPushHelper.register(this) {
if (unifiedPushHelper.isEmbeddedDistributor()) { if (unifiedPushHelper.isEmbeddedDistributor()) {
FcmHelper.ensureFcmTokenIsRetrieved( fcmHelper.ensureFcmTokenIsRetrieved(
this, this,
pushManager, pushManager,
vectorPreferences.areNotificationEnabledForDevice() vectorPreferences.areNotificationEnabledForDevice()

View File

@ -27,13 +27,14 @@ import javax.inject.Inject
class TestAvailableUnifiedPushDistributors @Inject constructor( class TestAvailableUnifiedPushDistributors @Inject constructor(
private val unifiedPushHelper: UnifiedPushHelper, private val unifiedPushHelper: UnifiedPushHelper,
private val stringProvider: StringProvider, private val stringProvider: StringProvider,
private val fcmHelper: FcmHelper,
) : TroubleshootTest(R.string.settings_troubleshoot_test_distributors_title) { ) : TroubleshootTest(R.string.settings_troubleshoot_test_distributors_title) {
override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) { override fun perform(activityResultLauncher: ActivityResultLauncher<Intent>) {
val distributors = unifiedPushHelper.getExternalDistributors() val distributors = unifiedPushHelper.getExternalDistributors()
description = if (distributors.isEmpty()) { description = if (distributors.isEmpty()) {
stringProvider.getString( stringProvider.getString(
if (FcmHelper.isFirebaseAvailable()) { if (fcmHelper.isFirebaseAvailable()) {
R.string.settings_troubleshoot_test_distributors_gplay R.string.settings_troubleshoot_test_distributors_gplay
} else { } else {
R.string.settings_troubleshoot_test_distributors_fdroid R.string.settings_troubleshoot_test_distributors_fdroid