Skip to content

Commit

Permalink
Merge pull request #1909 from OneSignal/AddUserStateChangeObserver
Browse files Browse the repository at this point in the history
Add getter for onesignalId and UserStateObserver
  • Loading branch information
nan-li authored and jinliu9508 committed Feb 6, 2024
2 parents d5405c0 + e48d50b commit 12ec274
Show file tree
Hide file tree
Showing 12 changed files with 157 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import androidx.multidex.MultiDexApplication;

import com.onesignal.OneSignal;
import com.onesignal.inAppMessages.IInAppMessage;
import com.onesignal.inAppMessages.IInAppMessageClickListener;
import com.onesignal.inAppMessages.IInAppMessageClickEvent;
import com.onesignal.inAppMessages.IInAppMessageDidDismissEvent;
Expand All @@ -26,6 +25,9 @@
import com.onesignal.sdktest.constant.Text;
import com.onesignal.sdktest.notification.OneSignalNotificationSender;
import com.onesignal.sdktest.util.SharedPreferenceUtil;
import com.onesignal.user.state.IUserStateObserver;
import com.onesignal.user.state.UserChangedState;
import com.onesignal.user.state.UserState;

import org.json.JSONObject;

Expand Down Expand Up @@ -116,6 +118,14 @@ public void onWillDisplay(@NonNull INotificationWillDisplayEvent event) {
}
});

OneSignal.getUser().addObserver(new IUserStateObserver() {
@Override
public void onUserStateChange(@NonNull UserChangedState state) {
UserState currentUserState = state.getCurrent();
Log.v(Tag.LOG_TAG, "onUserStateChange fired " + currentUserState.toJSONObject());
}
});

