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) } }