Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MC-1969 fixes #86

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#if (!UNITY_IOS && !UNITY_ANDROID) || UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Linq;

Expand Down Expand Up @@ -166,13 +167,13 @@ internal static class EventMeta {
internal const string CAMPAIGN = "campaign";
internal const string REF = "ref";
internal const string WZRK_REF = "wzrk_ref";
internal const string DISCARDED_EVENT_JSON_KEY = "d_e";
}

internal static class Validator {
internal const int MAX_KEY_CHARS = 120;
internal const int MAX_VALUE_CHARS = 1024;
internal const int MAX_VALUE_PROPERTY_ARRAY_COUNT = 100;

internal static readonly IReadOnlyList<string> KEY_NOT_ALLOWED_CHARS = new List<string> { ".", ":", "$", "'", "\"", "\\" };
internal static readonly IReadOnlyList<string> VALUE_NOT_ALLOWED_CHARS = new List<string> { "'", "\"", "\\" };

Expand Down Expand Up @@ -216,6 +217,9 @@ internal static class Network {
#endif
internal const string REQUEST_PATH_USER_VARIABLES = "defineVars";
internal const string REQUEST_PATH_HAND_SHAKE = "hello";

internal const string ARP_NAMESPACE_KEY = "ARP:{0}:{1}";
internal const string ARP_KEY = "arp";
}

internal static class Commands {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ internal class UnityNativeEventBuilder {
private UnityNativeDeviceInfo _deviceInfo;
private UnityNativeSessionManager _sessionManager;
private UnityNativeNetworkEngine _networkEngine;

internal UnityNativeEventBuilder(UnityNativeCoreState coreState, UnityNativeNetworkEngine networkEngine) {
private UnityNativeEventValidator _eventValidator;

internal UnityNativeEventBuilder(UnityNativeCoreState coreState, UnityNativeNetworkEngine networkEngine, UnityNativeEventValidator eventValidator) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eventValidator is unused, so it is not needed

_deviceInfo = coreState.DeviceInfo;
_sessionManager = coreState.SessionManager;
_networkEngine = networkEngine;
_eventValidator = eventValidator;
}

internal Dictionary<string, object> BuildEvent(UnityNativeEventType eventType, Dictionary<string, object> eventDetails) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@

namespace CleverTapSDK.Native {
internal class UnityNativeRaisedEventBuilder {
internal UnityNativeRaisedEventBuilder() { }

private UnityNativeEventValidator _eventValidator;
internal UnityNativeRaisedEventBuilder(UnityNativeEventValidator eventValidator)
{
this._eventValidator = eventValidator;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the _eventValidator is not used, currently each method uses a new instance instead of that one. Use the instance _eventValidator or remove it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, reverted it back to last change

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not fixed. You need to use the eventValidator passed from the constructor so it has the discarded events.

}
internal UnityNativeEventBuilderResult<Dictionary<string, object>> Build(string eventName, Dictionary<string, object> properties = null) {
var eventValidator = new UnityNativeEventValidator();
var eventValidationResultsWithErrors = new List<UnityNativeValidationResult>();
Expand All @@ -19,6 +22,12 @@ internal UnityNativeEventBuilderResult<Dictionary<string, object>> Build(string
eventValidationResultsWithErrors.Add(isRestrictedNameValidationResult);
return new UnityNativeEventBuilderResult<Dictionary<string, object>>(eventValidationResultsWithErrors, null);
}

var isDiscardedValidationResult = eventValidator.IsEventDiscarded(eventName);
if (!isDiscardedValidationResult.IsSuccess) {
eventValidationResultsWithErrors.Add(isDiscardedValidationResult);
return new UnityNativeEventBuilderResult<Dictionary<string, object>>(eventValidationResultsWithErrors, null);
}

var cleanEventNameValidationResult = eventValidator.CleanEventName(eventName, out var cleanEventName);
if (!cleanEventNameValidationResult.IsSuccess) {
Expand All @@ -33,12 +42,12 @@ internal UnityNativeEventBuilderResult<Dictionary<string, object>> Build(string
return new UnityNativeEventBuilderResult<Dictionary<string, object>>(eventValidationResultsWithErrors, eventDetails);
}

var cleanObjectDictonaryValidationResult = CleanObjectDictonary(properties);
if (cleanObjectDictonaryValidationResult.ValidationResults.Any(vr => !vr.IsSuccess)) {
eventValidationResultsWithErrors.AddRange(cleanObjectDictonaryValidationResult.ValidationResults.Where(vr => !vr.IsSuccess));
var cleanObjectDictionaryValidationResult = CleanObjectDictonary(properties);
if (cleanObjectDictionaryValidationResult.ValidationResults.Any(vr => !vr.IsSuccess)) {
eventValidationResultsWithErrors.AddRange(cleanObjectDictionaryValidationResult.ValidationResults.Where(vr => !vr.IsSuccess));
}

eventDetails.Add(UnityNativeConstants.Event.EVENT_DATA, cleanObjectDictonaryValidationResult.EventResult);
eventDetails.Add(UnityNativeConstants.Event.EVENT_DATA, cleanObjectDictionaryValidationResult.EventResult);

return new UnityNativeEventBuilderResult<Dictionary<string, object>>(eventValidationResultsWithErrors, eventDetails);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using CleverTapSDK.Native;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove unused namespace.

using CleverTapSDK.Utilities;

#if (!UNITY_IOS && !UNITY_ANDROID) || UNITY_EDITOR
namespace CleverTapSDK.Native
{
internal class UnityNativeARPResponseInterceptor : IUnityNativeResponseInterceptor
{
private readonly UnityNativeEventValidator _eventValidator;
private readonly string _accountId;
private readonly string _namespaceARPKey;
public UnityNativeARPResponseInterceptor(string accountId,string deviceId, UnityNativeEventValidator eventValidator)
{
this._accountId = accountId;
this._namespaceARPKey = string.Format(UnityNativeConstants.Network.ARP_NAMESPACE_KEY,accountId,deviceId);
_eventValidator = eventValidator;
}

UnityNativeResponse IUnityNativeResponseInterceptor.Intercept(UnityNativeResponse response)
{
var result = Json.Deserialize(response.Content) as Dictionary<string, object>;
try
{
if (result.ContainsKey("arp"))
if (Json.Deserialize(result["arp"].ToString()) is Dictionary<string, object> { Count: > 0 } arp)
{
//Handle Discarded events in ARP
try
{
ProcessDiscardedEventsList(arp);
}
catch (Exception t)
{
CleverTapLogger.Log("Failed to process ARP discarded events");
}

HandleARPUpdate(arp);
}
}
catch (Exception exception)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 'exception' variable is not used. Please log the exception details.

{
CleverTapLogger.Log("Failed to process ARP");
}

return response;
}


private void HandleARPUpdate(Dictionary<string, object> arp)
{
if (arp == null || arp.Count == 0 || string.IsNullOrEmpty(_namespaceARPKey))
return;

UnityNativePreferenceManager preferenceManager = UnityNativePreferenceManager.GetPreferenceManager(_accountId);
Dictionary<string, object> currentARP = Json.Deserialize(preferenceManager.GetString(_namespaceARPKey, "{}")) as Dictionary<string, object>;

if (currentARP == null || currentARP.Count == 0)
{
preferenceManager.SetString(_namespaceARPKey, Json.Serialize(arp));
return;
}

foreach (var keyValuePair in arp)
{
string key = keyValuePair.Key;
object value = keyValuePair.Value;

switch (value)
{
case int i:
currentARP[key] = i;
break;
case long l:
currentARP[key] = l;
break;
case float f:
currentARP[key] = f;
break;
case double d:
currentARP[key] = d;
break;
case string s:
currentARP[key] = s;
break;
case bool b:
currentARP[key] = b;
break;
default:
CleverTapLogger.Log($"ARP update for key {key} rejected (invalid data type)");
break;
}
}

preferenceManager.SetString(_namespaceARPKey, Json.Serialize(currentARP));
}


private void ProcessDiscardedEventsList(Dictionary<string, object> response)
{
if (!response.ContainsKey(UnityNativeConstants.EventMeta.DISCARDED_EVENT_JSON_KEY))
{
CleverTapLogger.Log("ARP doesn't contain the Discarded Events key");
return;
}

try
{
var discardedEventsList = new List<string>();
// Get the discarded event JSON from the response
string discardedEventsJson = response[UnityNativeConstants.EventMeta.DISCARDED_EVENT_JSON_KEY].ToString();
var discardedEventsArray = Json.Deserialize(discardedEventsJson) as List<string>;
if (discardedEventsArray != null)
{
discardedEventsList.AddRange(discardedEventsArray);
}
if (_eventValidator != null)
_eventValidator.SetDiscardedEvents(discardedEventsList);
else
CleverTapLogger.Log("Validator object is NULL");
}
catch (Exception e)
{
CleverTapLogger.Log("Error parsing discarded events list" + e.StackTrace);
}
}
}
}
#endif

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ internal abstract class UnityNativeBaseEventQueue

protected UnityNativeCoreState coreState;
protected UnityNativeNetworkEngine networkEngine;

protected UnityNativeEventValidator eventValidator;
private Coroutine timerCoroutine;

internal UnityNativeBaseEventQueue(UnityNativeCoreState coreState, UnityNativeNetworkEngine networkEngine, int queueLimit = 49, int defaultTimerInterval = 1)
internal UnityNativeBaseEventQueue(UnityNativeCoreState coreState, UnityNativeNetworkEngine networkEngine,UnityNativeEventValidator eventValidator, int queueLimit = 49, int defaultTimerInterval = 1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eventValidator is not needed since it is unused.

{
this.coreState = coreState;
this.networkEngine = networkEngine;
this.eventValidator = eventValidator;
this.queueLimit = queueLimit;
this.defaultTimerInterval = defaultTimerInterval;
eventsQueue = new Queue<List<UnityNativeEvent>>();
Expand Down Expand Up @@ -163,7 +164,7 @@ internal Dictionary<string, object> BuildMeta()
{
{ UnityNativeConstants.EventMeta.GUID, deviceInfo.DeviceId },
{ UnityNativeConstants.EventMeta.TYPE, UnityNativeConstants.EventMeta.TYPE_NAME },
{ UnityNativeConstants.EventMeta.APPLICATION_FIELDS, new UnityNativeEventBuilder(coreState, networkEngine).BuildAppFields() },
{ UnityNativeConstants.EventMeta.APPLICATION_FIELDS, new UnityNativeEventBuilder(coreState, networkEngine,eventValidator).BuildAppFields() },
{ UnityNativeConstants.EventMeta.ACCOUNT_ID, accountInfo.AccountId },
{ UnityNativeConstants.EventMeta.ACCOUNT_TOKEN, accountInfo.AccountToken },
{ UnityNativeConstants.EventMeta.FIRST_REQUEST_IN_SESSION, coreState.SessionManager.IsFirstSession() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ internal class UnityNativeRaisedEventQueue : UnityNativeBaseEventQueue {

protected override string QueueName => "RAISED_EVENTS";

internal UnityNativeRaisedEventQueue(UnityNativeCoreState coreState, UnityNativeNetworkEngine networkEngine, int queueLimit = 49, int defaultTimerInterval = 1) : base(coreState, networkEngine, queueLimit, defaultTimerInterval) { }
internal UnityNativeRaisedEventQueue(UnityNativeCoreState coreState, UnityNativeNetworkEngine networkEngine, UnityNativeEventValidator eventValidator, int queueLimit = 49, int defaultTimerInterval = 1) :
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The eventValidator seems unused here. Why do we need it?

base(coreState, networkEngine,eventValidator, queueLimit, defaultTimerInterval) { }

protected override string RequestPath => UnityNativeConstants.Network.REQUEST_PATH_RECORD;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ internal UnityNativeSession(string accountId) {
_lastSessionLength = lastSessionTime - lastSessionId;
}

_preferenceManager.SetLong(UnityNativeConstants.Session.SESSION_ID_KEY, _sessionId);
_preferenceManager.SetLong(UnityNativeConstants.Session.SESSION_ID_KEY, _sessionId.ToString());
}

internal long SessionId => _sessionId;
Expand All @@ -46,7 +46,7 @@ internal void SetIsAppLaunched(bool isAppLaunched) {

internal long UpdateTimestamp() {
long now = GetNow();
_preferenceManager.SetLong(UnityNativeConstants.Session.LAST_SESSION_TIME_KEY, now);
_preferenceManager.SetLong(UnityNativeConstants.Session.LAST_SESSION_TIME_KEY, now.ToString());
_lastUpdateTimestamp = now;
return _lastUpdateTimestamp;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ internal class UnityNativeUserEventQueue : UnityNativeBaseEventQueue {

protected override string QueueName => "USER_EVENTS";

internal UnityNativeUserEventQueue(UnityNativeCoreState coreState, UnityNativeNetworkEngine networkEngine, int queueLimit = 49, int defaultTimerInterval = 1) : base(coreState, networkEngine, queueLimit, defaultTimerInterval) { }
internal UnityNativeUserEventQueue(UnityNativeCoreState coreState, UnityNativeNetworkEngine networkEngine, UnityNativeEventValidator eventValidator, int queueLimit = 49, int defaultTimerInterval = 1) : base(coreState, networkEngine, eventValidator, queueLimit, defaultTimerInterval) { }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eventValidor is unused, remove it.


protected override string RequestPath => UnityNativeConstants.Network.REQUEST_PATH_RECORD;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#if (!UNITY_IOS && !UNITY_ANDROID) || UNITY_EDITOR
namespace CleverTapSDK.Native {
internal class UnityNativeValidationResult {
public class UnityNativeValidationResult {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did this need to be public?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not fixed.

// TODO : Consider converting errorCode into appropriate enumration(Enum)

private readonly int? _errorCode;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#if (!UNITY_IOS && !UNITY_ANDROID) || UNITY_EDITOR
using CleverTapSDK.Common;
using CleverTapSDK.Common;
using CleverTapSDK.Utilities;
using System;
using System.Collections;
Expand All @@ -18,6 +18,7 @@ internal class UnityNativeEventManager {
private UnityNativeCallbackHandler _callbackHandler;
private UnityNativeCoreState _coreState;
private UnityNativeNetworkEngine _networkEngine;
private UnityNativeEventValidator _eventValidator;
private string _accountId;
private int _enableNetworkInfoReporting = -1;

Expand All @@ -33,10 +34,19 @@ private void Initialize(string accountId, string token, string region = null)

_preferenceManager = UnityNativePreferenceManager.GetPreferenceManager(_accountId);
_databaseStore = new UnityNativeDatabaseStore($"{_accountId}_{NATIVE_EVENTS_DB_CACHE}");
_networkEngine = UnityNativeNetworkEngine.Create(_accountId);
_eventQueueManager = new UnityNativeEventQueueManager(_coreState, _networkEngine, _databaseStore);
_eventValidator = new UnityNativeEventValidator();
_networkEngine = UnityNativeNetworkEngine.Create(_coreState);
SetResponseInterceptors();
_eventQueueManager = new UnityNativeEventQueueManager(_coreState, _networkEngine, _databaseStore,_eventValidator);
}

private void SetResponseInterceptors()
{
List<IUnityNativeResponseInterceptor> responseInterceptors = new List<IUnityNativeResponseInterceptor>();
responseInterceptors.Add(new UnityNativeARPResponseInterceptor(_accountId,_coreState.DeviceInfo.DeviceId,_eventValidator));
_networkEngine.SetResponseInterceptors(responseInterceptors);
}

#region Launch

internal void LaunchWithCredentials(string accountId, string token, string region = null) {
Expand Down Expand Up @@ -170,6 +180,7 @@ private void SwitchOrCreateProfile(Dictionary<string, object> profile, string ca
_coreState.DeviceInfo.ForceNewDeviceID();
}

SetResponseInterceptors();
nzagorchev marked this conversation as resolved.
Show resolved Hide resolved
NotifyUserProfileInitialized();

RecordAppLaunch();
Expand Down Expand Up @@ -290,7 +301,7 @@ internal UnityNativeEvent RecordEvent(string eventName, Dictionary<string, objec
return null;
}

var eventBuilderResult = new UnityNativeRaisedEventBuilder().Build(eventName, properties);
var eventBuilderResult = new UnityNativeRaisedEventBuilder(_eventValidator).Build(eventName, properties);
var eventDetails = eventBuilderResult.EventResult;
return BuildEvent(UnityNativeEventType.RaisedEvent, eventDetails);
}
Expand All @@ -304,7 +315,7 @@ internal UnityNativeEvent RecordChargedEventWithDetailsAndItems(Dictionary<strin
return null;
}

var eventBuilderResult = new UnityNativeRaisedEventBuilder().BuildChargedEvent(details, items);
var eventBuilderResult = new UnityNativeRaisedEventBuilder(_eventValidator).BuildChargedEvent(details, items);
var eventDetails = eventBuilderResult.EventResult;
return BuildEvent(UnityNativeEventType.RaisedEvent, eventDetails);
}
Expand All @@ -331,7 +342,7 @@ private IEnumerator DeferEventCoroutine(Action action) {
}

private UnityNativeEvent BuildEvent(UnityNativeEventType eventType, Dictionary<string, object> eventDetails, bool storeEvent = true) {
var eventData = new UnityNativeEventBuilder(_coreState, _networkEngine).BuildEvent(eventType, eventDetails);
var eventData = new UnityNativeEventBuilder(_coreState, _networkEngine,_eventValidator).BuildEvent(eventType, eventDetails);
var eventDataJSONContent = Json.Serialize(eventData);
var @event = new UnityNativeEvent(eventType, eventDataJSONContent);
if (storeEvent)
Expand All @@ -342,7 +353,7 @@ private UnityNativeEvent BuildEvent(UnityNativeEventType eventType, Dictionary<s
}

private UnityNativeEvent BuildEventWithAppFields(UnityNativeEventType eventType, Dictionary<string, object> eventDetails, bool storeEvent = true) {
var eventData = new UnityNativeEventBuilder(_coreState, _networkEngine).BuildEventWithAppFields(eventType, eventDetails);
var eventData = new UnityNativeEventBuilder(_coreState, _networkEngine,_eventValidator).BuildEventWithAppFields(eventType, eventDetails);
var eventDataJSONContent = Json.Serialize(eventData);
var @event = new UnityNativeEvent(eventType, eventDataJSONContent);
if (storeEvent)
Expand Down
Loading