OneSignal.getInAppMessages().setPaused(true);
OneSignal.getLocation().setShared(false);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import android.app.Activity;
import android.content.Context;
import com.google.android.material.appbar.AppBarLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
Expand All @@ -13,10 +12,8 @@
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.ViewTreeObserver;
Expand All @@ -25,13 +22,10 @@
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.onesignal.Continue;
import com.onesignal.OneSignal;
import com.onesignal.sdktest.adapter.SubscriptionRecyclerViewAdapter;
import com.onesignal.user.subscriptions.IEmailSubscription;
import com.onesignal.user.subscriptions.IPushSubscription;
import com.onesignal.user.subscriptions.ISmsSubscription;
import com.onesignal.sdktest.R;
import com.onesignal.sdktest.activity.SecondaryActivity;
import com.onesignal.sdktest.adapter.InAppMessageRecyclerViewAdapter;
Expand All @@ -57,7 +51,6 @@
import com.onesignal.user.subscriptions.ISubscription;
import com.onesignal.user.subscriptions.IPushSubscriptionObserver;
import com.onesignal.user.subscriptions.PushSubscriptionChangedState;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
Expand Down
6 changes: 5 additions & 1 deletion MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,12 @@ The user name space is accessible via `OneSignal.User` (in Kotlin) or `OneSignal
| `val pushSubscription: IPushSubscription` | `IPushSubscription getPushSubscription()` | *The push subscription associated to the current user.* |
| `fun setLanguage(value: String)` | `void setLanguage(String value)` | *Set the 2-character language either as a detected language or explicitly set for this user.* |
| `fun pushSubscription.addChangeHandler(handler: ISubscriptionChangedHandler)` | `void pushSubscription.addChangeHandler(ISubscriptionChangedHandler handler)` | *Adds a change handler that will run whenever the push subscription has been changed.* |
| `val onesignalId: String` | `String getOnesignalId()` | *Returns the OneSignal ID for the current user, which can be the empty string if it is not yet available.* |
| `val externalId: String` | `String getExternalId()` | *Returns the external ID for the current user, which can be the empty string if not set.* |
| `fun addObserver(observer: IUserStateObserver)` | `void addObserve(IUserStateObserver observer)` | *The `IUserStateObserver.onUserStateChange` method will be fired on the passed-in object when the user state changes. The User State contains the onesignalId and externalId (which can be empty strings), and the observer will be fired when these values change.* |
| `fun removeObserver(observer: IUserStateObserver)` | `void removeObserver(IUserStateObserver observer)` | *Remove a user state observer that has been previously added.* |
| `fun addAlias(label: String, id: String)` | `void addAlias(String label, String id)` | *Set an alias for the current user. If this alias already exists it will be overwritten.* |
| `fun addAliases(aliases: Map<String, String>)` | `void addAliases(Map<String, String> aliases)` | S*et aliases for the current user. If any alias already exists it will be overwritten.* |
| `fun addAliases(aliases: Map<String, String>)` | `void addAliases(Map<String, String> aliases)` | *Set aliases for the current user. If any alias already exists it will be overwritten.* |
| `fun removeAlias(label: String)` | `void removeAlias(String label)` | *Remove an alias from the current user.* |
| `fun removeAliases(labels: Collection<String>)` | `void removeAliases(Collection<String> labels)` | *Remove multiple aliases from the current user.* |
| `fun addEmail(email: String)` | `void addEmail(String email)` | *Add a new email subscription to the current user.* |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ open class EventProducer<THandler> : IEventNotifier<THandler> {
* @param callback The callback will be invoked for each subscribed handler, allowing you to call the handler.
*/
fun fire(callback: (THandler) -> Unit) {
for (s in subscribers) {
callback(s)
synchronized(subscribers) {
for (s in subscribers) {
callback(s)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,12 @@ open class SingletonModelStore<TModel>(
model: TModel,
tag: String,
) {
val existingModel = this.model
existingModel.initializeFromModel(singletonId, model)
store.persist()
changeSubscription.fire { it.onModelReplaced(existingModel, tag) }
synchronized(replaceLock) {
val existingModel = this.model
existingModel.initializeFromModel(singletonId, model)
store.persist()
changeSubscription.fire { it.onModelReplaced(existingModel, tag) }
}
}

override fun subscribe(handler: ISingletonModelStoreChangeHandler<TModel>) = changeSubscription.subscribe(handler)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.onesignal.user

import com.onesignal.OneSignal
import com.onesignal.user.state.IUserStateObserver
import com.onesignal.user.subscriptions.IPushSubscription

/**
Expand All @@ -25,6 +26,19 @@ interface IUserManager {
*/
val pushSubscription: IPushSubscription

/**
* The UUID generated by OneSignal to represent a user, empty if this is currently unavailable
*/
val onesignalId: String

/**
* The External ID is OneSignal's default and recommended alias label. This should be the main
* identifier you use to identify users. It is set when calling the [OneSignal.login] method.
*
* This is empty if the External ID has not been set.
*/
val externalId: String

/**
* Set the 2-character language either as a detected language or explicitly set for this user. See
* See [Supported Languages | OneSignal](https://documentation.onesignal.com/docs/language-localization#what-languages-are-supported)
Expand Down Expand Up @@ -138,4 +152,18 @@ interface IUserManager {
* Return a copy of all local tags from the current user.
*/
fun getTags(): Map<String, String>

/**
* Add an observer to the user state, allowing the provider to be
* notified whenever the user state has changed.
*
* Important: When using the observer to retrieve the onesignalId, check the externalId as well
* to confirm the values are associated with the expected user.
*/
fun addObserver(observer: IUserStateObserver)

/**
* Remove an observer from the user state.
*/
fun removeObserver(observer: IUserStateObserver)
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package com.onesignal.user.internal

import com.onesignal.common.IDManager
import com.onesignal.common.OneSignalUtils
import com.onesignal.common.events.EventProducer
import com.onesignal.common.modeling.ISingletonModelStoreChangeHandler
import com.onesignal.common.modeling.ModelChangedArgs
import com.onesignal.core.internal.language.ILanguageContext
import com.onesignal.debug.LogLevel
import com.onesignal.debug.internal.logging.Logging
Expand All @@ -12,23 +16,31 @@ import com.onesignal.user.internal.properties.PropertiesModel
import com.onesignal.user.internal.properties.PropertiesModelStore
import com.onesignal.user.internal.subscriptions.ISubscriptionManager
import com.onesignal.user.internal.subscriptions.SubscriptionList
import com.onesignal.user.state.IUserStateObserver
import com.onesignal.user.state.UserChangedState
import com.onesignal.user.state.UserState
import com.onesignal.user.subscriptions.IPushSubscription

internal open class UserManager(
private val _subscriptionManager: ISubscriptionManager,
private val _identityModelStore: IdentityModelStore,
private val _propertiesModelStore: PropertiesModelStore,
private val _languageContext: ILanguageContext,
) : IUserManager {
val externalId: String?
get() = _identityModel.externalId
) : IUserManager, ISingletonModelStoreChangeHandler<IdentityModel> {
override val onesignalId: String
get() = if (IDManager.isLocalId(_identityModel.onesignalId)) "" else _identityModel.onesignalId

override val externalId: String
get() = _identityModel.externalId ?: ""

val aliases: Map<String, String>
get() = _identityModel.filter { it.key != IdentityModel::id.name }.toMap()

val subscriptions: SubscriptionList
get() = _subscriptionManager.subscriptions

val changeHandlersNotifier = EventProducer<IUserStateObserver>()

override val pushSubscription: IPushSubscription
get() = _subscriptionManager.subscriptions.push

Expand All @@ -42,6 +54,10 @@ internal open class UserManager(
_languageContext.language = value
}

init {
_identityModelStore.subscribe(this)
}

override fun addAlias(
label: String,
id: String,
Expand Down Expand Up @@ -219,4 +235,29 @@ internal open class UserManager(
override fun getTags(): Map<String, String> {
return _propertiesModel.tags.toMap()
}

override fun addObserver(observer: IUserStateObserver) {
changeHandlersNotifier.subscribe(observer)
}

override fun removeObserver(observer: IUserStateObserver) {
changeHandlersNotifier.unsubscribe(observer)
}

override fun onModelReplaced(
model: IdentityModel,
tag: String,
) { }

override fun onModelUpdated(
args: ModelChangedArgs,
tag: String,
) {
if (args.property == IdentityConstants.ONESIGNAL_ID) {
val newUserState = UserState(args.newValue.toString(), externalId)
this.changeHandlersNotifier.fire {
it.onUserStateChange(UserChangedState(newUserState))
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.onesignal.user.state

/**
* A user state changed observer. Implement this interface and provide the implementation
* to be notified when the user state has changed.
*/
interface IUserStateObserver {
/**
* Called when the user state this change handler was added to, has changed. A
* user state can change when user has logged in or out
*
* @param state The user changed state.
*/
fun onUserStateChange(state: UserChangedState)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.onesignal.user.state

import org.json.JSONObject

class UserChangedState(
val current: UserState,
) {
fun toJSONObject(): JSONObject {
return JSONObject()
.put("current", current.toJSONObject())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.onesignal.user.state

import org.json.JSONObject

/**
* A user state.
*/
class UserState(
/**
* The unique identifier for your OneSignal account. This will be an empty string until the
* user has been successfully logged in on the backend and assigned an ID.
* Use [addObserver] to be notified when the [onesignalId] has been successfully assigned.
*/
val onesignalId: String,
/**
* The external identifier that you use to identify users. Use [addObserver] to be notified
* when the [externalId] has been successfully assigned. This will be an empty string if no
* external identifier has been assigned to the associated [onesignalId].
*/
val externalId: String,
) {
fun toJSONObject(): JSONObject {
return JSONObject()
.put("onesignalId", onesignalId)
.put("externalId", externalId)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ object MockHelper {
action(identityModel)
}

val mockIdentityStore = mockk<IdentityModelStore>()
val mockIdentityStore = mockk<IdentityModelStore>(relaxed = true)

every { mockIdentityStore.model } returns identityModel

Expand Down
4 changes: 4 additions & 0 deletions OneSignalSDK/onesignal/notifications/consumer-rules.pro
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
void onPushSubscriptionChange(com.onesignal.user.subscriptions.PushSubscriptionChangedState);
}

-keep class ** implements com.onesignal.user.state.IUserStateObserver {
void onUserStateChange(com.onesignal.user.state.UserChangedState);
}

-keep class ** implements com.onesignal.notifications.INotificationServiceExtension{
void onNotificationReceived(com.onesignal.notifications.INotificationReceivedEvent);
}
Expand Down

0 comments on commit 12ec274

Please sign in to comment.