FirebaseTokenService.kt 1.92 KB
Newer Older
1 2 3
package chat.rocket.android.push

import chat.rocket.android.infrastructure.LocalRepository
4 5
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.infraestructure.RocketChatClientFactory
Lucio Maciel's avatar
Lucio Maciel committed
6
import chat.rocket.android.util.retryIO
7 8
import chat.rocket.common.RocketChatException
import chat.rocket.core.internal.rest.registerPushToken
Leonardo Aramaki's avatar
Leonardo Aramaki committed
9
import com.google.firebase.iid.FirebaseInstanceId
10
import com.google.firebase.iid.FirebaseInstanceIdService
11
import dagger.android.AndroidInjection
12 13 14 15
import kotlinx.coroutines.experimental.launch
import timber.log.Timber
import javax.inject.Inject

16
class FirebaseTokenService : FirebaseInstanceIdService() {
17 18

    @Inject
19 20 21
    lateinit var factory: RocketChatClientFactory
    @Inject
    lateinit var getCurrentServerInteractor: GetCurrentServerInteractor
22 23 24 25 26 27

    @Inject
    lateinit var localRepository: LocalRepository

    override fun onCreate() {
        super.onCreate()
28
        AndroidInjection.inject(this)
29 30 31
    }

    override fun onTokenRefresh() {
Lucio Maciel's avatar
Lucio Maciel committed
32
        try {
Leonardo Aramaki's avatar
Leonardo Aramaki committed
33
            val fcmToken = FirebaseInstanceId.getInstance().token
Lucio Maciel's avatar
Lucio Maciel committed
34 35
            val currentServer = getCurrentServerInteractor.get()
            val client = currentServer?.let { factory.create(currentServer) }
36

Leonardo Aramaki's avatar
Leonardo Aramaki committed
37 38
            fcmToken?.let {
                localRepository.save(LocalRepository.KEY_PUSH_TOKEN, fcmToken)
Lucio Maciel's avatar
Lucio Maciel committed
39 40 41
                client?.let {
                    launch {
                        try {
Leonardo Aramaki's avatar
Leonardo Aramaki committed
42 43
                            Timber.d("Registering push token: $fcmToken for ${client.url}")
                            retryIO("register push token") { client.registerPushToken(fcmToken) }
Lucio Maciel's avatar
Lucio Maciel committed
44 45 46
                        } catch (ex: RocketChatException) {
                            Timber.e(ex, "Error registering push token")
                        }
Lucio Maciel's avatar
Lucio Maciel committed
47
                    }
48 49
                }
            }
Lucio Maciel's avatar
Lucio Maciel committed
50
        } catch (ex: Exception) {
Leonardo Aramaki's avatar
Leonardo Aramaki committed
51
            Timber.e(ex, "Error refreshing Firebase TOKEN")
52 53 54
        }
    }
}