mirror of
https://github.com/oxen-io/session-android.git
synced 2025-05-17 23:18:16 +00:00
Add FirebasePushManager#unregister
This commit is contained in:
parent
95bb9ee441
commit
ba6eca2443
@ -2,5 +2,4 @@ package org.thoughtcrime.securesms.notifications
|
|||||||
|
|
||||||
interface PushManager {
|
interface PushManager {
|
||||||
fun register(force: Boolean)
|
fun register(force: Boolean)
|
||||||
fun unregister(token: String)
|
|
||||||
}
|
}
|
@ -1,6 +1,8 @@
|
|||||||
package org.thoughtcrime.securesms.notifications
|
package org.thoughtcrime.securesms.notifications
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import com.google.android.gms.tasks.Task
|
||||||
|
import com.google.firebase.iid.InstanceIdResult
|
||||||
import com.goterl.lazysodium.LazySodiumAndroid
|
import com.goterl.lazysodium.LazySodiumAndroid
|
||||||
import com.goterl.lazysodium.SodiumAndroid
|
import com.goterl.lazysodium.SodiumAndroid
|
||||||
import com.goterl.lazysodium.interfaces.AEAD
|
import com.goterl.lazysodium.interfaces.AEAD
|
||||||
@ -21,6 +23,8 @@ import org.session.libsession.messaging.sending_receiving.notifications.PushNoti
|
|||||||
import org.session.libsession.messaging.sending_receiving.notifications.PushNotificationMetadata
|
import org.session.libsession.messaging.sending_receiving.notifications.PushNotificationMetadata
|
||||||
import org.session.libsession.messaging.sending_receiving.notifications.SubscriptionRequest
|
import org.session.libsession.messaging.sending_receiving.notifications.SubscriptionRequest
|
||||||
import org.session.libsession.messaging.sending_receiving.notifications.SubscriptionResponse
|
import org.session.libsession.messaging.sending_receiving.notifications.SubscriptionResponse
|
||||||
|
import org.session.libsession.messaging.sending_receiving.notifications.UnsubscribeResponse
|
||||||
|
import org.session.libsession.messaging.sending_receiving.notifications.UnsubscriptionRequest
|
||||||
import org.session.libsession.messaging.utilities.SodiumUtilities
|
import org.session.libsession.messaging.utilities.SodiumUtilities
|
||||||
import org.session.libsession.snode.OnionRequestAPI
|
import org.session.libsession.snode.OnionRequestAPI
|
||||||
import org.session.libsession.snode.SnodeAPI
|
import org.session.libsession.snode.SnodeAPI
|
||||||
@ -74,7 +78,7 @@ class FirebasePushManager(private val context: Context, private val prefs: TextS
|
|||||||
|
|
||||||
val metadataJson = (expectedList[0] as? BencodeString)?.value
|
val metadataJson = (expectedList[0] as? BencodeString)?.value
|
||||||
?: error("no metadata")
|
?: error("no metadata")
|
||||||
val metadata:PushNotificationMetadata = Json.decodeFromString(String(metadataJson))
|
val metadata: PushNotificationMetadata = Json.decodeFromString(String(metadataJson))
|
||||||
|
|
||||||
val content: ByteArray? = if (expectedList.size >= 2) (expectedList[1] as? BencodeString)?.value else null
|
val content: ByteArray? = if (expectedList.size >= 2) (expectedList[1] as? BencodeString)?.value else null
|
||||||
// null content is valid only if we got a "data_too_long" flag
|
// null content is valid only if we got a "data_too_long" flag
|
||||||
@ -90,41 +94,71 @@ class FirebasePushManager(private val context: Context, private val prefs: TextS
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun register(force: Boolean) {
|
override fun register(force: Boolean) {
|
||||||
val currentInstanceIdJob = firebaseInstanceIdJob
|
firebaseInstanceIdJob?.apply {
|
||||||
if (currentInstanceIdJob != null && currentInstanceIdJob.isActive && !force) return
|
if (force) cancel() else if (isActive) return
|
||||||
|
|
||||||
if (force && currentInstanceIdJob != null) {
|
|
||||||
currentInstanceIdJob.cancel(null)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
firebaseInstanceIdJob = getFcmInstanceId { task ->
|
firebaseInstanceIdJob = getFcmInstanceId { register(it, force) }
|
||||||
// context in here is Dispatchers.IO
|
}
|
||||||
if (!task.isSuccessful) {
|
|
||||||
Log.w(
|
private fun register(task: Task<InstanceIdResult>, force: Boolean) {
|
||||||
"Loki",
|
// context in here is Dispatchers.IO
|
||||||
"FirebaseInstanceId.getInstance().getInstanceId() failed." + task.exception
|
if (!task.isSuccessful) {
|
||||||
)
|
Log.w(
|
||||||
return@getFcmInstanceId
|
"Loki",
|
||||||
}
|
"FirebaseInstanceId.getInstance().getInstanceId() failed." + task.exception
|
||||||
val token: String = task.result?.token ?: return@getFcmInstanceId
|
)
|
||||||
val userPublicKey = getLocalNumber(context) ?: return@getFcmInstanceId
|
return
|
||||||
val userEdKey = KeyPairUtilities.getUserED25519KeyPair(context) ?: return@getFcmInstanceId
|
}
|
||||||
if (prefs.isUsingFCM()) {
|
|
||||||
register(token, userPublicKey, userEdKey, force)
|
val token: String = task.result?.token ?: return
|
||||||
} else {
|
val userPublicKey = getLocalNumber(context) ?: return
|
||||||
unregister(token)
|
val userEdKey = KeyPairUtilities.getUserED25519KeyPair(context) ?: return
|
||||||
|
|
||||||
|
when {
|
||||||
|
prefs.isUsingFCM() -> register(token, userPublicKey, userEdKey, force)
|
||||||
|
prefs.getFCMToken() != null -> unregister(token, userPublicKey, userEdKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun unregister(token: String, userPublicKey: String, userEdKey: KeyPair) {
|
||||||
|
val timestamp = SnodeAPI.nowWithOffset / 1000 // get timestamp in ms -> s
|
||||||
|
// if we want to support passing namespace list, here is the place to do it
|
||||||
|
val sigData = "UNSUBSCRIBE${userPublicKey}${timestamp}".encodeToByteArray()
|
||||||
|
val signature = ByteArray(Sign.BYTES)
|
||||||
|
sodium.cryptoSignDetached(signature, sigData, sigData.size.toLong(), userEdKey.secretKey.asBytes)
|
||||||
|
|
||||||
|
val requestParameters = UnsubscriptionRequest(
|
||||||
|
pubkey = userPublicKey,
|
||||||
|
session_ed25519 = userEdKey.publicKey.asHexString,
|
||||||
|
service = "firebase",
|
||||||
|
sig_ts = timestamp,
|
||||||
|
signature = Base64.encodeBytes(signature),
|
||||||
|
service_info = mapOf("token" to token),
|
||||||
|
)
|
||||||
|
|
||||||
|
val url = "${PushNotificationAPI.server}/unsubscribe"
|
||||||
|
val body = RequestBody.create(MediaType.get("application/json"), Json.encodeToString(requestParameters))
|
||||||
|
val request = Request.Builder().url(url).post(body)
|
||||||
|
retryIfNeeded(maxRetryCount) {
|
||||||
|
getResponseBody<UnsubscribeResponse>(request.build()).map { response ->
|
||||||
|
if (response.success == true) {
|
||||||
|
TextSecurePreferences.setIsUsingFCM(context, false)
|
||||||
|
TextSecurePreferences.setFCMToken(context, null)
|
||||||
|
Log.d("Loki", "Unsubscribe FCM success")
|
||||||
|
} else {
|
||||||
|
Log.e("Loki", "Couldn't unregister for FCM due to error: ${response.message}")
|
||||||
|
}
|
||||||
|
}.fail { exception ->
|
||||||
|
Log.e("Loki", "Couldn't unregister for FCM due to error: ${exception}.", exception)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun unregister(token: String) {
|
private fun register(token: String, publicKey: String, userEd25519Key: KeyPair, force: Boolean, namespaces: List<Int> = listOf(Namespace.DEFAULT)) {
|
||||||
TODO("Not yet implemented")
|
|
||||||
}
|
|
||||||
|
|
||||||
fun register(token: String, publicKey: String, userEd25519Key: KeyPair, force: Boolean, namespaces: List<Int> = listOf(Namespace.DEFAULT)) {
|
|
||||||
val oldToken = TextSecurePreferences.getFCMToken(context)
|
val oldToken = TextSecurePreferences.getFCMToken(context)
|
||||||
val lastUploadDate = TextSecurePreferences.getLastFCMUploadTime(context)
|
val lastUploadDate = TextSecurePreferences.getLastFCMUploadTime(context)
|
||||||
if (!force && token == oldToken && System.currentTimeMillis() - lastUploadDate < tokenExpirationInterval) { return }
|
if (!force && token == oldToken && System.currentTimeMillis() - lastUploadDate < tokenExpirationInterval) return
|
||||||
|
|
||||||
val pnKey = getOrCreateNotificationKey()
|
val pnKey = getOrCreateNotificationKey()
|
||||||
|
|
||||||
@ -133,7 +167,7 @@ class FirebasePushManager(private val context: Context, private val prefs: TextS
|
|||||||
val sigData = "MONITOR${publicKey}${timestamp}1${namespaces.joinToString(separator = ",")}".encodeToByteArray()
|
val sigData = "MONITOR${publicKey}${timestamp}1${namespaces.joinToString(separator = ",")}".encodeToByteArray()
|
||||||
val signature = ByteArray(Sign.BYTES)
|
val signature = ByteArray(Sign.BYTES)
|
||||||
sodium.cryptoSignDetached(signature, sigData, sigData.size.toLong(), userEd25519Key.secretKey.asBytes)
|
sodium.cryptoSignDetached(signature, sigData, sigData.size.toLong(), userEd25519Key.secretKey.asBytes)
|
||||||
val requestParameters = SubscriptionRequest (
|
val requestParameters = SubscriptionRequest(
|
||||||
pubkey = publicKey,
|
pubkey = publicKey,
|
||||||
session_ed25519 = userEd25519Key.publicKey.asHexString,
|
session_ed25519 = userEd25519Key.publicKey.asHexString,
|
||||||
namespaces = listOf(Namespace.DEFAULT),
|
namespaces = listOf(Namespace.DEFAULT),
|
||||||
@ -149,9 +183,8 @@ class FirebasePushManager(private val context: Context, private val prefs: TextS
|
|||||||
val body = RequestBody.create(MediaType.get("application/json"), Json.encodeToString(requestParameters))
|
val body = RequestBody.create(MediaType.get("application/json"), Json.encodeToString(requestParameters))
|
||||||
val request = Request.Builder().url(url).post(body)
|
val request = Request.Builder().url(url).post(body)
|
||||||
retryIfNeeded(maxRetryCount) {
|
retryIfNeeded(maxRetryCount) {
|
||||||
getResponseBody(request.build()).map { response ->
|
getResponseBody<SubscriptionResponse>(request.build()).map { response ->
|
||||||
if (response.isSuccess()) {
|
if (response.isSuccess()) {
|
||||||
TextSecurePreferences.setIsUsingFCM(context, true)
|
|
||||||
TextSecurePreferences.setFCMToken(context, token)
|
TextSecurePreferences.setFCMToken(context, token)
|
||||||
TextSecurePreferences.setLastFCMUploadTime(context, System.currentTimeMillis())
|
TextSecurePreferences.setLastFCMUploadTime(context, System.currentTimeMillis())
|
||||||
} else {
|
} else {
|
||||||
@ -159,18 +192,16 @@ class FirebasePushManager(private val context: Context, private val prefs: TextS
|
|||||||
Log.e("Loki", "Couldn't register for FCM due to error: $message.")
|
Log.e("Loki", "Couldn't register for FCM due to error: $message.")
|
||||||
}
|
}
|
||||||
}.fail { exception ->
|
}.fail { exception ->
|
||||||
Log.e("Loki", "Couldn't register for FCM due to error: ${exception}.")
|
Log.e("Loki", "Couldn't register for FCM due to error: ${exception}.", exception)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getResponseBody(request: Request): Promise<SubscriptionResponse, Exception> {
|
private inline fun <reified T> getResponseBody(request: Request): Promise<T, Exception> =
|
||||||
return OnionRequestAPI.sendOnionRequest(request,
|
OnionRequestAPI.sendOnionRequest(
|
||||||
|
request,
|
||||||
PushNotificationAPI.server,
|
PushNotificationAPI.server,
|
||||||
PushNotificationAPI.serverPublicKey, Version.V4).map { response ->
|
PushNotificationAPI.serverPublicKey,
|
||||||
Json.decodeFromStream(response.body!!.inputStream())
|
Version.V4
|
||||||
}
|
).map { response -> Json.decodeFromStream(response.body!!.inputStream()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
@ -7,8 +7,4 @@ class NoOpPushManager: PushManager {
|
|||||||
override fun register(force: Boolean) {
|
override fun register(force: Boolean) {
|
||||||
Log.d("NoOpPushManager", "Push notifications not supported, not registering for push notifications")
|
Log.d("NoOpPushManager", "Push notifications not supported, not registering for push notifications")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
override fun unregister(token: String) {
|
|
||||||
Log.d("NoOpPushManager", "Push notifications not supported, not unregistering for push notifications")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -36,6 +36,24 @@ data class SubscriptionRequest(
|
|||||||
val enc_key: String
|
val enc_key: String
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class UnsubscriptionRequest(
|
||||||
|
/** the 33-byte account being subscribed to; typically a session ID */
|
||||||
|
val pubkey: String,
|
||||||
|
/** when the pubkey starts with 05 (i.e. a session ID) this is the ed25519 32-byte pubkey associated with the session ID */
|
||||||
|
val session_ed25519: String?,
|
||||||
|
/** 32-byte swarm authentication subkey; omitted (or null) when not using subkey auth (new closed groups) */
|
||||||
|
val subkey_tag: String? = null,
|
||||||
|
/** the signature unix timestamp in seconds, not ms */
|
||||||
|
val sig_ts: Long,
|
||||||
|
/** the 64-byte ed25519 signature */
|
||||||
|
val signature: String,
|
||||||
|
/** the string identifying the notification service, "firebase" for android (currently) */
|
||||||
|
val service: String,
|
||||||
|
/** dict of service-specific data, currently just "token" field with device-specific token but different services might have other requirements */
|
||||||
|
val service_info: Map<String, String>,
|
||||||
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class SubscriptionResponse(
|
data class SubscriptionResponse(
|
||||||
val error: Int? = null,
|
val error: Int? = null,
|
||||||
@ -60,6 +78,14 @@ data class SubscriptionResponse(
|
|||||||
} else null to null
|
} else null to null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class UnsubscribeResponse(
|
||||||
|
val error: Int? = null,
|
||||||
|
val message: String? = null,
|
||||||
|
val success: Boolean? = null,
|
||||||
|
val removed: Boolean? = null,
|
||||||
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class PushNotificationMetadata(
|
data class PushNotificationMetadata(
|
||||||
/** Account ID (such as Session ID or closed group ID) where the message arrived **/
|
/** Account ID (such as Session ID or closed group ID) where the message arrived **/
|
||||||
|
@ -318,7 +318,7 @@ interface TextSecurePreferences {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun setFCMToken(context: Context, value: String) {
|
fun setFCMToken(context: Context, value: String?) {
|
||||||
setStringPreference(context, FCM_TOKEN, value)
|
setStringPreference(context, FCM_TOKEN, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user