Skip to content

Commit

Permalink
Merge pull request #3485 from nextcloud/bugfix/noid/inviniteLoadingAf…
Browse files Browse the repository at this point in the history
…terLogin

Add fixes and changes to push handling
  • Loading branch information
mahibi authored Dec 1, 2023
2 parents a8cacf1 + 173582a commit e86599e
Show file tree
Hide file tree
Showing 12 changed files with 452 additions and 525 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,35 +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
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 All @@ -68,6 +71,6 @@ class GetFirebasePushTokenWorker(val context: Context, workerParameters: WorkerP
}

companion object {
const val TAG = "GetFirebasePushTokenWorker"
private val TAG = GetFirebasePushTokenWorker::class.simpleName
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,8 @@ class NCFirebaseMessagingService : FirebaseMessagingService() {

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
69 changes: 17 additions & 52 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,77 +64,43 @@ class ClosedInterfaceImpl : ClosedInterface, ProviderInstaller.ProviderInstallLi
val api = GoogleApiAvailability.getInstance()
val code =
NextcloudTalkApplication.sharedApplication?.let {
api.isGooglePlayServicesAvailable(
it.applicationContext
)
api.isGooglePlayServicesAvailable(it.applicationContext)
}
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,21 +357,10 @@ 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) {
Log.d(TAG, "caught EventStatus of type " + eventStatus.eventType.toString())
if (eventStatus.eventType == EventStatus.EventType.PUSH_REGISTRATION) {
if (internalAccountId == eventStatus.userId && !eventStatus.isAllGood) {
runOnUiThread {
Expand Down Expand Up @@ -415,31 +404,30 @@ class AccountVerificationActivity : BaseActivity() {
Data.Builder()
.putLong(KEY_INTERNAL_USER_ID, internalAccountId)
.build()
val pushNotificationWork =
val capabilitiesWork =
OneTimeWorkRequest.Builder(CapabilitiesWorker::class.java)
.setInputData(userData)
.build()
WorkManager.getInstance().enqueue(pushNotificationWork)
WorkManager.getInstance().enqueue(capabilitiesWork)
}

private fun fetchAndStoreExternalSignalingSettings() {
val userData =
Data.Builder()
.putLong(KEY_INTERNAL_USER_ID, internalAccountId)
.build()
val signalingSettings = OneTimeWorkRequest.Builder(SignalingSettingsWorker::class.java)
val signalingSettingsWorker = OneTimeWorkRequest.Builder(SignalingSettingsWorker::class.java)
.setInputData(userData)
.build()
val websocketConnectionsWorker = OneTimeWorkRequest.Builder(WebsocketConnectionsWorker::class.java).build()

WorkManager.getInstance(applicationContext!!)
.beginWith(signalingSettings)
.beginWith(signalingSettingsWorker)
.then(websocketConnectionsWorker)
.enqueue()
}

private fun proceedWithLogin() {
Log.d(TAG, "proceedWithLogin...")
cookieManager.cookieStore.removeAll()

if (userManager.users.blockingGet().size == 1 ||
Expand All @@ -466,6 +454,8 @@ class AccountVerificationActivity : BaseActivity() {
Log.e(TAG, "failed to set active user")
Snackbar.make(binding.root, R.string.nc_common_error_sorry, Snackbar.LENGTH_LONG).show()
}
} else {
Log.d(TAG, "continuing proceedWithLogin was skipped for this user")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import android.os.Bundle
import android.provider.ContactsContract
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
Expand All @@ -52,6 +53,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 +80,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 +281,7 @@ class MainActivity : BaseActivity(), ActionBarProvider {

override fun onSuccess(users: List<User>) {
if (users.isNotEmpty()) {
ClosedInterfaceImpl().setUpPushTokenRegistration()
runOnUiThread {
openConversationList()
}
Expand All @@ -292,6 +294,11 @@ class MainActivity : BaseActivity(), ActionBarProvider {

override fun onError(e: Throwable) {
Log.e(TAG, "Error loading existing users", e)
Toast.makeText(
context,
context.resources.getString(R.string.nc_common_error_sorry),
Toast.LENGTH_SHORT
).show()
}
})
}
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
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public PushRegistrationWorker(@NonNull Context context, @NonNull WorkerParameter
@Override
public Result doWork() {
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
if(new ClosedInterfaceImpl().isGooglePlayServicesAvailable()){
if (new ClosedInterfaceImpl().isGooglePlayServicesAvailable()) {
Data data = getInputData();
String origin = data.getString("origin");
Log.d(TAG, "PushRegistrationWorker called via " + origin);
Expand Down
Loading

0 comments on commit e86599e

Please sign in to comment.