aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/notify/PushReceiver.kt
blob: 64ea7a7e289ef49bfdb8f9a9cf35062515f7b246 (plain) (blame)
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
package org.meshbay.client.notify

import android.content.Context
import android.util.Log
import org.meshbay.client.bridge.Bridge
import org.unifiedpush.android.connector.FailedReason
import org.unifiedpush.android.connector.PushService
import org.unifiedpush.android.connector.data.PushEndpoint
import org.unifiedpush.android.connector.data.PushMessage

/**
 * What a distributor tells this application, page running or not — when the
 * phone has one. Losing it is not an error: the phone goes back to fetching
 * (`PollJob`), and the page tells the hub at its next start.
 *
 * A message is drawn only if the connector decrypted it with this phone's
 * key: anything else did not come from a hub holding the subscription.
 */
class PushReceiver : PushService() {
    private fun state() = PushState(getSharedPreferences(PushState.PREFS, Context.MODE_PRIVATE))

    override fun onNewEndpoint(endpoint: PushEndpoint, instance: String) {
        state().endpoint(endpoint.url, endpoint.pubKeySet?.pubKey, endpoint.pubKeySet?.auth)
    }

    override fun onMessage(message: PushMessage, instance: String) {
        val state = state()
        if (!message.decrypted || !state.enabled) { Log.w(Bridge.TAG, "push message dropped"); return }
        Notifier.parse(message.content)?.let { Notifier.deliver(this, state, it) }
    }

    override fun onRegistrationFailed(reason: FailedReason, instance: String) = fallBack(reason.name)

    override fun onUnregistered(instance: String) = fallBack("UNREGISTERED")

    private fun fallBack(reason: String) {
        val state = state()
        state.fellBack(reason)
        if (state.enabled) Poller.schedule(this, pushed = false)
    }
}