Skip to content

Commit

Permalink
refactor some push related code
Browse files Browse the repository at this point in the history
Fix injection in GetFirebasePushTokenWorker.
injection was not setup correctly in GetFirebasePushTokenWorker so the appPreferences were null. This resulted in the invinite loading screen during account setup if somehow onNewToken did not set the token.

avoid to register push on every load of ConversationList.

call GetFirebasePushTokenWorker instead of PushRegistrationWorker to make sure the firebase token is set(if onNewToken somehow fails to set it). Other than that, only call PushRegistrationWorker directly in NCFirebaseMessagingService as there the token is set.

Signed-off-by: Marcel Hibbe <[email protected]>
  • Loading branch information
mahibi committed Nov 30, 2023
1 parent 8326cbc commit 3f5bc09
Show file tree
Hide file tree
Showing 10 changed files with 449 additions and 537 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,6 @@ public boolean isGooglePlayServicesAvailable() {

@Override
public void setUpPushTokenRegistration() {
// no push notifications for generic build flavour :(
// If you want to develop push notifications without google play services, here is a good place to start...
// Also have a look at app/src/gplay/AndroidManifest.xml to see how to include a service that handles push
// notifications.
// no push notifications for generic build variant
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,36 +28,38 @@ import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import autodagger.AutoInjector
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging
import com.nextcloud.talk.application.NextcloudTalkApplication
import com.nextcloud.talk.utils.preferences.AppPreferences
import javax.inject.Inject

@AutoInjector(NextcloudTalkApplication::class)
class GetFirebasePushTokenWorker(val context: Context, workerParameters: WorkerParameters) :
Worker(context, workerParameters) {

@JvmField
@Inject
var appPreferences: AppPreferences? = null
lateinit var appPreferences: AppPreferences

@SuppressLint("LongLogTag")
override fun doWork(): Result {
NextcloudTalkApplication.sharedApplication!!.componentApplication.inject(this)

FirebaseMessaging.getInstance().token.addOnCompleteListener(
OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "Fetching FCM registration token failed", task.exception)
return@OnCompleteListener
}

val token = task.result
Log.d(TAG, "Fetched push token is: $token")
val pushToken = task.result
Log.d(TAG, "Fetched firebase push token is: $pushToken")

appPreferences?.pushToken = token
appPreferences.pushToken = pushToken

val data: Data =
Data.Builder()
.putString(PushRegistrationWorker.ORIGIN, "GetFirebasePushTokenWorker")
.build()
Data.Builder().putString(PushRegistrationWorker.ORIGIN, "GetFirebasePushTokenWorker").build()
val pushRegistrationWork = OneTimeWorkRequest.Builder(PushRegistrationWorker::class.java)
.setInputData(data)
.build()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,10 @@ class NCFirebaseMessagingService : FirebaseMessagingService() {
super.onNewToken(token)
Log.d(TAG, "onNewToken. token = $token")

// appPreferences.pushToken = token // TODO revert this! just for testing, do not set the token.
// seems this sometimes somehow also happens in reality
appPreferences.pushToken = token

val data: Data = Data.Builder().putString(
PushRegistrationWorker.ORIGIN,
"NCFirebaseMessagingService#onNewToken"
).build()
val data: Data =
Data.Builder().putString(PushRegistrationWorker.ORIGIN, "NCFirebaseMessagingService#onNewToken").build()
val pushRegistrationWork = OneTimeWorkRequest.Builder(PushRegistrationWorker::class.java)
.setInputData(data)
.build()
Expand Down
70 changes: 17 additions & 53 deletions app/src/gplay/java/com/nextcloud/talk/utils/ClosedInterfaceImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
package com.nextcloud.talk.utils

import android.content.Intent
import androidx.work.Data
import android.util.Log
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.PeriodicWorkRequest
Expand All @@ -36,7 +36,6 @@ import com.google.android.gms.security.ProviderInstaller
import com.nextcloud.talk.application.NextcloudTalkApplication
import com.nextcloud.talk.interfaces.ClosedInterface
import com.nextcloud.talk.jobs.GetFirebasePushTokenWorker
import com.nextcloud.talk.jobs.PushRegistrationWorker
import java.util.concurrent.TimeUnit

@AutoInjector(NextcloudTalkApplication::class)
Expand Down Expand Up @@ -65,78 +64,43 @@ class ClosedInterfaceImpl : ClosedInterface, ProviderInstaller.ProviderInstallLi
val api = GoogleApiAvailability.getInstance()
val code =
NextcloudTalkApplication.sharedApplication?.let {
api.isGooglePlayServicesAvailable(
it.applicationContext
)
api.isGooglePlayServicesAvailable(it.applicationContext)
}
// TODO: check if this always works!
return code == ConnectionResult.SUCCESS
return if (code == ConnectionResult.SUCCESS) {
true
} else {
Log.w(TAG, "GooglePlayServices are not available. Code:$code")
false
}
}

override fun setUpPushTokenRegistration() {
registerLocalToken()
setUpPeriodicLocalTokenRegistration()
setUpPeriodicTokenRefreshFromFCM()
}

private fun registerLocalToken() {
val data: Data = Data.Builder().putString(
PushRegistrationWorker.ORIGIN,
"ClosedInterfaceImpl#registerLocalToken"
)
.build()
val pushRegistrationWork = OneTimeWorkRequest.Builder(PushRegistrationWorker::class.java)
.setInputData(data)
.build()
WorkManager.getInstance().enqueue(pushRegistrationWork)
}

private fun setUpPeriodicLocalTokenRegistration() {
val data: Data = Data.Builder().putString(
PushRegistrationWorker.ORIGIN,
"ClosedInterfaceImpl#setUpPeriodicLocalTokenRegistration"
)
.build()

val periodicTokenRegistration = PeriodicWorkRequest.Builder(
PushRegistrationWorker::class.java,
DAILY,
TimeUnit.HOURS,
FLEX_INTERVAL,
TimeUnit.HOURS
)
.setInputData(data)
.build()
val firebasePushTokenWorker = OneTimeWorkRequest.Builder(GetFirebasePushTokenWorker::class.java).build()
WorkManager.getInstance().enqueue(firebasePushTokenWorker)

WorkManager.getInstance()
.enqueueUniquePeriodicWork(
"periodicTokenRegistration",
ExistingPeriodicWorkPolicy.REPLACE,
periodicTokenRegistration
)
setUpPeriodicTokenRefreshFromFCM()
}

private fun setUpPeriodicTokenRefreshFromFCM() {
val periodicTokenRefreshFromFCM = PeriodicWorkRequest.Builder(
GetFirebasePushTokenWorker::class.java,
MONTHLY,
TimeUnit.DAYS,
DAILY,
TimeUnit.HOURS,
FLEX_INTERVAL,
TimeUnit.DAYS
)
.build()
TimeUnit.HOURS
).build()

WorkManager.getInstance()
.enqueueUniquePeriodicWork(
"periodicTokenRefreshFromFCM",
ExistingPeriodicWorkPolicy.REPLACE,
ExistingPeriodicWorkPolicy.UPDATE,
periodicTokenRefreshFromFCM
)
}

companion object {
private val TAG = ClosedInterfaceImpl::class.java.simpleName
const val DAILY: Long = 24
const val MONTHLY: Long = 30
const val FLEX_INTERVAL: Long = 10
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ import com.nextcloud.talk.databinding.ActivityAccountVerificationBinding
import com.nextcloud.talk.events.EventStatus
import com.nextcloud.talk.jobs.AccountRemovalWorker
import com.nextcloud.talk.jobs.CapabilitiesWorker
import com.nextcloud.talk.jobs.PushRegistrationWorker
import com.nextcloud.talk.jobs.SignalingSettingsWorker
import com.nextcloud.talk.jobs.WebsocketConnectionsWorker
import com.nextcloud.talk.models.json.capabilities.Capabilities
Expand Down Expand Up @@ -277,8 +276,9 @@ class AccountVerificationActivity : BaseActivity() {
override fun onSuccess(user: User) {
internalAccountId = user.id!!
if (ClosedInterfaceImpl().isGooglePlayServicesAvailable) {
registerForPush()
ClosedInterfaceImpl().setUpPushTokenRegistration()
} else {
Log.w(TAG, "Skipping push registration.")
runOnUiThread {
binding.progressText.text =
""" ${binding.progressText.text}
Expand Down Expand Up @@ -357,18 +357,6 @@ class AccountVerificationActivity : BaseActivity() {
})
}

private fun registerForPush() {
val data =
Data.Builder()
.putString(PushRegistrationWorker.ORIGIN, "AccountVerificationActivity#registerForPush")
.build()
val pushRegistrationWork =
OneTimeWorkRequest.Builder(PushRegistrationWorker::class.java)
.setInputData(data)
.build()
WorkManager.getInstance().enqueue(pushRegistrationWork)
}

@SuppressLint("SetTextI18n")
@Subscribe(threadMode = ThreadMode.BACKGROUND)
fun onMessageEvent(eventStatus: EventStatus) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import com.nextcloud.talk.lock.LockedActivity
import com.nextcloud.talk.models.json.conversations.RoomOverall
import com.nextcloud.talk.users.UserManager
import com.nextcloud.talk.utils.ApiUtils
import com.nextcloud.talk.utils.ClosedInterfaceImpl
import com.nextcloud.talk.utils.SecurityUtils
import com.nextcloud.talk.utils.bundle.BundleKeys
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_ROOM_TOKEN
Expand All @@ -78,7 +79,6 @@ class MainActivity : BaseActivity(), ActionBarProvider {
}
}

@Suppress("Detekt.TooGenericExceptionCaught")
override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "onCreate: Activity: " + System.identityHashCode(this).toString())

Expand Down Expand Up @@ -280,6 +280,7 @@ class MainActivity : BaseActivity(), ActionBarProvider {

override fun onSuccess(users: List<User>) {
if (users.isNotEmpty()) {
ClosedInterfaceImpl().setUpPushTokenRegistration()
runOnUiThread {
openConversationList()
}
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/java/com/nextcloud/talk/api/NcApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@

import androidx.annotation.Nullable;
import io.reactivex.Observable;
import kotlin.Unit;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
Expand Down Expand Up @@ -333,7 +334,7 @@ Observable<GenericOverall> unregisterDeviceForNotificationsWithNextcloud(

@FormUrlEncoded
@POST
Observable<Void> registerDeviceForNotificationsWithPushProxy(@Url String url,
Observable<Unit> registerDeviceForNotificationsWithPushProxy(@Url String url,
@FieldMap Map<String, String> fields);


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ import com.nextcloud.talk.ui.dialog.ConversationsListBottomDialog
import com.nextcloud.talk.ui.dialog.FilterConversationFragment
import com.nextcloud.talk.users.UserManager
import com.nextcloud.talk.utils.ApiUtils
import com.nextcloud.talk.utils.ClosedInterfaceImpl
import com.nextcloud.talk.utils.FileUtils
import com.nextcloud.talk.utils.Mimetype
import com.nextcloud.talk.utils.ParticipantPermissions
Expand Down Expand Up @@ -254,7 +253,6 @@ class ConversationsListActivity :

showShareToScreen = hasActivityActionSendIntent()

ClosedInterfaceImpl().setUpPushTokenRegistration()
if (!eventBus.isRegistered(this)) {
eventBus.register(this)
}
Expand Down
Loading

0 comments on commit 3f5bc09

Please sign in to comment.