diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/AbstractBaseService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/AbstractBaseService.cs deleted file mode 100644 index 5e15e9028..000000000 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/AbstractBaseService.cs +++ /dev/null @@ -1,148 +0,0 @@ - -using System; -using System.Collections; -using System.Collections.Generic; -using Plugins.CountlySDK.Enums; -using Plugins.CountlySDK.Models; - -namespace Plugins.CountlySDK.Services -{ - public abstract class AbstractBaseService - { - internal object LockObj { get; set; } - internal List Listeners { get; set; } - - protected CountlyLogHelper Log { get; private set; } - protected readonly CountlyConfiguration _configuration; - protected readonly ConsentCountlyService _consentService; - - - protected AbstractBaseService(CountlyConfiguration configuration, CountlyLogHelper logHelper, ConsentCountlyService consentService) - { - Log = logHelper; - _configuration = configuration; - _consentService = consentService; - } - - protected IDictionary RemoveSegmentInvalidDataTypes(IDictionary segments) - { - - if (segments == null || segments.Count == 0) - { - return segments; - } - - string moduleName = GetType().Name; - int i = 0; - List toRemove = new List(); - foreach (KeyValuePair item in segments) - { - if (++i > _configuration.MaxSegmentationValues) - { - toRemove.Add(item.Key); - continue; - } - Type type = item.Value?.GetType(); - bool isValidDataType = item.Value != null - && (type == typeof(int) - || type == typeof(bool) - || type == typeof(float) - || type == typeof(double) - || type == typeof(string)); - - - if (!isValidDataType) - { - toRemove.Add(item.Key); - Log.Warning("[" + moduleName + "] RemoveSegmentInvalidDataTypes: In segmentation Data type '" + type + "' of item '" + item.Key + "' isn't valid."); - } - } - - foreach (string k in toRemove) - { - segments.Remove(k); - } - - return segments; - } - - protected string TrimKey(string k) - { - if (k.Length > _configuration.MaxKeyLength) - { - Log.Warning("[" + GetType().Name + "] TrimKey : Max allowed key length is " + _configuration.MaxKeyLength + ". " + k + " will be truncated."); - k = k.Substring(0, _configuration.MaxKeyLength); - } - - return k; - } - - protected string[] TrimValues(string[] values) - { - for (int i = 0; i < values.Length; ++i) - { - if (values[i].Length > _configuration.MaxValueSize) - { - Log.Warning("[" + GetType().Name + "] TrimKey : Max allowed value length is " + _configuration.MaxKeyLength + ". " + values[i] + " will be truncated."); - values[i] = values[i].Substring(0, _configuration.MaxValueSize); - } - } - - - return values; - } - - protected string TrimValue(string fieldName, string v) - { - if (v != null && v.Length > _configuration.MaxValueSize) - { - Log.Warning("[" + GetType().Name + "] TrimValue : Max allowed '" + fieldName + "' length is " + _configuration.MaxValueSize + ". " + v + " will be truncated."); - v = v.Substring(0, _configuration.MaxValueSize); - } - - return v; - } - - protected IDictionary FixSegmentKeysAndValues(IDictionary segments) - { - if (segments == null || segments.Count == 0) - { - return segments; - } - - IDictionary segmentation = new Dictionary(); - foreach (KeyValuePair item in segments) - { - string k = item.Key; - object v = item.Value; - - if (k == null || k.Length == 0 || v == null) - { - continue; - } - - k = TrimKey(k); - - if (v.GetType() == typeof(string)) - { - v = TrimValue(k, (string)v); - } - - segmentation.Add(k, v); - } - - return segmentation; - } - internal virtual void OnInitializationCompleted() { } - internal virtual void DeviceIdChanged(string deviceId, bool merged) { } - internal virtual void ConsentChanged(List updatedConsents, bool newConsentValue, ConsentChangedAction action) { } - } - - internal enum ConsentChangedAction - { - Initialization, - ConsentUpdated, - DeviceIDChangedNotMerged, - } - -} diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ViewCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ViewCountlyService.cs deleted file mode 100644 index 44aba129a..000000000 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ViewCountlyService.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Plugins.CountlySDK.Enums; -using Plugins.CountlySDK.Helpers; -using Plugins.CountlySDK.Models; -using UnityEngine; - -namespace Plugins.CountlySDK.Services -{ - - public class ViewCountlyService : AbstractBaseService - { - internal bool _isFirstView = true; - internal readonly EventCountlyService _eventService; - private readonly Dictionary _viewToLastViewStartTime = new Dictionary(); - - internal ViewCountlyService(CountlyConfiguration configuration, CountlyLogHelper logHelper, EventCountlyService eventService, ConsentCountlyService consentService) : base(configuration, logHelper, consentService) - { - Log.Debug("[ViewCountlyService] Initializing."); - - _eventService = eventService; - } - /// - /// Start tracking a view - /// - /// name of the view - /// - public async Task RecordOpenViewAsync(string name, IDictionary segmentation = null) - { - lock (LockObj) - { - Log.Info("[ViewCountlyService] RecordOpenViewAsync : name = " + name); - - if (!_consentService.CheckConsentInternal(Consents.Views)) - { - return; - } - - if (string.IsNullOrEmpty(name)) - { - return; - } - - if (name.Length > _configuration.MaxKeyLength) - { - Log.Verbose("[ViewCountlyService] RecordOpenViewAsync : Max allowed key length is " + _configuration.MaxKeyLength); - name = name.Substring(0, _configuration.MaxKeyLength); - } - - IDictionary openViewSegment = new Dictionary - { - {"name", name}, - {"segment", _configuration.metricHelper.OS}, - {"visit", 1}, - {"start", _isFirstView ? 1 : 0} - }; - - if (segmentation != null) - { - segmentation = RemoveSegmentInvalidDataTypes(segmentation); - segmentation = FixSegmentKeysAndValues(segmentation); - - foreach (KeyValuePair item in openViewSegment) - { - segmentation[item.Key] = item.Value; - } - } - else - { - segmentation = openViewSegment; - } - - if (!_viewToLastViewStartTime.ContainsKey(name)) - { - _viewToLastViewStartTime.Add(name, DateTime.UtcNow); - } - - CountlyEventModel currentView = new CountlyEventModel(CountlyEventModel.ViewEvent, segmentation); - _ = _eventService.RecordEventAsync(currentView); - - _isFirstView = false; - } - - await Task.CompletedTask; - } - - /// - /// Stop tracking a view - /// - /// - /// - //TODO: this performs in a non standard way. It should only be possible to close started views. - public async Task RecordCloseViewAsync(string name) - { - lock (LockObj) - { - Log.Info("[ViewCountlyService] RecordCloseViewAsync : name = " + name); - - if (!_consentService.CheckConsentInternal(Consents.Views)) - { - return; - } - - if (string.IsNullOrEmpty(name)) - { - return; - } - - if (name.Length > _configuration.MaxKeyLength) - { - Log.Verbose("[ViewCountlyService] RecordCloseViewAsync : Max allowed key length is " + _configuration.MaxKeyLength); - name = name.Substring(0, _configuration.MaxKeyLength); - } - - double? duration = null; - if (_viewToLastViewStartTime.ContainsKey(name)) - { - DateTime lastViewStartTime = _viewToLastViewStartTime[name]; - duration = (DateTime.UtcNow - lastViewStartTime).TotalSeconds; - - _viewToLastViewStartTime.Remove(name); - } - - IDictionary segment = new Dictionary - { - {"name", name}, - {"segment", _configuration.metricHelper.OS}, - }; - - CountlyEventModel currentView = new CountlyEventModel(CountlyEventModel.ViewEvent, segment, 1, null, duration); - _ = _eventService.RecordEventAsync(currentView); - } - await Task.CompletedTask; - } - - /// - /// Reports a particular action with the specified details - /// - /// type of action - /// x-coordinate - /// y-coordinate - /// width of screen - /// height of screen - /// - public async Task ReportActionAsync(string type, int x, int y, int width, int height) - { - lock (LockObj) - { - Log.Info("[ViewCountlyService] ReportActionAsync : type = " + type + ", x = " + x + ", y = " + y + ", width = " + width + ", height = " + height); - - if (!_consentService.CheckConsentInternal(Consents.Views)) - { - return; - } - - IDictionary segmentation = new Dictionary() - { - {"type", type}, - {"x", x}, - {"y", y}, - {"width", width}, - {"height", height}, - }; - CountlyEventModel currentView = new CountlyEventModel(CountlyEventModel.ViewActionEvent, segmentation); - _ = _eventService.RecordEventAsync(currentView); - } - await Task.CompletedTask; - } - - #region override Methods - internal override void DeviceIdChanged(string deviceId, bool merged) - { - if (!merged) - { - _isFirstView = true; - } - } - #endregion - } -} diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly.meta similarity index 77% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly.meta index 7ccafd0bb..f1093217a 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK.meta +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: eccff01d26db53b4da2d8e958649e328 +guid: 3b482047f13654c10b389c5670c49dc0 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/License.txt b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/License.txt similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/License.txt rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/License.txt diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/License.txt.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/License.txt.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/License.txt.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/License.txt.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins.meta similarity index 77% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins.meta index b3bb7b179..04fb824c9 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins.meta +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 17a4891e2ac5143718a9a27286d2e60e +guid: 2e22156c8cc414bce86eab1672f91139 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/AndroidManifest.xml b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/AndroidManifest.xml similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/AndroidManifest.xml rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/AndroidManifest.xml diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/AndroidManifest.xml.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/AndroidManifest.xml.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/AndroidManifest.xml.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/AndroidManifest.xml.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/build.gradle b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/build.gradle similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/build.gradle rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/build.gradle diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/build.gradle.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/build.gradle.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/build.gradle.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/build.gradle.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/libs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/libs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/libs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/libs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/libs/countly_notifications.jar b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/libs/countly_notifications.jar similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/libs/countly_notifications.jar rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/libs/countly_notifications.jar diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/libs/countly_notifications.jar.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/libs/countly_notifications.jar.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/libs/countly_notifications.jar.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/libs/countly_notifications.jar.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/project.properties b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/project.properties similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/project.properties rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/project.properties diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/project.properties.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/project.properties.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/project.properties.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/project.properties.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-hdpi.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-hdpi.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-hdpi.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-hdpi.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-hdpi/ic_stat.png b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-hdpi/ic_stat.png similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-hdpi/ic_stat.png rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-hdpi/ic_stat.png diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-hdpi/ic_stat.png.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-hdpi/ic_stat.png.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-hdpi/ic_stat.png.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-hdpi/ic_stat.png.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-mdpi.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-mdpi.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-mdpi.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-mdpi.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-mdpi/ic_stat.png b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-mdpi/ic_stat.png similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-mdpi/ic_stat.png rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-mdpi/ic_stat.png diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-mdpi/ic_stat.png.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-mdpi/ic_stat.png.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-mdpi/ic_stat.png.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-mdpi/ic_stat.png.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xhdpi.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xhdpi.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xhdpi.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xhdpi.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xhdpi/ic_stat.png b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xhdpi/ic_stat.png similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xhdpi/ic_stat.png rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xhdpi/ic_stat.png diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xhdpi/ic_stat.png.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xhdpi/ic_stat.png.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xhdpi/ic_stat.png.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xhdpi/ic_stat.png.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxhdpi.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxhdpi.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxhdpi.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxhdpi.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxhdpi/ic_stat.png b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxhdpi/ic_stat.png similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxhdpi/ic_stat.png rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxhdpi/ic_stat.png diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxhdpi/ic_stat.png.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxhdpi/ic_stat.png.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxhdpi/ic_stat.png.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxhdpi/ic_stat.png.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxxhdpi.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxxhdpi.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxxhdpi.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxxhdpi.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxxhdpi/ic_stat.png b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxxhdpi/ic_stat.png similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxxhdpi/ic_stat.png rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxxhdpi/ic_stat.png diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxxhdpi/ic_stat.png.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxxhdpi/ic_stat.png.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/drawable-xxxhdpi/ic_stat.png.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/drawable-xxxhdpi/ic_stat.png.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/raw.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/raw.meta new file mode 100644 index 000000000..c90e8bbab --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/raw.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 074b7b48bb5f5d94db4dcad18f50ec23 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/colors.xml b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/colors.xml similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/colors.xml rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/colors.xml diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/colors.xml.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/colors.xml.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/colors.xml.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/colors.xml.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/google-services.xml b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/google-services.xml similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/google-services.xml rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/google-services.xml diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/google-services.xml.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/google-services.xml.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/google-services.xml.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/google-services.xml.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/strings.xml b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/strings.xml similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/strings.xml rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/strings.xml diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/strings.xml.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/strings.xml.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Android/Notifications/res/values/strings.xml.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Android/Notifications/res/values/strings.xml.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/PluginAssembly.asmdef b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Countly.Core.asmdef similarity index 90% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/PluginAssembly.asmdef rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Countly.Core.asmdef index efc01cdc4..565607b2e 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/PluginAssembly.asmdef +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Countly.Core.asmdef @@ -1,5 +1,5 @@ { - "name": "PluginAssembly", + "name": "Countly.Core", "references": [], "includePlatforms": [], "excludePlatforms": [], diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/PluginAssembly.asmdef.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Countly.Core.asmdef.meta similarity index 76% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/PluginAssembly.asmdef.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Countly.Core.asmdef.meta index 5664a3aba..e86978203 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/PluginAssembly.asmdef.meta +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Countly.Core.asmdef.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1e69005fbbf5a4cd0a6c61596a74886e +guid: 097393a5382fd4a89a5a9de92743d1db AssemblyDefinitionImporter: externalObjects: {} userData: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Countly.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Countly.cs similarity index 58% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Countly.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Countly.cs index 27f34c1e0..fc518890f 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Countly.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Countly.cs @@ -13,62 +13,37 @@ using Plugins.iBoxDB; using UnityEngine; using Plugins.CountlySDK.Enums; +#pragma warning disable CS0618 [assembly: InternalsVisibleTo("PlayModeTests")] namespace Plugins.CountlySDK { public class Countly : MonoBehaviour { - //SDK limit defaults - internal const int MaxKeyLengthDefault = 128; - internal const int MaxValueSizeDefault = 256; - internal const int MaxSegmentationValuesDefault = 100; - internal const int MaxBreadcrumbCountDefault = 100; - internal const int MaxStackTraceLinesPerThreadDefault = 30; - internal const int MaxStackTraceLineLengthDefault = 200; - internal const int MaxStackTraceThreadCountDefault = 30; - - public CountlyAuthModel Auth; - public CountlyConfigModel Config; - internal RequestCountlyHelper RequestHelper; - internal CountlyConfiguration Configuration; - - /// - /// Check if SDK has been initialized. - /// - /// bool - public bool IsSDKInitialized { get; private set; } - - private CountlyLogHelper _logHelper; - private static Countly _instance = null; - internal StorageAndMigrationHelper StorageHelper; - internal readonly object lockObj = new object(); - private List _listeners = new List(); - /// - /// Return countly shared instance. + /// Return Countly shared instance. /// /// Countly public static Countly Instance { - get - { - if (_instance == null) - { - + get { + if (_instance == null) { GameObject gameObject = new GameObject("_countly"); _instance = gameObject.AddComponent(); } - return _instance; - } - internal set - { + internal set { _instance = value; } } + /// + /// Check if SDK has been initialized. + /// + /// bool + public bool IsSDKInitialized { get; private set; } + /// /// Check/Update consent for a particular feature. /// @@ -93,8 +68,6 @@ internal set /// EventCountlyService public EventCountlyService Events { get; private set; } - internal InitializationCountlyService Initialization { get; private set; } - /// /// Exposes functionality to set location parameters. /// @@ -117,26 +90,48 @@ internal set /// Exposes functionality to set and change custom user properties and interact with custom property modifiers. /// /// UserDetailsCountlyService + [Obsolete("UserDetailsCountlyService is deprecated and will be removed in the future. Please use UserProfile instead.")] public UserDetailsCountlyService UserDetails { get; private set; } /// - /// Exposes functionality to start and stop recording views and report positions for heat-map. + /// Exposes functionality for managing view lifecycle with segmentation options. Includes global view segmentation and adding segmentation to ongoing views. /// - /// ViewCountlyService - public ViewCountlyService Views { get; private set; } + public IViewModule Views { get; private set; } - public MetricHelper MetricHelper { get; private set; } - internal SessionCountlyService Session { get; set; } + /// + /// Exposes functionality to set and change custom user properties and interact with custom property modifiers. + /// + public IUserProfileModule UserProfile { get; private set; } /// /// Add callbacks to listen to push notification events for when a notification is received and when it is clicked. /// /// NotificationsCallbackService public NotificationsCallbackService Notifications { get; set; } - + public CountlyAuthModel Auth; + public CountlyConfigModel Config; + internal SessionCountlyService Session { get; set; } + internal InitializationCountlyService Initialization { get; private set; } + internal RequestCountlyHelper RequestHelper; + internal CountlyConfiguration Configuration; + internal StorageAndMigrationHelper StorageHelper; + internal readonly object lockObj = new object(); private bool _logSubscribed; + private List _listeners = new List(); + private CountlyLogHelper _logHelper; + private static Countly _instance = null; private PushCountlyService _push; + private CountlyMainThreadHandler countlyMainThreadHandler; + #region SDK limit defaults + internal const int MaxKeyLengthDefault = 128; + internal const int MaxValueSizeDefault = 256; + internal const int MaxSegmentationValuesDefault = 100; + internal const int MaxBreadcrumbCountDefault = 100; + internal const int MaxStackTraceLinesPerThreadDefault = 30; + internal const int MaxStackTraceLineLengthDefault = 200; + internal const int MaxStackTraceThreadCountDefault = 30; + #endregion /// /// Initialize SDK at the start of your app @@ -145,189 +140,169 @@ private void Awake() { DontDestroyOnLoad(gameObject); Instance = this; - + countlyMainThreadHandler = CountlyMainThreadHandler.Instance; //Auth and Config will not be null in case initializing through countly prefab - if (Auth != null && Config != null) - { + if (Auth != null && Config != null) { Init(new CountlyConfiguration(Auth, Config)); } - } public void Init(CountlyConfiguration configuration) { - if (IsSDKInitialized) - { - _logHelper.Error("SDK has already been initialized, 'Init' should not be called a second time!"); + // Check if the current thread is the main thread + if (countlyMainThreadHandler.IsMainThread()) { + // If on the main thread, initialize directly + InitInternal(configuration); + } else { + // If not on the main thread, schedule initialization on the main thread + // This ensures that SDK is initialized on the main thread + countlyMainThreadHandler.RunOnMainThread(() => { InitInternal(configuration); }); + + // Avoid potential issues with SDK initialization on non-main threads + Debug.LogWarning("[Countly][Init] Initialization process is being moved to the main thread. Ensure this is intended behavior."); + } + } + + public void InitInternal(CountlyConfiguration configuration) + { + if (IsSDKInitialized) { + _logHelper.Error("[Countly][InitInternal] SDK has already been initialized, 'Init' should not be called a second time!"); return; } Configuration = configuration; _logHelper = new CountlyLogHelper(Configuration); - - _logHelper.Info("[Init] Initializing Countly [SdkName: " + Constants.SdkName + " SdkVersion: " + Constants.SdkVersion + "]"); - + _logHelper.Info("[Countly][InitInternal] Initializing Countly [SdkName: " + Constants.SdkName + " SdkVersion: " + Constants.SdkVersion + "]"); configuration.metricHelper = new MetricHelper(configuration.overridenMetrics); - if (configuration.Parent != null) - { + if (configuration.Parent != null) { transform.parent = configuration.Parent.transform; } - if (string.IsNullOrEmpty(configuration.ServerUrl)) - { - throw new ArgumentNullException(configuration.ServerUrl, "Server URL is required."); + if (string.IsNullOrEmpty(configuration.GetServerUrl())) { + throw new ArgumentNullException(configuration.GetServerUrl(), "Server URL is required."); } - if (string.IsNullOrEmpty(configuration.AppKey)) - { - throw new ArgumentNullException(configuration.AppKey, "App Key is required."); + if (string.IsNullOrEmpty(configuration.GetAppKey())) { + throw new ArgumentNullException(configuration.GetAppKey(), "App Key is required."); } - if (configuration.ServerUrl[configuration.ServerUrl.Length - 1] == '/') - { - configuration.ServerUrl = configuration.ServerUrl.Remove(configuration.ServerUrl.Length - 1); + if (configuration.GetServerUrl()[configuration.GetServerUrl().Length - 1] == '/') { + configuration.ServerUrl = configuration.GetServerUrl().Remove(configuration.GetServerUrl().Length - 1); } - _logHelper.Debug("[Init] SDK initialized with the URL:[" + configuration.ServerUrl + "] and the appKey:[" + configuration.AppKey + "]"); - + _logHelper.Debug("[Countly][InitInternal] SDK initialized with the URL:[" + configuration.GetServerUrl() + "] and the appKey:[" + configuration.GetAppKey() + "]"); - if (configuration.SessionDuration < 1) - { - _logHelper.Error("[Init] provided session duration is less than 1. Replacing it with 1."); - configuration.SessionDuration = 1; + if (configuration.GetUpdateSessionTimerDelay() < 1) { + _logHelper.Error("[Countly][InitInternal] provided session duration is less than 1. Replacing it with 1."); + configuration.SetUpdateSessionTimerDelay(1); } - _logHelper.Debug("[Init] session duration set to [" + configuration.SessionDuration + "]"); + _logHelper.Debug("[Countly][InitInternal] session duration set to [" + configuration.GetUpdateSessionTimerDelay() + "]"); - if (configuration.EnablePost) - { - _logHelper.Debug("[Init] Setting HTTP POST to be forced"); + if (configuration.IsForcedHttpPostEnabled()) { + _logHelper.Debug("[Countly][InitInternal] Setting HTTP POST to be forced"); } - if (configuration.Salt != null) - { - _logHelper.Debug("[Init] Enabling tamper protection"); + if (configuration.GetParameterTamperingProtectionSalt() != null) { + _logHelper.Debug("[Countly][InitInternal] Enabling tamper protection"); } - if (configuration.NotificationMode != TestMode.None) - { - _logHelper.Debug("[Init] Enabling push notification"); + if (configuration.GetNotificationMode() != TestMode.None) { + _logHelper.Debug("[Countly][InitInternal] Enabling push notification"); } - if (configuration.EnableTestMode) - { - _logHelper.Warning("[Init] Enabling test mode"); + if (configuration.EnableTestMode) { + _logHelper.Warning("[Countly][InitInternal] Enabling test mode"); } - if (configuration.EnableAutomaticCrashReporting) - { - _logHelper.Debug("[Init] Enabling automatic crash reporting"); + if (configuration.IsAutomaticCrashReportingEnabled()) { + _logHelper.Debug("[Countly][InitInternal] Enabling automatic crash reporting"); } // Have a look at the SDK limit values - if (configuration.EventQueueThreshold < 1) - { - _logHelper.Error("[Init] provided event queue size is less than 1. Replacing it with 1."); - configuration.EventQueueThreshold = 1; + if (configuration.GetEventQueueSizeToSend() < 1) { + _logHelper.Error("[Countly][InitInternal] provided event queue size is less than 1. Replacing it with 1."); + configuration.SetEventQueueSizeToSend(1); } - _logHelper.Debug("[Init] event queue size set to [" + configuration.EventQueueThreshold + "]"); + _logHelper.Debug("[Countly][InitInternal] event queue size set to [" + configuration.GetEventQueueSizeToSend() + "]"); - if (configuration.StoredRequestLimit < 1) - { - _logHelper.Error("[Init] provided request queue size is less than 1. Replacing it with 1."); - configuration.StoredRequestLimit = 1; + if (configuration.GetMaxRequestQueueSize() < 1) { + _logHelper.Error("[Countly][InitInternal] provided request queue size is less than 1. Replacing it with 1."); + configuration.SetMaxRequestQueueSize(1); } - _logHelper.Debug("[Init] request queue size set to [" + configuration.StoredRequestLimit + "]"); + _logHelper.Debug("[Countly][InitInternal] request queue size set to [" + configuration.GetMaxRequestQueueSize() + "]"); - if (configuration.MaxKeyLength != MaxKeyLengthDefault) - { - if (configuration.MaxKeyLength < 1) - { - configuration.MaxKeyLength = 1; - _logHelper.Warning("[Init] provided 'maxKeyLength' is less than '1'. Setting it to '1'."); + if (configuration.GetMaxKeyLength() != MaxKeyLengthDefault) { + if (configuration.GetMaxKeyLength() < 1) { + configuration.SetMaxKeyLength(1); + _logHelper.Warning("[Countly][InitInternal] provided 'maxKeyLength' is less than '1'. Setting it to '1'."); } - _logHelper.Info("[Init] provided 'maxKeyLength' override:[" + configuration.MaxKeyLength + "]"); + _logHelper.Info("[Countly][InitInternal] provided 'maxKeyLength' override:[" + configuration.GetMaxKeyLength() + "]"); } - if (configuration.MaxValueSize != MaxValueSizeDefault) - { - if (configuration.MaxValueSize < 1) - { - configuration.MaxValueSize = 1; - _logHelper.Warning("[Init] provided 'maxValueSize' is less than '1'. Setting it to '1'."); + if (configuration.GetMaxValueSize() != MaxValueSizeDefault) { + if (configuration.GetMaxValueSize() < 1) { + configuration.SetMaxValueSize(1); + _logHelper.Warning("[Countly][InitInternal] provided 'maxValueSize' is less than '1'. Setting it to '1'."); } - _logHelper.Info("[Init] provided 'maxValueSize' override:[" + configuration.MaxValueSize + "]"); + _logHelper.Info("[Countly][InitInternal] provided 'maxValueSize' override:[" + configuration.GetMaxValueSize() + "]"); } - if (configuration.MaxSegmentationValues != MaxSegmentationValuesDefault) - { - if (configuration.MaxSegmentationValues < 1) - { - configuration.MaxSegmentationValues = 1; - _logHelper.Warning("[Init] provided 'maxSegmentationValues' is less than '1'. Setting it to '1'."); + if (configuration.GetMaxSegmentationValues() != MaxSegmentationValuesDefault) { + if (configuration.GetMaxSegmentationValues() < 1) { + configuration.SetMaxSegmentationValues(1); + _logHelper.Warning("[Countly][InitInternal] provided 'maxSegmentationValues' is less than '1'. Setting it to '1'."); } - _logHelper.Info("[Init] provided 'maxSegmentationValues' override:[" + configuration.MaxSegmentationValues + "]"); + _logHelper.Info("[Countly][InitInternal] provided 'maxSegmentationValues' override:[" + configuration.GetMaxSegmentationValues() + "]"); } - if (configuration.TotalBreadcrumbsAllowed != MaxBreadcrumbCountDefault) - { - if (configuration.TotalBreadcrumbsAllowed < 1) - { - configuration.TotalBreadcrumbsAllowed = 1; - _logHelper.Warning("[Init] provided 'maxBreadcrumbCount' is less than '1'. Setting it to '1'."); + if (configuration.GetMaxBreadcrumbCount() != MaxBreadcrumbCountDefault) { + if (configuration.GetMaxBreadcrumbCount() < 1) { + configuration.SetMaxBreadcrumbCount(1); + _logHelper.Warning("[Countly][InitInternal] provided 'maxBreadcrumbCount' is less than '1'. Setting it to '1'."); } - _logHelper.Info("[Init] provided 'maxBreadcrumbCount' override:[" + configuration.TotalBreadcrumbsAllowed + "]"); + _logHelper.Info("[Countly][InitInternal] provided 'maxBreadcrumbCount' override:[" + configuration.GetMaxBreadcrumbCount() + "]"); } - if (configuration.MaxStackTraceLinesPerThread != MaxStackTraceLinesPerThreadDefault) - { - if (configuration.MaxStackTraceLinesPerThread < 1) - { - configuration.MaxStackTraceLinesPerThread = 1; - _logHelper.Warning("[Init] provided 'maxStackTraceLinesPerThread' is less than '1'. Setting it to '1'."); + if (configuration.GetMaxStackTraceLinesPerThread() != MaxStackTraceLinesPerThreadDefault) { + if (configuration.GetMaxStackTraceLinesPerThread() < 1) { + configuration.SetMaxStackTraceLinesPerThread(1); + _logHelper.Warning("[Countly][InitInternal] provided 'maxStackTraceLinesPerThread' is less than '1'. Setting it to '1'."); } - _logHelper.Info("[Init] provided 'maxStackTraceLinesPerThread' override:[" + configuration.MaxStackTraceLinesPerThread + "]"); + _logHelper.Info("[Countly][InitInternal] provided 'maxStackTraceLinesPerThread' override:[" + configuration.GetMaxStackTraceLinesPerThread() + "]"); } - if (configuration.MaxStackTraceLineLength != MaxStackTraceLineLengthDefault) - { - if (configuration.MaxStackTraceLineLength < 1) - { - configuration.MaxStackTraceLineLength = 1; - _logHelper.Warning("[Init] provided 'maxStackTraceLineLength' is less than '1'. Setting it to '1'."); + if (configuration.GetMaxStackTraceLineLength() != MaxStackTraceLineLengthDefault) { + if (configuration.GetMaxStackTraceLineLength() < 1) { + configuration.SetMaxStackTraceLineLength(1); + _logHelper.Warning("[Countly][InitInternal] provided 'maxStackTraceLineLength' is less than '1'. Setting it to '1'."); } - _logHelper.Info("[Init] provided 'maxStackTraceLineLength' override:[" + configuration.MaxStackTraceLineLength + "]"); + _logHelper.Info("[Countly][InitInternal] provided 'maxStackTraceLineLength' override:[" + configuration.GetMaxStackTraceLineLength() + "]"); } - if (configuration.SafeEventIDGenerator == null) - { + if (configuration.SafeEventIDGenerator == null) { configuration.SafeEventIDGenerator = new SafeIDGenerator(); } - if (configuration.SafeViewIDGenerator == null) - { + if (configuration.SafeViewIDGenerator == null) { configuration.SafeViewIDGenerator = new SafeIDGenerator(); } FirstLaunchAppHelper.Process(); - RequestBuilder requestBuilder = new RequestBuilder(); StorageHelper = new StorageAndMigrationHelper(_logHelper, requestBuilder); StorageHelper.OpenDB(); IDictionary migrationParams = new Dictionary() { - {StorageAndMigrationHelper.key_from_2_to_3_custom_id_set, configuration.DeviceId != null }, + {StorageAndMigrationHelper.key_from_2_to_3_custom_id_set, configuration.GetDeviceId() != null }, }; StorageHelper.RunMigration(migrationParams); - Init(requestBuilder, StorageHelper.RequestRepo, StorageHelper.EventRepo, StorageHelper.ConfigDao); - - Device.InitDeviceId(configuration.DeviceId); + Device.InitDeviceId(configuration.GetDeviceId()); OnInitialisationComplete(); - - _logHelper.Debug("[Countly] Finished Initializing SDK."); + _logHelper.Debug("[Countly][InitInternal] Finished Initializing SDK."); } private void Init(RequestBuilder requestBuilder, RequestRepository requestRepo, @@ -335,41 +310,35 @@ private void Init(RequestBuilder requestBuilder, RequestRepository requestRepo, { CountlyUtils countlyUtils = new CountlyUtils(this); RequestHelper = new RequestCountlyHelper(Configuration, _logHelper, countlyUtils, requestBuilder, requestRepo, this); - Consents = new ConsentCountlyService(Configuration, _logHelper, Consents, RequestHelper); - Events = new EventCountlyService(Configuration, _logHelper, RequestHelper, nonViewEventRepo, Consents); - + Events = new EventCountlyService(Configuration, _logHelper, RequestHelper, nonViewEventRepo, Consents, countlyUtils); Location = new Services.LocationService(Configuration, _logHelper, RequestHelper, Consents); Notifications = new NotificationsCallbackService(Configuration, _logHelper); ProxyNotificationsService notificationsService = new ProxyNotificationsService(transform, Configuration, _logHelper, InternalStartCoroutine, Events); _push = new PushCountlyService(Configuration, _logHelper, RequestHelper, notificationsService, Notifications, Consents); Session = new SessionCountlyService(Configuration, _logHelper, Events, RequestHelper, Location, Consents, this); - CrashReports = new CrashReportsCountlyService(Configuration, _logHelper, RequestHelper, Consents); Initialization = new InitializationCountlyService(Configuration, _logHelper, Location, Session, Consents); RemoteConfigs = new RemoteConfigCountlyService(Configuration, _logHelper, RequestHelper, countlyUtils, configDao, Consents, requestBuilder); - StarRating = new StarRatingCountlyService(Configuration, _logHelper, Consents, Events); UserDetails = new UserDetailsCountlyService(Configuration, _logHelper, RequestHelper, countlyUtils, Consents); - Views = new ViewCountlyService(Configuration, _logHelper, Events, Consents); + UserProfile = new UserProfile(this, Configuration, _logHelper, RequestHelper, countlyUtils, Consents, Events); + Views = new ViewCountlyService(this, countlyUtils, Configuration, _logHelper, Events, Consents); Device = new DeviceIdCountlyService(Configuration, _logHelper, Session, RequestHelper, Events, countlyUtils, Consents); CreateListOfIBaseService(); RegisterListenersToServices(); } - private async void OnInitialisationComplete() + private void OnInitialisationComplete() { - lock (lockObj) - { + lock (lockObj) { IsSDKInitialized = true; _ = Initialization.OnInitialisationComplete(); - foreach (AbstractBaseService listener in _listeners) - { + foreach (AbstractBaseService listener in _listeners) { listener.OnInitializationCompleted(); } } - } private void CreateListOfIBaseService() @@ -377,7 +346,7 @@ private void CreateListOfIBaseService() _listeners.Clear(); _listeners.Add(_push); - _listeners.Add(Views); + _listeners.Add((ViewCountlyService)Views); _listeners.Add(Events); _listeners.Add(Device); _listeners.Add(Session); @@ -385,6 +354,7 @@ private void CreateListOfIBaseService() _listeners.Add(Consents); _listeners.Add(StarRating); _listeners.Add(UserDetails); + _listeners.Add((UserProfile)UserProfile); _listeners.Add(CrashReports); _listeners.Add(RemoteConfigs); _listeners.Add(Initialization); @@ -395,8 +365,7 @@ private void RegisterListenersToServices() Device.Listeners = _listeners; Consents.Listeners = _listeners; - foreach (AbstractBaseService listener in _listeners) - { + foreach (AbstractBaseService listener in _listeners) { listener.LockObj = lockObj; } } @@ -406,8 +375,7 @@ private void RegisterListenersToServices() /// private void OnApplicationQuit() { - if (!IsSDKInitialized) - { + if (!IsSDKInitialized) { return; } @@ -423,67 +391,52 @@ internal void CloseDBConnection() internal void ClearStorage() { - if (!IsSDKInitialized) - { + if (!IsSDKInitialized) { return; } _logHelper.Debug("[Countly] ClearStorage"); - PlayerPrefs.DeleteAll(); StorageHelper?.ClearDBData(); - StorageHelper?.CloseDB(); } private void OnApplicationFocus(bool hasFocus) { - if (!IsSDKInitialized) - { + if (!IsSDKInitialized) { return; } _logHelper?.Debug("[Countly] OnApplicationFocus: " + hasFocus); - if (hasFocus) - { + if (hasFocus) { SubscribeAppLog(); - } - else - { + } else { HandleAppPauseOrFocus(); } } private void OnApplicationPause(bool pauseStatus) { - lock (lockObj) - { - if (!IsSDKInitialized) - { + lock (lockObj) { + if (!IsSDKInitialized) { return; } _logHelper?.Debug("[Countly] OnApplicationPause: " + pauseStatus); - if (CrashReports != null) - { + if (CrashReports != null) { CrashReports.IsApplicationInBackground = pauseStatus; } - if (pauseStatus) - { + if (pauseStatus) { HandleAppPauseOrFocus(); - if (!Configuration.IsAutomaticSessionTrackingDisabled) - { + if (!Configuration.IsAutomaticSessionTrackingDisabled) { _ = Session?.EndSessionAsync(); } - } - else - { + } else { SubscribeAppLog(); - if (!Configuration.IsAutomaticSessionTrackingDisabled) - { + if (!Configuration.IsAutomaticSessionTrackingDisabled) { _ = Session?.BeginSessionAsync(); } } @@ -509,17 +462,14 @@ private void OnDisable() private void LogCallback(string condition, string stackTrace, LogType type) { - if (type == LogType.Exception) - { + if (type == LogType.Exception) { CrashReports?.SendCrashReportAsync(condition, stackTrace); } - } private void SubscribeAppLog() { - if (_logSubscribed) - { + if (_logSubscribed) { return; } @@ -529,8 +479,7 @@ private void SubscribeAppLog() private void UnsubscribeAppLog() { - if (!_logSubscribed) - { + if (!_logSubscribed) { return; } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Countly.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Countly.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Countly.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Countly.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyMainThreadHandler.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyMainThreadHandler.cs similarity index 82% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyMainThreadHandler.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyMainThreadHandler.cs index 8d62d0233..e9ec5066f 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyMainThreadHandler.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyMainThreadHandler.cs @@ -12,18 +12,15 @@ public class CountlyMainThreadHandler : MonoBehaviour public static CountlyMainThreadHandler Instance { - get - { - if (_instance == null) - { + get { + if (_instance == null) { // If instance is null, add this script to the created Countly object GameObject gameObject = Countly.Instance.gameObject; _instance = gameObject.AddComponent(); } return _instance; } - internal set - { + internal set { // Allow internal setting of the instance (used during cleanup) _instance = value; } @@ -35,6 +32,10 @@ private void Awake() mainThread = Thread.CurrentThread; } + /// + /// Checks if the current thread is the main thread + /// + /// public bool IsMainThread() { return Thread.CurrentThread.ManagedThreadId == mainThread.ManagedThreadId; @@ -43,16 +44,12 @@ public bool IsMainThread() public void RunOnMainThread(Action action) { // Check if we are on the main thread - if (IsMainThread()) - { + if (IsMainThread()) { // If on the main thread, invoke the action immediately action.Invoke(); - } - else - { + } else { // If on a different thread, queue the action to be executed on the main thread - lock (lockObject) - { + lock (lockObject) { _queuedAction = action; } } @@ -61,13 +58,11 @@ public void RunOnMainThread(Action action) private void Update() { // Execute any queued action on the main thread during the Unity Update phase - if (_queuedAction != null) - { - lock (lockObject) - { + if (_queuedAction != null) { + lock (lockObject) { _queuedAction.Invoke(); _queuedAction = null; } } } -} \ No newline at end of file +} diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyMainThreadHandler.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyMainThreadHandler.cs.meta similarity index 83% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyMainThreadHandler.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyMainThreadHandler.cs.meta index 715f8837e..68a54f69e 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyMainThreadHandler.cs.meta +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyMainThreadHandler.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 65c548d701c912641b9790aa9face003 +guid: 47f183e7dc5294e22be5312cb78a308d MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/CountlyUtils.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyUtils.cs similarity index 76% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/CountlyUtils.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyUtils.cs index e5d82273a..99eb30eed 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/CountlyUtils.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyUtils.cs @@ -7,6 +7,8 @@ using Plugins.CountlySDK.Helpers; using Plugins.CountlySDK.Models; using UnityEngine; +#nullable enable +#pragma warning disable 0618 namespace Plugins.CountlySDK { @@ -16,30 +18,42 @@ public class CountlyUtils internal string ServerInputUrl { get; private set; } internal string ServerOutputUrl { get; private set; } + private readonly string _appVersion; + public CountlyUtils(Countly countly) { _countly = countly; - ServerInputUrl = _countly.Configuration.ServerUrl + "/i?"; ServerOutputUrl = _countly.Configuration.ServerUrl + "/o/sdk?"; + _appVersion = Application.version; } public static string GetUniqueDeviceId() { + string result; string uniqueID = SystemInfo.deviceUniqueIdentifier; - if (uniqueID.Length > 5) - { - return "CLY_" + uniqueID; - } - else - { - return "CLY_" + SafeRandomVal(); + + if (uniqueID.Length > 5) { + result = uniqueID; + } else { + result = SafeRandomVal(); } + + return "CLY_" + result; } - public static string GetAppVersion() + /// + /// Returns the current version of the Application. + /// + public string GetAppVersion() { - return Application.version; + try { + return _appVersion; + } catch (Exception ex) { + Debug.Log("Error getting application version: " + ex.Message); + // Returns "-" to make sure that initialization process doesn't crash + return "-"; + } } /// @@ -61,8 +75,7 @@ public Dictionary GetBaseParams() }; // Add time-based metrics to the base parameters dictionary - foreach (KeyValuePair item in TimeMetricModel.GetTimeMetricModel()) - { + foreach (KeyValuePair item in TimeMetricModel.GetTimeMetricModel()) { baseParams.Add(item.Key, item.Value); } return baseParams; @@ -107,8 +120,7 @@ public bool IsNullEmptyOrWhitespace(string input) public bool IsPictureValid(string pictureUrl) { // Check if the provided url contains additional query parameters. Indicated by "?" - if (!string.IsNullOrEmpty(pictureUrl) && pictureUrl.Contains("?")) - { + if (!string.IsNullOrEmpty(pictureUrl) && pictureUrl.Contains("?")) { // Remove the query string portion to isolate the file extension. pictureUrl = pictureUrl.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0]; } @@ -129,10 +141,9 @@ public bool IsPictureValid(string pictureUrl) /// A hexadecimal string representation of the input byte array, /// or an empty string if the input byte array is null. /// - public string GetStringFromBytes(byte[] bytes) + public string GetStringFromBytes(byte[]? bytes) { - if (bytes == null) - { + if (bytes == null) { // Always return a value as a fallback return ""; } @@ -140,8 +151,7 @@ public string GetStringFromBytes(byte[] bytes) StringBuilder hex = new StringBuilder(bytes.Length * 2); // Iterate through each byte and convert to hexadecimal - foreach (byte b in bytes) - { + foreach (byte b in bytes) { hex.AppendFormat("{0:x2}", b); } @@ -157,15 +167,13 @@ public string GetStringFromBytes(byte[] bytes) /// public void TruncateSegmentationValues(Dictionary? segmentation, int maxCount, string prefix, CountlyLogHelper logger) { - if (segmentation == null) - { + if (segmentation == null) { return; } List keysToRemove = segmentation.Keys.Skip(maxCount).ToList(); - foreach (string key in keysToRemove) - { + foreach (string key in keysToRemove) { logger.Warning($"{prefix}, Value exceeded the maximum segmentation count key:[{key}]"); segmentation.Remove(key); } @@ -180,15 +188,12 @@ public void TruncateSegmentationValues(Dictionary? segmentation, /// public void RemoveReservedKeysFromSegmentation(Dictionary? segmentation, string[] reservedKeys, string messagePrefix, CountlyLogHelper logger) { - if (segmentation == null) - { + if (segmentation == null) { return; } - foreach (string rKey in reservedKeys) - { - if (segmentation.ContainsKey(rKey)) - { + foreach (string rKey in reservedKeys) { + if (segmentation.ContainsKey(rKey)) { logger.Warning($"{messagePrefix} provided segmentation contains protected key [{rKey}]"); segmentation.Remove(rKey); } @@ -210,8 +215,7 @@ public int CurrentTimestampSeconds() public static string SafeRandomVal() { long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds(); - using (RandomNumberGenerator random = new RNGCryptoServiceProvider()) - { + using (RandomNumberGenerator random = new RNGCryptoServiceProvider()) { byte[] value = new byte[6]; random.GetBytes(value); string b64Value = Convert.ToBase64String(value); @@ -227,21 +231,18 @@ public static string SafeRandomVal() /// Returns true if any entry had been removed public bool RemoveUnsupportedDataTypes(Dictionary? data, CountlyLogHelper? logger) { - if (data == null) - { + if (data == null) { return false; } List keysToRemove = new List(); bool removed = false; - foreach (var entry in data) - { + foreach (var entry in data) { string key = entry.Key; object value = entry.Value; - if (string.IsNullOrEmpty(key) || !(value is string || value is int || value is double || value is bool || value is float)) - { + if (string.IsNullOrEmpty(key) || !(value is string || value is int || value is double || value is bool || value is float || value is long)) { // found unsupported data type or null key or value, add key to removal list keysToRemove.Add(key); removed = true; @@ -249,14 +250,12 @@ public bool RemoveUnsupportedDataTypes(Dictionary? data, Countly } // Remove the keys marked for removal - foreach (string key in keysToRemove) - { + foreach (string key in keysToRemove) { data.Remove(key); } - if (removed & logger != null) - { - logger.Warning("[Utils] Unsupported data types were removed from provided segmentation"); + if (removed & logger != null) { + logger?.Warning("[Utils] Unsupported data types were removed from provided segmentation"); } return removed; @@ -271,8 +270,7 @@ private int Type() { int type = 0; - switch (_countly.Device.DeviceIdType) - { + switch (_countly.Device.DeviceIdType) { case DeviceIdType.DeveloperProvided: type = 0; break; @@ -284,5 +282,30 @@ private int Type() } return type; } + + /// + /// Copies all key-value pairs from the source dictionary to the destination dictionary. + /// + /// The dictionary to which the key-value pairs will be copied. + /// The dictionary from which the key-value pairs will be copied. + /// CountlyLogHelper to log warnings if either dictionary is null. + public void CopyDictionaryToDestination(Dictionary? destination, Dictionary? source, CountlyLogHelper logger) + { + logger.Verbose("[CountlyUtils] CopyDictionaryToDestination: Copying source dictionary into destination."); + + if (destination == null) { + logger.Warning("[CountlyUtils] CopyDictionaryToDestination: Provided destination is null."); + return; + } + + if (source == null) { + logger.Warning("[CountlyUtils] CopyDictionaryToDestination: Provided source is null."); + return; + } + + foreach (KeyValuePair kvp in source) { + destination[kvp.Key] = kvp.Value; + } + } } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/CountlyUtils.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyUtils.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/CountlyUtils.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/CountlyUtils.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor/CountlyBuildProcessor.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor/CountlyBuildProcessor.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor/CountlyBuildProcessor.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor/CountlyBuildProcessor.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor/CountlyBuildProcessor.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor/CountlyBuildProcessor.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor/CountlyBuildProcessor.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor/CountlyBuildProcessor.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor/EditorConfigSolutionFileGenerator.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor/EditorConfigSolutionFileGenerator.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor/EditorConfigSolutionFileGenerator.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor/EditorConfigSolutionFileGenerator.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor/EditorConfigSolutionFileGenerator.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor/EditorConfigSolutionFileGenerator.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Editor/EditorConfigSolutionFileGenerator.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Editor/EditorConfigSolutionFileGenerator.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/Consents.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/Consents.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/Consents.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/Consents.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/Consents.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/Consents.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/Consents.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/Consents.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/DeviceIdType.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/DeviceIdType.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/DeviceIdType.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/DeviceIdType.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/DeviceIdType.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/DeviceIdType.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/DeviceIdType.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/DeviceIdType.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/TestMode.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/TestMode.cs old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/TestMode.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/TestMode.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/TestMode.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/TestMode.cs.meta old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Enums/TestMode.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Enums/TestMode.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Constants.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Constants.cs similarity index 97% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Constants.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Constants.cs index 88215c201..cf65797ea 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Constants.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Constants.cs @@ -5,7 +5,7 @@ namespace Plugins.CountlySDK.Helpers { internal class Constants { - public const string SdkVersion = "23.12.0"; + public const string SdkVersion = "24.8.0"; #if UNITY_EDITOR public const string SdkName = "csharp-unity-editor"; diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Constants.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Constants.cs.meta old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Constants.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Constants.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Converter.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Converter.cs similarity index 92% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Converter.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Converter.cs index d04a01445..c482ac847 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Converter.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Converter.cs @@ -21,28 +21,23 @@ public static class Converter public static CountlyEventModel ConvertEventEntityToEventModel(EventEntity entity, CountlyLogHelper L) { // Check if the input EventEntity is null - if (entity == null) - { + if (entity == null) { L?.Warning("[Converter] 'ConvertEventEntityToEventModel': EventEntity variable is null"); return null; } - if (string.IsNullOrEmpty(entity.Json)) - { + if (string.IsNullOrEmpty(entity.Json)) { L?.Warning("[Converter] 'ConvertEventEntityToEventModel': EventEntity.Json variable is null or empty"); return null; } - try - { + try { CountlyEventModel model = JsonConvert.DeserializeObject(entity.Json); model.Id = entity.Id; return model; - } - catch (Exception ex) - { + } catch (Exception ex) { // Handle JSON serialization error L?.Warning($"[Converter] 'ConvertEventEntityToEventModel': JSON serialization error: {ex.Message}"); return null; @@ -58,8 +53,7 @@ public static EventEntity ConvertEventModelToEventEntity(CountlyEventModel model string json = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); model.Id = id; - return new EventEntity - { + return new EventEntity { Id = id, Json = json }; @@ -85,8 +79,7 @@ public static SegmentEntity ConvertSegmentModelToSegmentEntity(SegmentModel mode string json = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); model.Id = id; - return new SegmentEntity - { + return new SegmentEntity { Id = id, Json = json }; @@ -113,8 +106,7 @@ public static RequestEntity ConvertRequestModelToRequestEntity(CountlyRequestMod new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); model.Id = id; - return new RequestEntity - { + return new RequestEntity { Id = id, Json = json }; @@ -126,8 +118,7 @@ public static RequestEntity ConvertRequestModelToRequestEntity(CountlyRequestMod /// Dictionary of string and object representing the converted JSON data, or null if the input JSON string is null. public static Dictionary ConvertJsonToDictionary(string json, CountlyLogHelper L) { - if (json == null) - { + if (json == null) { L?.Warning("[Converter] 'ConvertJsonToDictionary': Provided Json is null"); return null; } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Converter.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Converter.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/Converter.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/Converter.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs similarity index 75% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs index 72ba2f02d..ee09b9071 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs @@ -1,5 +1,5 @@ using Plugins.CountlySDK.Models; - +#pragma warning disable 0618 public class CountlyLogHelper { private const string TAG = "[Countly]"; @@ -11,8 +11,7 @@ internal CountlyLogHelper(CountlyConfiguration configuration) internal void Info(string message) { - if (_configuration.EnableConsoleLogging) - { + if (_configuration.EnableConsoleLogging) { UnityEngine.Debug.Log("[Info]" + TAG + message); } @@ -20,8 +19,7 @@ internal void Info(string message) internal void Debug(string message) { - if (_configuration.EnableConsoleLogging) - { + if (_configuration.EnableConsoleLogging) { UnityEngine.Debug.Log("[Debug]" + TAG + message); } @@ -29,8 +27,7 @@ internal void Debug(string message) internal void Verbose(string message) { - if (_configuration.EnableConsoleLogging) - { + if (_configuration.EnableConsoleLogging) { UnityEngine.Debug.Log("[Verbose]" + TAG + message); } @@ -38,16 +35,14 @@ internal void Verbose(string message) internal void Error(string message) { - if (_configuration.EnableConsoleLogging) - { + if (_configuration.EnableConsoleLogging) { UnityEngine.Debug.LogError("[Error]" + TAG + message); } } internal void Warning(string message) { - if (_configuration.EnableConsoleLogging) - { + if (_configuration.EnableConsoleLogging) { UnityEngine.Debug.LogWarning("[Warning]" + TAG + message); } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/CountlyLogHelper.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyResponse.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/CountlyResponse.cs old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyResponse.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/CountlyResponse.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyResponse.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/CountlyResponse.cs.meta old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/CountlyResponse.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/CountlyResponse.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs similarity index 88% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs index ac5666571..9f4b5c993 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs @@ -20,14 +20,11 @@ internal static class FirstLaunchAppHelper /// public static void Process() { - if (!PlayerPrefs.HasKey(Constants.FirstAppLaunch)) - { + if (!PlayerPrefs.HasKey(Constants.FirstAppLaunch)) { PlayerPrefs.SetInt(Constants.FirstAppLaunch, 1); PlayerPrefs.Save(); _firstLaunchApp = true; - } - else - { + } else { PlayerPrefs.SetInt(Constants.FirstAppLaunch, 0); PlayerPrefs.Save(); _firstLaunchApp = false; @@ -42,10 +39,8 @@ public static void Process() /// public static bool IsFirstLaunchApp { - get - { - if (!_firstLaunchApp.HasValue) - { + get { + if (!_firstLaunchApp.HasValue) { Debug.LogWarning("[FirstLaunchAppHelper] IsFirstLaunchApp : Process should be called when session begins"); Process(); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/FirstLaunchAppHelper.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/MetricHelper.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/MetricHelper.cs similarity index 83% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/MetricHelper.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/MetricHelper.cs index a1c5d1f36..1bddc31d6 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/MetricHelper.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/MetricHelper.cs @@ -24,10 +24,8 @@ public MetricHelper(Dictionary overridenMetrics) public string OS { - get - { - if (overridenMetrics != null && overridenMetrics.ContainsKey("_os")) - { + get { + if (overridenMetrics != null && overridenMetrics.ContainsKey("_os")) { return overridenMetrics["_os"]; } return unityPlatform; @@ -36,10 +34,8 @@ public string OS public string OSVersion { - get - { - if (overridenMetrics != null && overridenMetrics.ContainsKey("_os_version")) - { + get { + if (overridenMetrics != null && overridenMetrics.ContainsKey("_os_version")) { return overridenMetrics["_os_version"]; } return SystemInfo.operatingSystem; @@ -48,10 +44,8 @@ public string OSVersion public string Device { - get - { - if (overridenMetrics != null && overridenMetrics.ContainsKey("_device")) - { + get { + if (overridenMetrics != null && overridenMetrics.ContainsKey("_device")) { return overridenMetrics["_device"]; } return SystemInfo.deviceModel; @@ -60,10 +54,8 @@ public string Device public string Resolution { - get - { - if (overridenMetrics != null && overridenMetrics.ContainsKey("_resolution")) - { + get { + if (overridenMetrics != null && overridenMetrics.ContainsKey("_resolution")) { return overridenMetrics["_resolution"]; } return Screen.currentResolution.ToString(); @@ -72,10 +64,8 @@ public string Resolution public string AppVersion { - get - { - if (overridenMetrics != null && overridenMetrics.ContainsKey("_app_version")) - { + get { + if (overridenMetrics != null && overridenMetrics.ContainsKey("_app_version")) { return overridenMetrics["_app_version"]; } return Application.version; @@ -84,10 +74,8 @@ public string AppVersion public string Density { - get - { - if (overridenMetrics != null && overridenMetrics.ContainsKey("_density")) - { + get { + if (overridenMetrics != null && overridenMetrics.ContainsKey("_density")) { return overridenMetrics["_density"]; } return Screen.dpi.ToString(); @@ -96,10 +84,8 @@ public string Density public string Locale { - get - { - if (overridenMetrics != null && overridenMetrics.ContainsKey("_locale")) - { + get { + if (overridenMetrics != null && overridenMetrics.ContainsKey("_locale")) { return overridenMetrics["_locale"]; } return Application.systemLanguage.ToString(); @@ -122,12 +108,9 @@ public string buildMetricJSON() { "_locale", Locale} }; - if (overridenMetrics != null) - { - foreach (KeyValuePair kvp in overridenMetrics) - { - if (!metrics.ContainsKey(kvp.Key)) - { + if (overridenMetrics != null) { + foreach (KeyValuePair kvp in overridenMetrics) { + if (!metrics.ContainsKey(kvp.Key)) { metrics[kvp.Key] = kvp.Value; } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/MetricHelper.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/MetricHelper.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/MetricHelper.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/MetricHelper.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestBuilder.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestBuilder.cs similarity index 97% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestBuilder.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestBuilder.cs index 0c70bd415..669843b99 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestBuilder.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestBuilder.cs @@ -23,8 +23,7 @@ internal CountlyRequestModel BuildRequest(IDictionary baseParams { //Metrics added to each request IDictionary requestData = baseParams; - foreach (KeyValuePair item in queryParams) - { + foreach (KeyValuePair item in queryParams) { requestData.Add(item.Key, item.Value); } @@ -45,10 +44,8 @@ internal string BuildQueryString(IDictionary queryParams) StringBuilder requestStringBuilder = new StringBuilder(); //Query params supplied for creating request - foreach (KeyValuePair item in queryParams) - { - if (!string.IsNullOrEmpty(item.Key) && item.Value != null) - { + foreach (KeyValuePair item in queryParams) { + if (!string.IsNullOrEmpty(item.Key) && item.Value != null) { requestStringBuilder.AppendFormat(requestStringBuilder.Length == 0 ? "{0}={1}" : "&{0}={1}", item.Key, Convert.ToString(item.Value)); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestBuilder.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestBuilder.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestBuilder.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestBuilder.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs similarity index 88% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs index d6c39bbd9..5416060ac 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs @@ -13,6 +13,7 @@ using Plugins.CountlySDK.Persistance.Repositories; using UnityEngine; using UnityEngine.Networking; +#pragma warning disable CS0618 namespace Plugins.CountlySDK.Helpers { @@ -46,21 +47,18 @@ internal void AddRequestToQueue(CountlyRequestModel request) { Log.Verbose($"[RequestCountlyHelper] AddRequestToQueue, Request: [{request.ToString()}]"); - if (_config.EnableTestMode) - { + if (_config.EnableTestMode) { return; } - if (_requestRepo.Count >= _config.StoredRequestLimit) - { + if (_requestRepo.Count >= _config.GetMaxRequestQueueSize()) { // Calculate how many items need to be removed from the queue to accommodate the new request. - int exceedAmount = _requestRepo.Count - _config.StoredRequestLimit; + int exceedAmount = _requestRepo.Count - _config.GetMaxRequestQueueSize(); int removeAmount = Mathf.Min(exceedAmount, countlyRequestRemoveLimit) + 1; Log.Warning("[RequestCountlyHelper] Request Queue is full. Dropping the oldest request."); // Remove the calculated amount of oldest requests from the queue. - while (removeAmount > 0) - { + while (removeAmount > 0) { _requestRepo.Dequeue(); removeAmount--; } @@ -75,8 +73,7 @@ internal void AddRequestToQueue(CountlyRequestModel request) /// internal async Task ProcessQueue() { - if (_isQueueBeingProcess) - { + if (_isQueueBeingProcess) { Log.Verbose("[RequestCountlyHelper] ProcessQueue, queue is being processed."); return; } @@ -84,35 +81,29 @@ internal async Task ProcessQueue() _isQueueBeingProcess = true; CountlyRequestModel[] requests = null; - try - { + try { requests = _requestRepo.Models.ToArray(); Log.Verbose($"[RequestCountlyHelper] ProcessQueue, request count: [{requests.Length}]"); - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Warning($"[RequestCountlyHelper] ProcessQueue, exception occurred while converting Models to array. Exception: {ex}"); _isQueueBeingProcess = false; return; } // make sure that flag is corrected and exit - if (requests.Length == 0) - { + if (requests.Length == 0) { Log.Verbose("[RequestCountlyHelper] ProcessQueue, Request Queue is empty. Returning."); _isQueueBeingProcess = false; return; } - foreach (CountlyRequestModel reqModel in requests) - { + foreach (CountlyRequestModel reqModel in requests) { // Add the remaining request count in RequestData reqModel.RequestData += "&rr=" + (requests.Length - 1); CountlyResponse response = await ProcessRequest(reqModel); - if (!response.IsSuccess) - { + if (!response.IsSuccess) { Log.Verbose($"[RequestCountlyHelper] ProcessQueue: Request failed. Response: [{response.ToString()}]"); _isQueueBeingProcess = false; break; @@ -131,7 +122,7 @@ internal async Task ProcessQueue() private async Task ProcessRequest(CountlyRequestModel model) { Log.Verbose($"[RequestCountlyHelper] Process request, request: [{model}]"); - bool shouldPost = _config.EnablePost || model.RequestData.Length > 2000; + bool shouldPost = _config.IsForcedHttpPostEnabled() || model.RequestData.Length > 2000; #if UNITY_WEBGL // There is not HTTP GET for WebGL. We always do a HTTP POST @@ -159,12 +150,10 @@ internal void AddToRequestQueue(Dictionary queryParams) private string AddChecksum(string query) { - if (!string.IsNullOrEmpty(_config.Salt)) - { + if (!string.IsNullOrEmpty(_config.GetParameterTamperingProtectionSalt())) { // Create a SHA256 - using (SHA256 sha256Hash = SHA256.Create()) - { - byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(query + _config.Salt)); + using (SHA256 sha256Hash = SHA256.Create()) { + byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(query + _config.GetParameterTamperingProtectionSalt())); string hex = _countlyUtils.GetStringFromBytes(bytes); query += "&checksum256=" + hex; @@ -189,15 +178,12 @@ internal async Task GetAsync(string uri, string data) string query = AddChecksum(data); string url = uri + query; - try - { + try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); - using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) - { + using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) { int code = (int)response.StatusCode; using (Stream stream = response.GetResponseStream()) - using (StreamReader reader = new StreamReader(stream)) - { + using (StreamReader reader = new StreamReader(stream)) { string res = await reader.ReadToEndAsync(); countlyResponse.Data = res; @@ -205,17 +191,13 @@ internal async Task GetAsync(string uri, string data) countlyResponse.IsSuccess = IsSuccess(countlyResponse); } } - } - catch (WebException ex) - { + } catch (WebException ex) { countlyResponse.ErrorMessage = ex.Message; - if (ex.Response != null) - { + if (ex.Response != null) { HttpWebResponse response = (HttpWebResponse)ex.Response; int code = (int)response.StatusCode; using (Stream stream = ex.Response.GetResponseStream()) - using (StreamReader reader = new StreamReader(stream)) - { + using (StreamReader reader = new StreamReader(stream)) { string res = await reader.ReadToEndAsync(); countlyResponse.StatusCode = code; countlyResponse.Data = res; @@ -238,8 +220,7 @@ internal async Task PostAsync(string uri, string data) { CountlyResponse countlyResponse = new CountlyResponse(); - try - { + try { string query = AddChecksum(data); byte[] dataBytes = Encoding.ASCII.GetBytes(query); @@ -248,17 +229,14 @@ internal async Task PostAsync(string uri, string data) request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; - using (Stream requestBody = request.GetRequestStream()) - { + using (Stream requestBody = request.GetRequestStream()) { await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length); } - using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) - { + using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) { int code = (int)response.StatusCode; using (Stream stream = response.GetResponseStream()) - using (StreamReader reader = new StreamReader(stream)) - { + using (StreamReader reader = new StreamReader(stream)) { string res = await reader.ReadToEndAsync(); countlyResponse.Data = res; @@ -266,17 +244,13 @@ internal async Task PostAsync(string uri, string data) countlyResponse.IsSuccess = IsSuccess(countlyResponse); } } - } - catch (WebException ex) - { + } catch (WebException ex) { countlyResponse.ErrorMessage = ex.Message; - if (ex.Response != null) - { + if (ex.Response != null) { HttpWebResponse response = (HttpWebResponse)ex.Response; int code = (int)response.StatusCode; using (Stream stream = ex.Response.GetResponseStream()) - using (StreamReader reader = new StreamReader(stream)) - { + using (StreamReader reader = new StreamReader(stream)) { string res = await reader.ReadToEndAsync(); countlyResponse.StatusCode = code; countlyResponse.Data = res; @@ -300,28 +274,20 @@ private Task StartProcessRequestRoutine(string uri, string data Log.Debug($"[RequestCountlyHelper] StartProcessRequestRoutine, Start"); TaskCompletionSource tcs = new TaskCompletionSource(); - try - { + try { // 'IsObjectMonoBehaviour can only be called from the main thread' // That's why we have to move it to main thread. - CountlyMainThreadHandler.Instance.RunOnMainThread(() => - { - try - { - _monoBehaviour.StartCoroutine(ProcessRequestCoroutine(uri, data, (response) => - { + CountlyMainThreadHandler.Instance.RunOnMainThread(() => { + try { + _monoBehaviour.StartCoroutine(ProcessRequestCoroutine(uri, data, (response) => { tcs.SetResult(response); })); - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Error($"[RequestCountlyHelper] StartProcessRequestRoutine, Exception occurred while starting coroutine. Exception: [{ex}]"); tcs.SetException(ex); } }); - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Error($"[RequestCountlyHelper] StartProcessRequestRoutine, Exception occurred while queueing to main thread. Exception: [{ex}]"); tcs.SetException(ex); } @@ -344,8 +310,7 @@ private IEnumerator ProcessRequestCoroutine(string uri, string data, ActionTrue if the status code is between 200 and 299 and the response data contains a "result" key; otherwise, false. private bool IsSuccess(CountlyResponse countlyResponse) { - if (countlyResponse.StatusCode >= 200 && countlyResponse.StatusCode < 300) - { - try - { + if (countlyResponse.StatusCode >= 200 && countlyResponse.StatusCode < 300) { + try { JObject json = JObject.Parse(countlyResponse.Data); - if (json.ContainsKey("result")) - { + if (json.ContainsKey("result")) { return true; } - } - catch (JsonException ex) - { + } catch (JsonException ex) { Log.Debug($"[RequestCountlyHelper] IsSuccess : Returned request is not a JSON object. Exception: [{ex}]"); return false; } - } - else - { + } else { Log.Debug($"[RequestCountlyHelper] IsSuccess, Status Code: [{countlyResponse.StatusCode}] is not in between 200-299. Returning false."); } return false; } } -} \ No newline at end of file +} diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/RequestCountlyHelper.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs similarity index 98% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs index b95193b1f..b27ec36e2 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs @@ -1,9 +1,9 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; - +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + namespace Plugins.CountlySDK -{ +{ public interface ISafeIDGenerator { string GenerateValue(); @@ -16,5 +16,5 @@ public string GenerateValue() return CountlyUtils.SafeRandomVal(); } } -} - +} + diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/SafeIDGenerator.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs similarity index 93% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs index 68acdb227..be9ba65bb 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs @@ -51,13 +51,10 @@ internal StorageAndMigrationHelper(CountlyLogHelper logHelper, RequestBuilder re _logHelper = logHelper; _requestBuilder = requestBuilder; - if (FirstLaunchAppHelper.IsFirstLaunchApp) - { + if (FirstLaunchAppHelper.IsFirstLaunchApp) { CurrentVersion = SchemaVersion; PlayerPrefs.SetInt(Constants.SchemaVersion, SchemaVersion); - } - else - { + } else { CurrentVersion = PlayerPrefs.GetInt(Constants.SchemaVersion, 0); } } @@ -75,8 +72,7 @@ private DB BuildDatabase(long dbNumber) db.GetConfig().EnsureTable(EntityType.NonViewEvents.ToString(), "Id"); db.GetConfig().EnsureTable(EntityType.NonViewEventSegments.ToString(), "Id"); - if (CurrentVersion < 1) - { + if (CurrentVersion < 1) { db.GetConfig().EnsureTable(EntityType.ViewEvents.ToString(), "Id"); db.GetConfig().EnsureTable(EntityType.ViewEventSegments.ToString(), "Id"); db.GetConfig().EnsureTable(EntityType.EventNumberInSameSessions.ToString(), "Id"); @@ -103,8 +99,7 @@ internal void OpenDB() RequestDao = new Dao(auto, EntityType.Requests.ToString(), _logHelper); EventDao = new Dao(auto, EntityType.NonViewEvents.ToString(), _logHelper); - if (CurrentVersion < 1) - { + if (CurrentVersion < 1) { EventNrInSameSessionDao = new Dao(auto, EntityType.EventNumberInSameSessions.ToString(), _logHelper); Dao viewDao = new Dao(auto, EntityType.ViewEvents.ToString(), _logHelper); @@ -144,8 +139,7 @@ internal void RunMigration(IDictionary migrationParams) * - Deletion of the data in the “EventNumberInSameSessionEntity” table * - Copy data of 'Views Repository(Entity Dao, Segment Dao)' into Event Repository(Entity Dao, Segment Dao)'. */ - if (CurrentVersion == 0) - { + if (CurrentVersion == 0) { Migration_EventNumberInSameSessionEntityDataRemoval(); Migration_CopyViewDataIntoEventData(); @@ -153,15 +147,13 @@ internal void RunMigration(IDictionary migrationParams) PlayerPrefs.SetInt(Constants.SchemaVersion, CurrentVersion); } - if (CurrentVersion == 1) - { + if (CurrentVersion == 1) { Migration_MigrateOldRequests(); CurrentVersion = 2; PlayerPrefs.SetInt(Constants.SchemaVersion, CurrentVersion); } - if (CurrentVersion == 2) - { + if (CurrentVersion == 2) { bool customIdProvided = (bool)migrationParams[key_from_2_to_3_custom_id_set]; Migration_GuessTheDeviceIDType(customIdProvided); CurrentVersion = 3; @@ -185,8 +177,7 @@ private void Migration_EventNumberInSameSessionEntityDataRemoval() /// private void Migration_CopyViewDataIntoEventData() { - while (ViewRepo.Count > 0) - { + while (ViewRepo.Count > 0) { EventRepo.Enqueue(ViewRepo.Dequeue()); } _logHelper.Verbose("[CountlyStorageHelper] Migration_CopyViewDataIntoEventData"); @@ -202,11 +193,9 @@ private void Migration_MigrateOldRequests() { //get all stored requests CountlyRequestModel[] requestModels = RequestRepo.Models.ToArray(); - foreach (CountlyRequestModel request in requestModels) - { + foreach (CountlyRequestModel request in requestModels) { //go through all of them - if (request.RequestData == null) - { + if (request.RequestData == null) { // if we have no request data then that means that all of the info is in the request URL // start by parsing all the params from the URL. // remove the checksum and then write the request back as a string @@ -220,9 +209,7 @@ private void Migration_MigrateOldRequests() request.RequestUrl = null; request.RequestData = data; - } - else - { + } else { // if we don't have request data then that means that all of the request params are in the request data field // deserialize the values, remove the checksum and then combine them all into a single array which should then be the replacement Dictionary requestData = JsonConvert.DeserializeObject>(request.RequestData); @@ -233,8 +220,7 @@ private void Migration_MigrateOldRequests() } bool result = RequestRepo.Update(request); - if (!result) - { + if (!result) { _logHelper.Warning("[CountlyStorageHelper] Migration_MigrateOldRequests: updating the request failed"); //we failed to update the old request, @@ -249,12 +235,9 @@ private void Migration_MigrateOldRequests() private void Migration_GuessTheDeviceIDType(bool customIdProvided) { - if (customIdProvided) - { + if (customIdProvided) { PlayerPrefs.SetInt(Constants.DeviceIDTypeKey, (int)DeviceIdType.DeveloperProvided); - } - else - { + } else { PlayerPrefs.SetInt(Constants.DeviceIDTypeKey, (int)DeviceIdType.SDKGenerated); } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Helpers/StorageAndMigrationHelper.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces.meta new file mode 100644 index 000000000..9af0a36ab --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9aafa2f9edac44a95ab66501602f97c5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IUserProfileModule.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IUserProfileModule.cs new file mode 100644 index 000000000..67612fdec --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IUserProfileModule.cs @@ -0,0 +1,19 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public interface IUserProfileModule +{ + public void Increment(string key); + public void IncrementBy(string key, double value); + public void SaveMax(string key, double value); + public void SaveMin(string key, double value); + public void Multiply(string key, double value); + public void Pull(string key, string value); + public void Push(string key, string value); + public void PushUnique(string key, string value); + public void Save(); + public void SetOnce(string key, string value); + public void SetProperties(Dictionary data); + public void SetProperty(string key, object value); +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IUserProfileModule.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IUserProfileModule.cs.meta new file mode 100644 index 000000000..e143f5291 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IUserProfileModule.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a87287ad3b5ac461ab182b258b05cabe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewIDProvider.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewIDProvider.cs new file mode 100644 index 000000000..468715301 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewIDProvider.cs @@ -0,0 +1,5 @@ +interface IViewIDProvider +{ + public string GetCurrentViewId(); + public string GetPreviousViewId(); +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewIDProvider.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewIDProvider.cs.meta new file mode 100644 index 000000000..94299b8f6 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewIDProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 80996e89904c04b8f8377dee55fd5f10 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewModule.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewModule.cs new file mode 100644 index 000000000..486aa2959 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewModule.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +public interface IViewModule +{ + /// + /// Manually starts a view with the given name. + /// It can be used to open multiple views in parallel. + /// + /// Name of the view + /// ViewId + string StartView(string viewName); + + /// + /// Manually starts a view with the given name. + /// It can be used to open multiple views in parallel. + /// + /// Name of the view + /// Segmentation that will be added to the view, set 'null' if none should be added + /// ViewId + string StartView(string viewName, Dictionary viewSegmentation); + + /// + /// Manually starts a view with the given name. Starting any other view or calling this again, + /// closes the one that's opened automatically.
+ /// This ensures a 'one view at a time' flow. + ///
+ /// Name of the view + /// ViewId + string StartAutoStoppedView(string viewName); + + /// + /// Manually starts a view with the given name. Starting any other view or calling this again, + /// closes the one that's opened automatically.
+ /// This ensures a 'one view at a time' flow. + ///
+ /// Name of the view + /// Segmentation that will be added to the view, set 'null' if none should be added + /// ViewId + string StartAutoStoppedView(string viewName, Dictionary viewSegmentation); + + /// + /// Stops a view with the given name if it is open + /// If multiple views with same name are open, last opened view will be closed. + /// + /// Name of the view + void StopViewWithName(string viewName); + + /// + /// Stops a view with the given name if it is open + /// If multiple views with same name are open, last opened view will be closed. + /// + /// Name of the view + /// Segmentation that will be added to the view, set 'null' if none should be added + void StopViewWithName(string viewName, Dictionary viewSegmentation); + + /// + /// Stops a view with the given ID if it is open + /// + /// ID of the view + void StopViewWithID(string viewID); + + /// + /// Stops a view with the given ID if it is open + /// + /// ID of the view + /// Segmentation that will be added to the view, set 'null' if none should be added + void StopViewWithID(string viewID, Dictionary viewSegmentation); + + /// + /// Pauses a view with the given ID + /// + /// ID of the view + void PauseViewWithID(string viewID); + + /// + /// Resumes a view with the given ID + /// + /// ID of the view + void ResumeViewWithID(string viewID); + + /// + /// Stops all views and records a segmentation if set + /// + /// Segmentation that will be added, set 'null' if none should be added + void StopAllViews(Dictionary viewSegmentation); + + /// + /// Set a segmentation to be recorded with all views + /// + /// Global View Segmentation + void SetGlobalViewSegmentation(Dictionary viewSegmentation); + + /// + /// Updates the segmentation of a view with view id. + /// + /// ID of the view + /// Segmentation that will be added to the view + void AddSegmentationToViewWithID(string viewID, Dictionary viewSegmentation); + + /// + /// Updates the segmentation of a view with view name. + /// If multiple views with same name are open, last opened view will be updated. + /// + /// Name of the view + /// Segmentation that will be added to the view + void AddSegmentationToViewWithName(string viewName, Dictionary viewSegmentation); + + /// + /// Updates the global segmentation + /// + /// Segmentation that will be added to the view + void UpdateGlobalViewSegmentation(Dictionary viewSegmentation); + + /// + /// Records the opening of a view. This method is deprecated. + /// + /// + /// This method must be used in conjunction with . + /// Do not use with as it will not function correctly. + /// Please use and for new implementations. + /// + /// The name of the view to open. + /// Optional segmentation data for the view. + /// A task representing the asynchronous operation. + [Obsolete("RecordOpenViewAsync(string name, IDictionary segmentation = null) is deprecated and will be removed in the future. Please use StartView instead.")] + Task RecordOpenViewAsync(string name, IDictionary segmentation = null); + + /// + /// Records the closing of a view. This method is deprecated. + /// + /// + /// This method should only be used to close views that were opened using . + /// Do not use to close views started with . + /// + /// The name of the view to close. + /// A task representing the asynchronous operation. + [Obsolete("RecordCloseViewAsync(string name) is deprecated and will be removed in the future. Please use StopView instead.")] + Task RecordCloseViewAsync(string name); + + /// + /// Reports a particular action with the specified details. + /// + /// + /// This method is deprecated and will be removed in a future release. There is no direct replacement for this method. + /// Consider re-evaluating the need for this functionality or implementing a custom solution as needed. + /// + /// The type of action. + /// The x-coordinate. + /// The y-coordinate. + /// The width of the screen. + /// The height of the screen. + /// A task representing the asynchronous operation. + [Obsolete("ReportActionAsync(string type, int x, int y, int width, int height) is deprecated and will be removed in the future.")] + Task ReportActionAsync(string type, int x, int y, int width, int height); +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewModule.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewModule.cs.meta new file mode 100644 index 000000000..68848a13b --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Interfaces/IViewModule.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9f64177a442064555be12500bf14702a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyAuthModel.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyAuthModel.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyAuthModel.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyAuthModel.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyAuthModel.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyAuthModel.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyAuthModel.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyAuthModel.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyConfigModel.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyConfigModel.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyConfigModel.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyConfigModel.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyConfigModel.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyConfigModel.cs.meta old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyConfigModel.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyConfigModel.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyConfiguration.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyConfiguration.cs similarity index 78% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyConfiguration.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyConfiguration.cs index ac5acc129..8b2e8e6e0 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyConfiguration.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyConfiguration.cs @@ -6,7 +6,7 @@ using Plugins.CountlySDK.Helpers; using Plugins.CountlySDK.Services; using UnityEngine; - +#pragma warning disable CS0618 namespace Plugins.CountlySDK.Models { [Serializable] @@ -73,7 +73,7 @@ public class CountlyConfiguration /// min value 1 (1 second), max value 600 (10 minutes) /// [Obsolete("SessionDuration is deprecated. Use SetUpdateSessionTimerDelay(int duration) instead.")] - public int SessionDuration = 60; + public int SessionDuration = 20; /// /// Maximum size of all string keys @@ -109,13 +109,13 @@ public class CountlyConfiguration /// Set threshold value for the number of events that can be stored locally. /// [Obsolete("EventQueueThreshold is deprecated. Use SetEventQueueSizeToSend(int threshold) instead.")] - public int EventQueueThreshold = 100; + public int EventQueueThreshold = 10; /// /// Set limit for the number of requests that can be stored locally. /// [Obsolete("StoredRequestLimit is deprecated. Use SetMaxRequestQueueSize(int limit) instead.")] - public int StoredRequestLimit = 1000; + public int StoredRequestLimit = 10; /// /// Set the maximum amount of breadcrumbs. @@ -135,8 +135,8 @@ public class CountlyConfiguration [Obsolete("RequiresConsent is deprecated. Use SetRequiresConsent(bool enable) instead.")] public bool RequiresConsent = false; - internal SafeIDGenerator SafeViewIDGenerator = null; - internal SafeIDGenerator SafeEventIDGenerator = null; + internal ISafeIDGenerator SafeViewIDGenerator = null; + internal ISafeIDGenerator SafeEventIDGenerator = null; internal string City = null; internal string Location = null; @@ -150,6 +150,7 @@ public class CountlyConfiguration internal List NotificationEventListeners; internal Dictionary ConsentGroups { get; private set; } internal Dictionary overridenMetrics; + private Dictionary providedUserProperties = new Dictionary(); internal MetricHelper metricHelper; /// @@ -456,6 +457,114 @@ public CountlyConfiguration SetRequiresConsent(bool enable) return this; } + + /// + /// Sets user properties that would be sent as soon as possible + /// + /// Modified instance of the CountlyConfiguration + public CountlyConfiguration SetUserProperties(Dictionary userProperties) + { + providedUserProperties = userProperties; + return this; + } + #endregion + #region Getters + + /// + /// Returns the URL of the Countly server to submit data to. + /// + public string GetServerUrl() { return ServerUrl; } + + /// + /// Returns the App key for the application being tracked. + /// + public string GetAppKey() { return AppKey; } + + /// + /// Returns the Unique ID for the device the app is running on. + /// + public string GetDeviceId() { return DeviceId; } + + /// + /// Returns the parameter that prevents tampering. + /// + public string GetParameterTamperingProtectionSalt() { return Salt; } + + /// + /// Returns true if it's set to send all requests made to the Countly server using HTTP POST. + /// + public bool IsForcedHttpPostEnabled() { return EnablePost; } + + /// + /// Returns true if it's set to enable countly internal debugging logs. + /// + public bool IsLoggingEnabled() { return EnableConsoleLogging; } + + /// + /// Returns the mode of push notification. + /// + public TestMode GetNotificationMode() { return NotificationMode; } + + /// + /// Returns the interval for the automatic update calls + /// + public int GetUpdateSessionTimerDelay() { return SessionDuration; } + + /// + /// Returns the maximum size of all string keys + /// + public int GetMaxKeyLength() { return MaxKeyLength; } + + /// + /// Returns the maximum size of all values in our key-value pairs + /// + public int GetMaxValueSize() { return MaxValueSize; } + + /// + /// Returns the maximum amount of custom (dev provided) segmentation in one event + /// + public int GetMaxSegmentationValues() { return MaxSegmentationValues; } + + /// + /// Returns the limit for how many stack trace lines would be recorded per thread + /// + public int GetMaxStackTraceLinesPerThread() { return MaxStackTraceLinesPerThread; } + + /// + /// Returns the limit for how many characters are allowed per stack trace line + /// + public int GetMaxStackTraceLineLength() { return MaxStackTraceLineLength; } + + /// + /// Returns the threshold value for the number of events that can be stored locally. + /// + public int GetEventQueueSizeToSend() { return EventQueueThreshold; } + + /// + /// Returns the limit for the number of requests that can be stored locally. + /// + public int GetMaxRequestQueueSize() { return StoredRequestLimit; } + + /// + /// Returns the maximum amount of breadcrumbs. + /// + public int GetMaxBreadcrumbCount() { return TotalBreadcrumbsAllowed; } + + /// + /// Returns true if uncaught crash reporting is enabled. + /// + public bool IsAutomaticCrashReportingEnabled() { return EnableAutomaticCrashReporting; } + + /// + /// Returns true if consent is required. + /// + public bool IsConsentRequired() { return RequiresConsent; } + + /// + /// Returns provided user properties set. + /// + /// + public Dictionary GetUserProperties() { return providedUserProperties; } #endregion } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyConfiguration.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyConfiguration.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyConfiguration.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyConfiguration.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyEventModel.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyEventModel.cs similarity index 71% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyEventModel.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyEventModel.cs index bd74818cb..ed87153ac 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyEventModel.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyEventModel.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; using Plugins.CountlySDK.Persistance; +#nullable enable namespace Plugins.CountlySDK.Models { @@ -16,12 +17,11 @@ public class CountlyEventModel : IModel /// /// /// - public CountlyEventModel(string key, IDictionary segmentation = null, int? count = 1, double? sum = null, double? duration = null) + public CountlyEventModel(string key, IDictionary? segmentation = null, int? count = 1, double? sum = null, double? duration = null, string? eventId = null, string? pvid = null, string? cvid = null, string? peid = null) { Key = key; Count = count ?? 1; - if (segmentation != null) - { + if (segmentation != null) { Segmentation = new SegmentModel(segmentation); } Duration = duration; @@ -32,6 +32,11 @@ public CountlyEventModel(string key, IDictionary segmentation = Hour = timeModel.Hour; DayOfWeek = timeModel.DayOfWeek; Timestamp = timeModel.Timestamp; + + EventID = eventId; + PreviousEventID = peid; + PreviousViewID = pvid; + CurrentViewID = cvid; } public CountlyEventModel() @@ -40,8 +45,7 @@ public CountlyEventModel() [JsonIgnore] public long Id { get; set; } - - [JsonProperty("key")] public string Key { get; set; } + [JsonProperty("key")] public string? Key { get; set; } [JsonProperty("count")] public int? Count { get; set; } @@ -49,7 +53,7 @@ public CountlyEventModel() [JsonProperty("dur")] public double? Duration { get; set; } - [JsonProperty("segmentation")] public SegmentModel Segmentation { get; set; } + [JsonProperty("segmentation")] public SegmentModel? Segmentation { get; set; } [JsonProperty("timestamp")] public long Timestamp { get; set; } @@ -57,8 +61,15 @@ public CountlyEventModel() [JsonProperty("dow")] public int DayOfWeek { get; set; } - #region Reserved Event Names + [JsonProperty("id")] public string? EventID { get; set; } + + [JsonProperty("pvid")] public string? PreviousViewID { get; set; } + + [JsonProperty("cvid")] public string? CurrentViewID { get; set; } + + [JsonProperty("peid")] public string? PreviousEventID { get; set; } + #region Reserved Event Names [JsonIgnore] public const string NPSEvent = "[CLY]_nps"; [JsonIgnore] public const string ViewEvent = "[CLY]_view"; @@ -72,15 +83,11 @@ public CountlyEventModel() [JsonIgnore] public const string PushActionEvent = "[CLY]_push_action"; [JsonIgnore] public const string OrientationEvent = "[CLY]_orientation"; - - - #endregion - public override string ToString() { - return $"{nameof(Id)}: {Id}, {nameof(Key)}: {Key}, {nameof(Count)}: {Count}, {nameof(Sum)}: {Sum}, {nameof(Duration)}: {Duration}, {nameof(Segmentation)}: {Segmentation}, {nameof(Timestamp)}: {Timestamp}, {nameof(Hour)}: {Hour}, {nameof(DayOfWeek)}: {DayOfWeek},"; + return $"{nameof(Id)}: {Id}, {nameof(Key)}: {Key}, {nameof(Count)}: {Count}, {nameof(Sum)}: {Sum}, {nameof(Duration)}: {Duration}, {nameof(Segmentation)}: {Segmentation}, {nameof(Timestamp)}: {Timestamp}, {nameof(Hour)}: {Hour}, {nameof(DayOfWeek)}: {DayOfWeek}, {nameof(EventID)}: {EventID}, {nameof(PreviousViewID)}: {PreviousViewID}, {nameof(CurrentViewID)}: {CurrentViewID}, {nameof(PreviousEventID)}: {PreviousEventID},"; } } -} +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyEventModel.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyEventModel.cs.meta old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyEventModel.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyEventModel.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyExceptionDetailModel.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyExceptionDetailModel.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyExceptionDetailModel.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyExceptionDetailModel.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyExceptionDetailModel.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyExceptionDetailModel.cs.meta old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyExceptionDetailModel.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyExceptionDetailModel.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyRequestModel.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyRequestModel.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyRequestModel.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyRequestModel.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyRequestModel.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyRequestModel.cs.meta old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyRequestModel.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyRequestModel.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs similarity index 98% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs index 73a8e6c07..c1f568d05 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs @@ -53,8 +53,7 @@ public CountlyUserDetailsModel(string name, string username, string email, strin PictureUrl = pictureUrl; Gender = gender; BirthYear = birthYear; - if (customData != null) - { + if (customData != null) { Custom = customData as Dictionary; } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs.meta old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/CountlyUserDetailsModel.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/SegmentModel.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/SegmentModel.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/SegmentModel.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/SegmentModel.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/SegmentModel.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/SegmentModel.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/SegmentModel.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/SegmentModel.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/TimeMetricModel.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/TimeMetricModel.cs similarity index 88% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/TimeMetricModel.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/TimeMetricModel.cs index 28eec2ed9..0442cd094 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/TimeMetricModel.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/TimeMetricModel.cs @@ -39,16 +39,13 @@ private long GetUniqueMilliSecTimeStamp(DateTime? requestedDatetime = null) //get current timestamp in miliseconds DateTimeOffset currentMilliSecTimeStamp = DateTimeOffset.UtcNow; - if (requestedDatetime.HasValue) - { + if (requestedDatetime.HasValue) { currentMilliSecTimeStamp = requestedDatetime.Value; _lastMilliSecTimeStamp = _lastMilliSecTimeStamp >= currentMilliSecTimeStamp ? _lastMilliSecTimeStamp.AddMilliseconds(1) : _lastMilliSecTimeStamp = currentMilliSecTimeStamp; - } - else - { + } else { _lastMilliSecTimeStamp = currentMilliSecTimeStamp; } @@ -59,11 +56,10 @@ internal static TimeMetricModel GetTimeZoneInfoForRequest() { DateTime currentDateTime = DateTime.Now; TimeMetricModel model = - new TimeMetricModel - { + new TimeMetricModel { Hour = currentDateTime.TimeOfDay.Hours, DayOfWeek = (int)currentDateTime.DayOfWeek, - Timezone = TimeZone.CurrentTimeZone.GetUtcOffset(currentDateTime).TotalMinutes.ToString(CultureInfo.InvariantCulture) + Timezone = TimeZoneInfo.Local.GetUtcOffset(currentDateTime).TotalMinutes.ToString(CultureInfo.InvariantCulture) }; model.Timestamp = model.GetUniqueMilliSecTimeStamp(currentDateTime); diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/TimeMetricModel.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/TimeMetricModel.cs.meta old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Models/TimeMetricModel.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Models/TimeMetricModel.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Dao.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Dao.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Dao.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Dao.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs similarity index 87% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs index 9a5bdcdca..859094714 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs @@ -28,24 +28,19 @@ public SegmentEntity GetByEventId(long eventId) string ql = _stringBuilder.Append("from ").Append(Table).Append(" where EventId==?").ToString(); - try - { + try { System.Collections.Generic.List entities = Auto.Select(ql, eventId); - if (entities.Count > 1) - { + if (entities.Count > 1) { throw new ArgumentException("Only one or zero segment can be assigned to entity with id " + eventId + ". " + entities.Count + " segments found."); } - if (entities.Count == 0) - { + if (entities.Count == 0) { return null; } return entities[0]; - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Debug("[SegmentDao] GetByEventId: Couldn't complete db operation, [" + ex.Message + "]"); return null; } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Dao/SegmentDao.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/ConfigEntity.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/ConfigEntity.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/ConfigEntity.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/ConfigEntity.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/ConfigEntity.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/ConfigEntity.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/ConfigEntity.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/ConfigEntity.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/EventEntity.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/EventEntity.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/EventEntity.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/EventEntity.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/EventEntity.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/EventEntity.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/EventEntity.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/EventEntity.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/EventNumberInSameSessionEntity.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/EventNumberInSameSessionEntity.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/EventNumberInSameSessionEntity.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/EventNumberInSameSessionEntity.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/EventNumberInSameSessionEntity.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/EventNumberInSameSessionEntity.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/EventNumberInSameSessionEntity.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/EventNumberInSameSessionEntity.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/IEntity.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/IEntity.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/IEntity.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/IEntity.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/IEntity.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/IEntity.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/IEntity.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/IEntity.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/RequestEntity.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/RequestEntity.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/RequestEntity.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/RequestEntity.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/RequestEntity.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/RequestEntity.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/RequestEntity.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/RequestEntity.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/SegmentEntity.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/SegmentEntity.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/SegmentEntity.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/SegmentEntity.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/SegmentEntity.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/SegmentEntity.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Entities/SegmentEntity.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Entities/SegmentEntity.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/IModel.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/IModel.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/IModel.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/IModel.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/IModel.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/IModel.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/IModel.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/IModel.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs similarity index 91% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs index 616deafb4..8e2850332 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs @@ -22,11 +22,9 @@ protected AbstractEventRepository(Dao dao, SegmentDao segmentDao, C public override void Initialize() { base.Initialize(); - foreach (CountlyEventModel model in Models) - { + foreach (CountlyEventModel model in Models) { SegmentEntity segmentEntity = _segmentDao.GetByEventId(model.Id); - if (segmentEntity == null) - { + if (segmentEntity == null) { continue; } @@ -50,14 +48,12 @@ public override bool Enqueue(CountlyEventModel model) Log.Debug("[" + GetType().Name + "] Enqueue: \n" + model); bool res = base.Enqueue(model); - if (!res) - { + if (!res) { return false; } SegmentModel segmentModel = model.Segmentation; - if (segmentModel != null) - { + if (segmentModel != null) { SegmentEntity segmentEntity = Converter.ConvertSegmentModelToSegmentEntity(segmentModel, _segmentDao.GenerateNewId()); segmentEntity.EventId = model.Id; _segmentDao.Save(segmentEntity); @@ -72,8 +68,7 @@ public override CountlyEventModel Dequeue() { CountlyEventModel @event = base.Dequeue(); SegmentEntity segmentEntity = _segmentDao.GetByEventId(@event.Id); - if (segmentEntity != null) - { + if (segmentEntity != null) { SegmentModel segmentModel = Converter.ConvertSegmentEntityToSegmentModel(segmentEntity); @event.Segmentation = segmentModel; } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/AbstractEventRepository.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls/NonViewEventRepository.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls/NonViewEventRepository.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls/NonViewEventRepository.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls/NonViewEventRepository.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls/NonViewEventRepository.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls/NonViewEventRepository.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls/NonViewEventRepository.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls/NonViewEventRepository.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls/ViewEventRepository.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls/ViewEventRepository.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls/ViewEventRepository.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls/ViewEventRepository.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls/ViewEventRepository.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls/ViewEventRepository.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Impls/ViewEventRepository.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Impls/ViewEventRepository.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Repository.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Repository.cs similarity index 93% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Repository.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Repository.cs index 6460d7a98..d6346106b 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Repository.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Repository.cs @@ -30,8 +30,7 @@ public virtual bool Enqueue(TModel model) { Log.Verbose("[Repository] Enqueue, TModel: " + model); - if (!ValidateModelBeforeEnqueue(model)) - { + if (!ValidateModelBeforeEnqueue(model)) { return false; } @@ -62,11 +61,9 @@ public virtual void RefreshMemoryCache() Models.Clear(); List entities = _dao.LoadAll(); - foreach (TEntity entity in entities) - { + foreach (TEntity entity in entities) { TModel model = ConvertEntityToModel(entity); - if (!ValidateModelBeforeEnqueue(model)) - { + if (!ValidateModelBeforeEnqueue(model)) { continue; } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Repository.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Repository.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/Repository.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/Repository.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/RequestRepository.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/RequestRepository.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/RequestRepository.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/RequestRepository.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/RequestRepository.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/RequestRepository.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Persistance/Repositories/RequestRepository.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Persistance/Repositories/RequestRepository.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Prefabs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Prefabs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Prefabs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Prefabs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Prefabs/Countly.prefab b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Prefabs/Countly.prefab similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Prefabs/Countly.prefab rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Prefabs/Countly.prefab diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Prefabs/Countly.prefab.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Prefabs/Countly.prefab.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Prefabs/Countly.prefab.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Prefabs/Countly.prefab.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/AbstractBaseService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/AbstractBaseService.cs new file mode 100644 index 000000000..8ccb724ec --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/AbstractBaseService.cs @@ -0,0 +1,209 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Plugins.CountlySDK.Enums; +using Plugins.CountlySDK.Models; + +namespace Plugins.CountlySDK.Services +{ + public abstract class AbstractBaseService + { + internal object LockObj { get; set; } + internal List Listeners { get; set; } + protected CountlyLogHelper Log { get; private set; } + protected readonly CountlyConfiguration _configuration; + protected readonly ConsentCountlyService _consentService; + + protected AbstractBaseService(CountlyConfiguration configuration, CountlyLogHelper logHelper, ConsentCountlyService consentService) + { + Log = logHelper; + _configuration = configuration; + _consentService = consentService; + } + + protected IDictionary RemoveSegmentInvalidDataTypes(IDictionary segments) + { + if (segments == null || segments.Count == 0) { + return segments; + } + + string moduleName = GetType().Name; + int i = 0; + List toRemove = new List(); + foreach (KeyValuePair item in segments) { + if (++i > _configuration.GetMaxSegmentationValues()) { + toRemove.Add(item.Key); + continue; + } + + Type type = item.Value?.GetType(); + bool isValidDataType = item.Value != null + && (type == typeof(int) + || type == typeof(bool) + || type == typeof(float) + || type == typeof(double) + || type == typeof(string) + || type == typeof(long) + || (type.IsArray && IsValidElementType(type.GetElementType())) + || (IsListType(type) && IsValidElementType(type.GetGenericArguments()[0]))); + + if (!isValidDataType) { + toRemove.Add(item.Key); + Log.Warning($"[{moduleName}][RemoveSegmentInvalidDataTypes]: In provided segmentation, value: [{item.Value}], for key: [{item.Key}], is not an allowed data type. Will be removed."); + } + } + + foreach (string k in toRemove) { + segments.Remove(k); + } + + return segments; + } + + private bool IsValidElementType(Type type) + { + return type == typeof(int) + || type == typeof(bool) + || type == typeof(float) + || type == typeof(double) + || type == typeof(string) + || type == typeof(long); + } + + private bool IsValidDataType(object value) + { + if (value == null) { + return false; + } + + Type type = value.GetType(); + + return type == typeof(int) + || type == typeof(bool) + || type == typeof(float) + || type == typeof(double) + || type == typeof(string) + || type == typeof(long) + || (type.IsArray && IsValidElementType(type.GetElementType())) + || (IsListType(type) && IsValidElementType(type.GetGenericArguments()[0])); + } + + private bool IsListType(Type type) + { + return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>); + } + + protected string TrimKey(string k) + { + if (k.Length > _configuration.GetMaxKeyLength()) { + Log.Warning($"[{GetType().Name}][TrimKey]: Max allowed key length is {_configuration.GetMaxKeyLength()}. Key: [{k}] will be truncated."); + k = k.Substring(0, _configuration.GetMaxKeyLength()); + } + + return k; + } + + protected string[] TrimValues(string[] values) + { + for (int i = 0; i < values.Length; ++i) { + if (values[i].Length > _configuration.GetMaxValueSize()) { + Log.Warning($"[{GetType().Name}][TrimValues]: Max allowed value length is {_configuration.GetMaxValueSize()}. Value: [{values[i]}] will be truncated."); + values[i] = values[i].Substring(0, _configuration.GetMaxValueSize()); + } + } + + return values; + } + + protected string TrimValue(string fieldName, string v) + { + if (v != null && v.Length > _configuration.GetMaxValueSize()) { + Log.Warning($"[{GetType().Name}][TrimValue]: Max allowed length for [{fieldName}] is {_configuration.GetMaxValueSize()}. Value: [{v}] will be truncated."); + v = v.Substring(0, _configuration.GetMaxValueSize()); + } + + return v; + } + + protected IDictionary FixSegmentKeysAndValues(IDictionary segments) + { + if (segments == null || segments.Count == 0) { + return segments; + } + + IDictionary segmentation = new Dictionary(); + foreach (KeyValuePair item in segments) { + string k = item.Key; + object v = item.Value; + + if (k == null || k.Length == 0) { + Log.Warning($"[{GetType().Name}][FixSegmentKeysAndValues]: Provided key is {(k == null ? "null" : "empty")}, will be skipped."); + continue; + } + if (v == null) { + Log.Warning($"[{GetType().Name}][FixSegmentKeysAndValues]: Provided value for '[{k}]' is null, will be skipped."); + continue; + } + + k = TrimKey(k); + + if (v.GetType() == typeof(string)) { + v = TrimValue(k, (string)v); + } + + segmentation.Add(k, v); + } + + return segmentation; + } + + protected void LogSegmentation(Dictionary data, string prefix) + { + if (data != null && data.Count > 0) { + StringBuilder validEntries = new StringBuilder(); + StringBuilder invalidEntries = new StringBuilder(); + + foreach (var kvp in data) { + string valueType = kvp.Value?.GetType().ToString() ?? "null"; + string valueStr = kvp.Value?.ToString() ?? "null"; + + if (IsValidDataType(kvp.Value)) { + if (kvp.Value is Array array) { + valueStr = "{" + string.Join(", ", array.Cast()) + "}"; + } else if (IsListType(kvp.Value.GetType())) { + var list = kvp.Value as System.Collections.IEnumerable; + valueStr = "{" + string.Join(", ", list.Cast()) + "}"; + } + + validEntries.AppendLine($"Key: {kvp.Key}, Value: {valueStr}, Type: {valueType}"); + } else { + invalidEntries.AppendLine($"Key: {kvp.Key}, Value: {valueStr}, Type: {valueType}"); + } + } + + if (validEntries.Length > 0) { + Log.Info($"{prefix} Valid Entries:\n{validEntries}"); + } + + if (invalidEntries.Length > 0) { + Log.Warning($"{prefix} Invalid Entries (skipped):\n{invalidEntries}"); + } + } else { + Log.Info($"{prefix} No values provided"); + } + } + + internal virtual void OnInitializationCompleted() { } + internal virtual void DeviceIdChanged(string deviceId, bool merged) { } + internal virtual void ConsentChanged(List updatedConsents, bool newConsentValue, ConsentChangedAction action) { } + } + + internal enum ConsentChangedAction + { + Initialization, + ConsentUpdated, + DeviceIDChangedNotMerged, + } +} diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/AbstractBaseService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/AbstractBaseService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/AbstractBaseService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/AbstractBaseService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ConsentCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ConsentCountlyService.cs similarity index 87% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ConsentCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ConsentCountlyService.cs index a9d8d8c5a..be4595e54 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ConsentCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ConsentCountlyService.cs @@ -6,7 +6,7 @@ using Plugins.CountlySDK.Enums; using Plugins.CountlySDK.Helpers; using Plugins.CountlySDK.Models; - +#pragma warning disable 0618 namespace Plugins.CountlySDK.Services { public class ConsentCountlyService : AbstractBaseService @@ -18,32 +18,26 @@ public class ConsentCountlyService : AbstractBaseService internal ConsentCountlyService(CountlyConfiguration configuration, CountlyLogHelper logHelper, ConsentCountlyService consentService, RequestCountlyHelper requestCountlyHelper) : base(configuration, logHelper, consentService) { - Log.Debug("[ConsentCountlyService] Initializing."); - - if (configuration.RequiresConsent) - { - if (configuration.GivenConsent != null) - { - Log.Debug("[ConsentCountlyService] Enabling consent: " + string.Format("[{0}]", string.Join(", ", configuration.GivenConsent))); - } - - foreach (KeyValuePair entry in configuration.ConsentGroups) - { - Log.Debug("[ConsentCountlyService] Enabling consent group " + entry.Key + ": " + string.Format("[{0}]", string.Join(", ", entry.Value))); - } - } + Log.Debug("[ConsentCountlyService] Initializing."); + + if (configuration.RequiresConsent) { + if (configuration.GivenConsent != null) { + Log.Debug("[ConsentCountlyService] Enabling consent: " + string.Format("[{0}]", string.Join(", ", configuration.GivenConsent))); + } + + foreach (KeyValuePair entry in configuration.ConsentGroups) { + Log.Debug("[ConsentCountlyService] Enabling consent group " + entry.Key + ": " + string.Format("[{0}]", string.Join(", ", entry.Value))); + } + } _requestCountlyHelper = requestCountlyHelper; CountlyConsents = new Dictionary(); RequiresConsent = _configuration.RequiresConsent; _countlyConsentGroups = new Dictionary(_configuration.ConsentGroups); - if (_configuration.EnabledConsentGroups != null) - { - foreach (KeyValuePair entry in _countlyConsentGroups) - { - if (_configuration.EnabledConsentGroups.Contains(entry.Key)) - { + if (_configuration.EnabledConsentGroups != null) { + foreach (KeyValuePair entry in _countlyConsentGroups) { + if (_configuration.EnabledConsentGroups.Contains(entry.Key)) { SetConsentInternal(entry.Value, true, sendRequest: false, ConsentChangedAction.Initialization); } } @@ -60,8 +54,7 @@ internal ConsentCountlyService(CountlyConfiguration configuration, CountlyLogHel /// Returns "true" if the consent for the checked feature has been provided public bool CheckConsent(Consents consent) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[ConsentCountlyService] CheckConsent : consent = " + consent.ToString()); return CheckConsentInternal(consent); } @@ -77,13 +70,13 @@ internal bool CheckConsentInternal(Consents consent) bool result = !RequiresConsent || CheckConsentRawValue(consent); Log.Verbose("[ConsentCountlyService] CheckConsent : consent = " + consent.ToString() + ", result = " + result); return result; - } - - /// - /// Returns the raw consent value as it is stored internally - /// - /// - /// + } + + /// + /// Returns the raw consent value as it is stored internally + /// + /// + /// internal bool CheckConsentRawValue(Consents consent) { return CountlyConsents.ContainsKey(consent) && CountlyConsents[consent]; @@ -97,16 +90,13 @@ internal bool AnyConsentGiven() { bool result = !RequiresConsent; - if (result) - { + if (result) { Log.Verbose("[ConsentCountlyService] AnyConsentGiven = " + result); return result; } - foreach (KeyValuePair entry in CountlyConsents) - { - if (entry.Value) - { + foreach (KeyValuePair entry in CountlyConsents) { + if (entry.Value) { result = true; break; } @@ -124,12 +114,10 @@ internal bool AnyConsentGiven() /// public void GiveConsent(Consents[] consents) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[ConsentCountlyService] GiveConsent : consents = " + (consents != null)); - if (!RequiresConsent) - { + if (!RequiresConsent) { Log.Debug("[ConsentCountlyService] GiveConsent: Please set consent to be required before calling this!"); return; } @@ -144,12 +132,10 @@ public void GiveConsent(Consents[] consents) /// public void GiveConsentAll() { - lock (LockObj) - { + lock (LockObj) { Log.Info("[ConsentCountlyService] GiveConsentAll"); - if (!RequiresConsent) - { + if (!RequiresConsent) { Log.Debug("[ConsentCountlyService] GiveConsentAll: Please set consent to be required before calling this!"); return; } @@ -166,18 +152,15 @@ public void GiveConsentAll() /// public void RemoveConsent(Consents[] consents) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[ConsentCountlyService] RemoveConsent : consents = " + (consents != null)); - if (!RequiresConsent) - { + if (!RequiresConsent) { Log.Debug("[ConsentCountlyService] RemoveConsent: Please set consent to be required before calling this!"); return; } - if (consents == null) - { + if (consents == null) { Log.Debug("[ConsentCountlyService] Calling RemoveConsent with null consents list!"); return; } @@ -195,12 +178,10 @@ public void RemoveConsent(Consents[] consents) /// public void RemoveAllConsent() { - lock (LockObj) - { + lock (LockObj) { Log.Info("[ConsentCountlyService] RemoveAllConsent"); - if (!RequiresConsent) - { + if (!RequiresConsent) { Log.Debug("[ConsentCountlyService] RemoveAllConsent: Please set consent to be required before calling this!"); return; } @@ -216,26 +197,21 @@ public void RemoveAllConsent() /// public void GiveConsentToGroup(string[] groupName) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[ConsentCountlyService] GiveConsentToGroup : groupName = " + (groupName != null)); - if (!RequiresConsent) - { + if (!RequiresConsent) { Log.Debug("[ConsentCountlyService] GiveConsentToGroup: Please set consent to be required before calling this!"); return; } - if (groupName == null) - { + if (groupName == null) { Log.Debug("[ConsentCountlyService] Calling GiveConsentToGroup with null groupName!"); return; } - foreach (string name in groupName) - { - if (_countlyConsentGroups.ContainsKey(name)) - { + foreach (string name in groupName) { + if (_countlyConsentGroups.ContainsKey(name)) { Consents[] consents = _countlyConsentGroups[name]; SetConsentInternal(consents, true, sendRequest: true); } @@ -250,26 +226,21 @@ public void GiveConsentToGroup(string[] groupName) /// public void RemoveConsentOfGroup(string[] groupName) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[ConsentCountlyService] RemoveConsentOfGroup : groupName = " + (groupName != null)); - if (!RequiresConsent) - { + if (!RequiresConsent) { Log.Debug("[ConsentCountlyService] RemoveConsentOfGroup: Please set consent to be required before calling this!"); return; } - if (groupName == null) - { + if (groupName == null) { Log.Debug("[ConsentCountlyService] Calling RemoveConsentOfGroup with null groupName!"); return; } - foreach (string name in groupName) - { - if (_countlyConsentGroups.ContainsKey(name)) - { + foreach (string name in groupName) { + if (_countlyConsentGroups.ContainsKey(name)) { Consents[] consents = _countlyConsentGroups[name]; SetConsentInternal(consents, false, sendRequest: true); } @@ -286,15 +257,13 @@ public void RemoveConsentOfGroup(string[] groupName) /// value to be set internal async Task SendConsentChanges() { - if (!RequiresConsent || _requestCountlyHelper == null) - { + if (!RequiresConsent || _requestCountlyHelper == null) { return; } JObject jObj = new JObject(); Consents[] consents = System.Enum.GetValues(typeof(Consents)).Cast().ToArray(); - foreach (Consents consent in consents) - { + foreach (Consents consent in consents) { jObj.Add(GetConsentKey(consent), CheckConsentRawValue(consent)); } @@ -315,8 +284,7 @@ internal async Task SendConsentChanges() private string GetConsentKey(Consents consent) { string key = ""; - switch (consent) - { + switch (consent) { case Consents.Clicks: key = "clicks"; break; @@ -361,22 +329,18 @@ private string GetConsentKey(Consents consent) /// value to be set internal async void SetConsentInternal(Consents[] consents, bool value, bool sendRequest = false, ConsentChangedAction action = ConsentChangedAction.ConsentUpdated) { - if (consents == null) - { + if (consents == null) { Log.Debug("[ConsentCountlyService] Calling SetConsentInternal with null consents list!"); return; } List updatedConsents = new List(consents.Length); - foreach (Consents consent in consents) - { - if (CountlyConsents.ContainsKey(consent) && CountlyConsents[consent] == value) - { + foreach (Consents consent in consents) { + if (CountlyConsents.ContainsKey(consent) && CountlyConsents[consent] == value) { continue; } - if (!CountlyConsents.ContainsKey(consent) && !value) - { + if (!CountlyConsents.ContainsKey(consent) && !value) { continue; } @@ -386,8 +350,7 @@ internal async void SetConsentInternal(Consents[] consents, bool value, bool sen Log.Debug("[ConsentCountlyService] Setting consent for: [" + consent.ToString() + "] with value: [" + value + "]"); } - if (sendRequest && updatedConsents.Count > 0) - { + if (sendRequest && updatedConsents.Count > 0) { await SendConsentChanges(); } @@ -401,13 +364,11 @@ internal async void SetConsentInternal(Consents[] consents, bool value, bool sen /// Modified Consents's new value private void NotifyListeners(List updatedConsents, bool newConsentValue, ConsentChangedAction action) { - if (Listeners == null || updatedConsents.Count < 1) - { + if (Listeners == null || updatedConsents.Count < 1) { return; } - foreach (AbstractBaseService listener in Listeners) - { + foreach (AbstractBaseService listener in Listeners) { listener.ConsentChanged(updatedConsents, newConsentValue, action); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ConsentCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ConsentCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ConsentCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ConsentCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs similarity index 88% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs index 1acf971a9..01ab4a606 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs @@ -7,6 +7,7 @@ using Plugins.CountlySDK.Helpers; using Plugins.CountlySDK.Models; using UnityEngine; +#pragma warning disable 0618 namespace Plugins.CountlySDK.Services { @@ -27,28 +28,23 @@ internal CrashReportsCountlyService(CountlyConfiguration configuration, CountlyL private string ManipulateStackTrace(string stackTrace) { string result = null; - if (!string.IsNullOrEmpty(stackTrace)) - { + if (!string.IsNullOrEmpty(stackTrace)) { string[] lines = stackTrace.Split('\n'); int limit = lines.Length; - if (limit > _configuration.MaxStackTraceLinesPerThread) - { - limit = _configuration.MaxStackTraceLinesPerThread; + if (limit > _configuration.GetMaxStackTraceLinesPerThread()) { + limit = _configuration.GetMaxStackTraceLinesPerThread(); } - for (int i = 0; i < limit; ++i) - { + for (int i = 0; i < limit; ++i) { string line = lines[i]; - if (line.Length > _configuration.MaxStackTraceLineLength) - { - line = line.Substring(0, _configuration.MaxStackTraceLineLength); + if (line.Length > _configuration.GetMaxStackTraceLineLength()) { + line = line.Substring(0, _configuration.GetMaxStackTraceLineLength()); } - if (i + 1 != limit) - { + if (i + 1 != limit) { line += '\n'; } @@ -73,17 +69,14 @@ private string ManipulateStackTrace(string stackTrace) public async Task SendCrashReportAsync(string message, string stackTrace, LogType type, IDictionary segments = null, bool nonfatal = true) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[CrashReportsCountlyService] SendCrashReportAsync : message = " + message + ", stackTrace = " + stackTrace); - if (!_consentService.CheckConsentInternal(Consents.Crashes)) - { + if (!_consentService.CheckConsentInternal(Consents.Crashes)) { return; } - if (string.IsNullOrEmpty(message) || string.IsNullOrWhiteSpace(message)) - { + if (string.IsNullOrEmpty(message) || string.IsNullOrWhiteSpace(message)) { Log.Warning("[CrashReportsCountlyService] SendCrashReportAsync : The parameter 'message' can't be null or empty"); return; } @@ -97,6 +90,7 @@ public async Task SendCrashReportAsync(string message, string stackTrace, LogTyp await Task.CompletedTask; } + /// /// Public method that sends crash details to the server. Set param "nonfatal" to true for Custom Logged errors /// @@ -107,19 +101,15 @@ public async Task SendCrashReportAsync(string message, string stackTrace, LogTyp /// public async Task SendCrashReportAsync(string message, string stackTrace, IDictionary segments = null, bool nonfatal = true) { - if (_configuration.EnableAutomaticCrashReporting) - { - lock (LockObj) - { + if (_configuration.IsAutomaticCrashReportingEnabled()) { + lock (LockObj) { Log.Info("[CrashReportsCountlyService] SendCrashReportAsync : message = " + message + ", stackTrace = " + stackTrace); - if (!_consentService.CheckConsentInternal(Consents.Crashes)) - { + if (!_consentService.CheckConsentInternal(Consents.Crashes)) { return; } - if (string.IsNullOrEmpty(message) || string.IsNullOrWhiteSpace(message)) - { + if (string.IsNullOrEmpty(message) || string.IsNullOrWhiteSpace(message)) { Log.Warning("[CrashReportsCountlyService] SendCrashReportAsync : The parameter 'message' can't be null or empty"); return; } @@ -134,6 +124,7 @@ public async Task SendCrashReportAsync(string message, string stackTrace, IDicti await Task.CompletedTask; } + internal async Task SendCrashReportInternal(CountlyExceptionDetailModel model) { Log.Debug("[CrashReportsCountlyService] SendCrashReportInternal : model = " + model.ToString()); @@ -148,7 +139,6 @@ internal async Task SendCrashReportInternal(CountlyExceptionDetailModel model) _requestCountlyHelper.AddToRequestQueue(requestParams); await _requestCountlyHelper.ProcessQueue(); - } /// @@ -159,20 +149,17 @@ public void AddBreadcrumbs(string value) { Log.Info("[CrashReportsCountlyService] AddBreadcrumbs : " + value); - if (!_consentService.CheckConsentInternal(Consents.Crashes)) - { + if (!_consentService.CheckConsentInternal(Consents.Crashes)) { return; } - if (_configuration.EnableTestMode) - { + if (_configuration.EnableTestMode) { return; } - string validBreadcrumb = value.Length > _configuration.MaxValueSize ? value.Substring(0, _configuration.MaxValueSize) : value; + string validBreadcrumb = value.Length > _configuration.GetMaxValueSize() ? value.Substring(0, _configuration.GetMaxValueSize()) : value; - if (_crashBreadcrumbs.Count == _configuration.TotalBreadcrumbsAllowed) - { + if (_crashBreadcrumbs.Count >= _configuration.GetMaxBreadcrumbCount()) { _crashBreadcrumbs.Dequeue(); } @@ -189,8 +176,7 @@ public void AddBreadcrumbs(string value) /// CountlyExceptionDetailModel internal CountlyExceptionDetailModel ExceptionDetailModel(string message, string stackTrace, bool nonfatal, IDictionary segments) { - return new CountlyExceptionDetailModel - { + return new CountlyExceptionDetailModel { OS = _configuration.metricHelper.OS, OSVersion = SystemInfo.operatingSystem, Device = SystemInfo.deviceName, diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/CrashReportsCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs similarity index 80% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs index 6e0a55632..764cfaf55 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs @@ -15,10 +15,8 @@ public class DeviceIdCountlyService : AbstractBaseService private readonly EventCountlyService _eventCountlyService; internal readonly RequestCountlyHelper _requestCountlyHelper; private readonly SessionCountlyService _sessionCountlyService; - private readonly int DEVICE_TYPE_FALLBACK_VALUE = -1; - internal DeviceIdCountlyService(CountlyConfiguration configuration, CountlyLogHelper logHelper, SessionCountlyService sessionCountlyService, RequestCountlyHelper requestCountlyHelper, EventCountlyService eventCountlyService, CountlyUtils countlyUtils, ConsentCountlyService consentService) : base(configuration, logHelper, consentService) { @@ -29,6 +27,7 @@ internal DeviceIdCountlyService(CountlyConfiguration configuration, CountlyLogHe _requestCountlyHelper = requestCountlyHelper; _sessionCountlyService = sessionCountlyService; } + /// /// Returns the Device ID that is currently used by the SDK /// @@ -51,8 +50,7 @@ internal void InitDeviceId(string deviceId = null) //User provided DeviceID //Generate Random DeviceID string storedDeviceId = PlayerPrefs.GetString(Constants.DeviceIDKey); - if (!_countlyUtils.IsNullEmptyOrWhitespace(storedDeviceId)) - { + if (!_countlyUtils.IsNullEmptyOrWhitespace(storedDeviceId)) { //SDK already has a device id //assign locally stored device id @@ -62,48 +60,46 @@ internal void InitDeviceId(string deviceId = null) int storedDIDType = PlayerPrefs.GetInt(Constants.DeviceIDTypeKey, DEVICE_TYPE_FALLBACK_VALUE); //checking if we valid device id type - if (storedDIDType == (int)DeviceIdType.SDKGenerated || storedDIDType == (int)DeviceIdType.DeveloperProvided) - { + if (storedDIDType == (int)DeviceIdType.SDKGenerated || storedDIDType == (int)DeviceIdType.DeveloperProvided) { //SDK has a valid device id type in storage. SDK will be using it. DeviceIdType = (DeviceIdType)storedDIDType; - } - else - { - if (storedDIDType == DEVICE_TYPE_FALLBACK_VALUE) - { + } else { + if (storedDIDType == DEVICE_TYPE_FALLBACK_VALUE) { Log.Error("[DeviceIdCountlyService] InitDeviceId: SDK doesn't have device ID type stored. There should have been one."); - } - else - { + } else { Log.Error("[DeviceIdCountlyService] InitDeviceId: The stored device id type wasn't valid ['" + storedDeviceId + "']. SDK will assign a new type"); } - if (_countlyUtils.IsNullEmptyOrWhitespace(deviceId)) - { + if (_countlyUtils.IsNullEmptyOrWhitespace(deviceId)) { UpdateDeviceIdAndDeviceIdType(DeviceId, DeviceIdType.SDKGenerated); - } - else - { + } else { UpdateDeviceIdAndDeviceIdType(DeviceId, DeviceIdType.DeveloperProvided); } } - } - else - { + } else { //SDK doesn't have a device id stored locally - //checking if developer provided device id is null or empty. - if (_countlyUtils.IsNullEmptyOrWhitespace(deviceId)) - { + if (_countlyUtils.IsNullEmptyOrWhitespace(deviceId)) { UpdateDeviceIdAndDeviceIdType(CountlyUtils.GetUniqueDeviceId(), DeviceIdType.SDKGenerated); - } - else - { + } else { UpdateDeviceIdAndDeviceIdType(deviceId, DeviceIdType.DeveloperProvided); } } } + + /// + /// Sets current device id to the new one + /// + /// device id to set + public void SetId(string newDeviceId) + { + lock (LockObj) { + Log.Info("[DeviceIdCountlyService] SetId: deviceId = " + newDeviceId); + SetIdInternal(newDeviceId).Wait(); + } + } + /// /// Changes Device Id. /// Adds currently recorded but not queued events to request queue. @@ -114,13 +110,11 @@ internal void InitDeviceId(string deviceId = null) /// new device id public async Task ChangeDeviceIdWithoutMerge(string deviceId) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[DeviceIdCountlyService] ChangeDeviceIdWithoutMerge: deviceId = " + deviceId); //Ignore call if new and old device id are same - if (DeviceId == deviceId) - { + if (DeviceId == deviceId) { return; } @@ -132,23 +126,20 @@ public async Task ChangeDeviceIdWithoutMerge(string deviceId) //Ends current session //Do not dispose timer object - if (!_configuration.IsAutomaticSessionTrackingDisabled) - { + if (!_configuration.IsAutomaticSessionTrackingDisabled) { _ = _sessionCountlyService.EndSessionAsync(); } //Update device id UpdateDeviceIdAndDeviceIdType(deviceId, DeviceIdType.DeveloperProvided); - if (_consentService.RequiresConsent) - { + if (_consentService.RequiresConsent) { _consentService.SetConsentInternal(_consentService.CountlyConsents.Keys.ToArray(), false, sendRequest: false, ConsentChangedAction.DeviceIDChangedNotMerged); } //Begin new session with new device id //Do not initiate timer again, it is already initiated - if (!_configuration.IsAutomaticSessionTrackingDisabled) - { + if (!_configuration.IsAutomaticSessionTrackingDisabled) { _ = _sessionCountlyService.BeginSessionAsync(); } @@ -168,13 +159,11 @@ public async Task ChangeDeviceIdWithoutMerge(string deviceId) /// new device id public async Task ChangeDeviceIdWithMerge(string deviceId) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[DeviceIdCountlyService] ChangeDeviceIdWithMerge: deviceId = " + deviceId); //Ignore call if new and old device id are same - if (DeviceId == deviceId) - { + if (DeviceId == deviceId) { return; } @@ -196,6 +185,32 @@ public async Task ChangeDeviceIdWithMerge(string deviceId) await Task.CompletedTask; } + private async Task SetIdInternal(string newDeviceId) + { + if (_countlyUtils.IsNullEmptyOrWhitespace(newDeviceId)) { + Log.Warning("[DeviceIdCountlyService] SetId: Provided id to SetId method is null or empty. Will be ignored"); + return; + } + + if (DeviceId == newDeviceId) { + Log.Warning("[DeviceIdCountlyService] SetId: Same id provided to SetId method. Will be ignored."); + return; + } + + // if current type is DEVELOPER_SUPPLIED + // an ID was provided by the host app previously + // we can assume that a device ID change with merge was executed previously + // now we change it without merging + // else + // SDK generated ID + // we change device ID with merge so that data is combined + if (DeviceIdType == DeviceIdType.DeveloperProvided) { + await ChangeDeviceIdWithoutMerge(newDeviceId); + } else { + await ChangeDeviceIdWithMerge(newDeviceId); + } + } + /// /// Updates Device ID both in app and in cache /// @@ -220,18 +235,13 @@ private void UpdateDeviceIdAndDeviceIdType(string newDeviceId, DeviceIdType type /// If passed "true" if will perform a device ID merge server side of the old and new device ID. This will merge their data private void NotifyListeners(bool merged) { - if (Listeners == null) - { + if (Listeners == null) { return; } - foreach (AbstractBaseService listener in Listeners) - { + foreach (AbstractBaseService listener in Listeners) { listener.DeviceIdChanged(DeviceId, merged); } } - - #region override Methods - #endregion } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/DeviceIdCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/EventCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/EventCountlyService.cs similarity index 73% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/EventCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/EventCountlyService.cs index ddd532f8b..522387e55 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/EventCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/EventCountlyService.cs @@ -6,24 +6,29 @@ using Plugins.CountlySDK.Helpers; using Plugins.CountlySDK.Models; using Plugins.CountlySDK.Persistance.Repositories.Impls; +#pragma warning disable CS0618 namespace Plugins.CountlySDK.Services { public class EventCountlyService : AbstractBaseService { private bool isQueueBeingProcessed = false; + string previousEventID = ""; internal readonly NonViewEventRepository _eventRepo; - private readonly RequestCountlyHelper _requestCountlyHelper; - internal readonly IDictionary _timedEvents; - - internal EventCountlyService(CountlyConfiguration configuration, CountlyLogHelper logHelper, RequestCountlyHelper requestCountlyHelper, NonViewEventRepository nonViewEventRepo, ConsentCountlyService consentService) : base(configuration, logHelper, consentService) + internal ISafeIDGenerator safeEventIDGenerator; + internal IViewIDProvider viewIDProvider; + private readonly RequestCountlyHelper _requestCountlyHelper; + private readonly CountlyUtils _utils; + internal EventCountlyService(CountlyConfiguration configuration, CountlyLogHelper logHelper, RequestCountlyHelper requestCountlyHelper, NonViewEventRepository nonViewEventRepo, ConsentCountlyService consentService, CountlyUtils utils) : base(configuration, logHelper, consentService) { Log.Debug("[EventCountlyService] Initializing."); _eventRepo = nonViewEventRepo; _requestCountlyHelper = requestCountlyHelper; _timedEvents = new Dictionary(); + safeEventIDGenerator = configuration.SafeEventIDGenerator; + _utils = utils; } /// @@ -39,17 +44,14 @@ internal void CancelAllTimedEvents() /// internal void AddEventsToRequestQueue() { - Log.Debug("[EventCountlyService] AddEventsToRequestQueue: Start"); - if (_eventRepo.Models.Count == 0) - { + if (_eventRepo.Models.Count == 0) { Log.Debug("[EventCountlyService] AddEventsToRequestQueue: Event queue is empty!"); return; } - if (isQueueBeingProcessed) - { + if (isQueueBeingProcessed) { Log.Verbose("[EventCountlyService] AddEventsToRequestQueue: Event queue being processed!"); return; } @@ -69,8 +71,7 @@ internal void AddEventsToRequestQueue() _requestCountlyHelper.AddToRequestQueue(requestParams); Log.Debug("[EventCountlyService] AddEventsToRequestQueue: Remove events from event queue, count: " + count); - for (int i = 0; i < count; ++i) - { + for (int i = 0; i < count; ++i) { _eventRepo.Dequeue(); } @@ -88,37 +89,65 @@ internal void AddEventsToRequestQueue() /// set sum if needed, default value is "0" /// internal async Task RecordEventInternal(string key, IDictionary segmentation = null, - int? count = 1, double? sum = 0, double? duration = null) + int? count = 1, double? sum = 0, double? duration = null, string eventIDOverride = null) { - if (!CheckConsentOnKey(key)) - { + if (!CheckConsentOnKey(key)) { return; } - if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) - { + if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) { Log.Warning("[EventCountlyService] RecordEventInternal : The event key '" + key + "'isn't valid."); return; } - if (_configuration.EnableTestMode) - { + if (_configuration.EnableTestMode) { return; } - if (key.Length > _configuration.MaxKeyLength) - { + if (key.Length > _configuration.MaxKeyLength) { Log.Warning("[EventCountlyService] RecordEventInternal : Max allowed key length is " + _configuration.MaxKeyLength); key = key.Substring(0, _configuration.MaxKeyLength); } - IDictionary segments = RemoveSegmentInvalidDataTypes(segmentation); - segments = FixSegmentKeysAndValues(segments); + string pvid = null; // previous view id + string cvid = null; // current view id + string eventID; - CountlyEventModel @event = new CountlyEventModel(key, segments, count, sum, duration); + if (_utils.IsNullEmptyOrWhitespace(eventIDOverride)) { + Log.Info("[EventCountlyService] RecordEventInternal provided eventIDOverride value is null, empty or whitespace. Will generate a new one."); + eventID = safeEventIDGenerator.GenerateValue(); + } else { + eventID = eventIDOverride; + } + + if (viewIDProvider != null) { + if (key.Equals(CountlyEventModel.ViewEvent)) { + pvid = viewIDProvider.GetPreviousViewId(); + } else { + cvid = viewIDProvider.GetCurrentViewId(); + } + } - await RecordEventAsync(@event); + IDictionary segments = RemoveSegmentInvalidDataTypes(segmentation); + segments = FixSegmentKeysAndValues(segments); + //before each event is recorded, check if user profile data needs to be saved + Countly.Instance.UserProfile.Save(); + + if (key == CountlyEventModel.NPSEvent || + key == CountlyEventModel.SurveyEvent || + key == CountlyEventModel.StarRatingEvent || + key == CountlyEventModel.OrientationEvent || + key == CountlyEventModel.ViewEvent || + key == CountlyEventModel.PushActionEvent || + key == CountlyEventModel.ViewActionEvent) { + CountlyEventModel @event = new CountlyEventModel(key, segments, count, sum, duration, eventID, pvid, cvid, null); + await RecordEventAsync(@event); + } else { + CountlyEventModel @event = new CountlyEventModel(key, segments, count, sum, duration, eventID, pvid, cvid, previousEventID); + previousEventID = eventID; + await RecordEventAsync(@event); + } } /// @@ -130,15 +159,13 @@ internal async Task RecordEventAsync(CountlyEventModel @event) { Log.Debug("[EventCountlyService] RecordEventAsync : " + @event.ToString()); - if (_configuration.EnableTestMode) - { + if (_configuration.EnableTestMode) { return; } _eventRepo.Enqueue(@event); - if (_eventRepo.Count >= _configuration.EventQueueThreshold) - { + if (_eventRepo.Count >= _configuration.EventQueueThreshold) { AddEventsToRequestQueue(); await _requestCountlyHelper.ProcessQueue(); } @@ -146,35 +173,21 @@ internal async Task RecordEventAsync(CountlyEventModel @event) private bool CheckConsentOnKey(string key) { - if (key.Equals(CountlyEventModel.ViewEvent)) - { + if (key.Equals(CountlyEventModel.ViewEvent)) { return _consentService.CheckConsentInternal(Consents.Views); - } - else if (key.Equals(CountlyEventModel.StarRatingEvent)) - { + } else if (key.Equals(CountlyEventModel.StarRatingEvent)) { return _consentService.CheckConsentInternal(Consents.StarRating); - } - else if (key.Equals(CountlyEventModel.PushActionEvent)) - { + } else if (key.Equals(CountlyEventModel.PushActionEvent)) { return _consentService.CheckConsentInternal(Consents.Push); - } - else if (key.Equals(CountlyEventModel.ViewActionEvent)) - { + } else if (key.Equals(CountlyEventModel.ViewActionEvent)) { return _consentService.CheckConsentInternal(Consents.Clicks); - } - else if (key.Equals(CountlyEventModel.NPSEvent)) - { + } else if (key.Equals(CountlyEventModel.NPSEvent)) { return _consentService.CheckConsentInternal(Consents.Feedback); - } - else if (key.Equals(CountlyEventModel.SurveyEvent)) - { + } else if (key.Equals(CountlyEventModel.SurveyEvent)) { return _consentService.CheckConsentInternal(Consents.Feedback); - } - else if (key.Equals(CountlyEventModel.OrientationEvent)) - { + } else if (key.Equals(CountlyEventModel.OrientationEvent)) { return _consentService.CheckConsentInternal(Consents.Users); - } - else { return _consentService.CheckConsentInternal(Consents.Events); } + } else { return _consentService.CheckConsentInternal(Consents.Events); } } /// @@ -184,23 +197,19 @@ private bool CheckConsentOnKey(string key) /// public void StartEvent(string key) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[EventCountlyService] StartEvent : key = " + key); - if (!_consentService.CheckConsentInternal(Consents.Events)) - { + if (!_consentService.CheckConsentInternal(Consents.Events)) { return; } - if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) - { + if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) { Log.Warning("[EventCountlyService] StartEvent : The event key '" + key + "' isn't valid."); return; } - if (_timedEvents.ContainsKey(key)) - { + if (_timedEvents.ContainsKey(key)) { Log.Warning("[EventCountlyService] StartEvent : Event with key '" + key + "' has already started."); return; } @@ -218,23 +227,19 @@ public void StartEvent(string key) /// public void CancelEvent(string key) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[EventCountlyService] CancelEvent : key = " + key); - if (!_consentService.CheckConsentInternal(Consents.Events)) - { + if (!_consentService.CheckConsentInternal(Consents.Events)) { return; } - if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) - { + if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) { Log.Warning("[EventCountlyService] CancelEvent : The event key '" + key + "' isn't valid."); return; } - if (!_timedEvents.ContainsKey(key)) - { + if (!_timedEvents.ContainsKey(key)) { Log.Warning("[EventCountlyService] CancelEvent : Time event with key '" + key + "' doesn't exist."); return; } @@ -254,23 +259,19 @@ public void CancelEvent(string key) /// public void EndEvent(string key, IDictionary segmentation = null, int? count = 1, double? sum = 0) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[EventCountlyService] EndEvent : key = " + key + ", segmentation = " + segmentation + ", count = " + count + ", sum = " + sum); - if (!_consentService.CheckConsentInternal(Consents.Events)) - { + if (!_consentService.CheckConsentInternal(Consents.Events)) { return; } - if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) - { + if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) { Log.Warning("[EventCountlyService] EndEvent : The event key '" + key + "' isn't valid."); return; } - if (!_timedEvents.ContainsKey(key)) - { + if (!_timedEvents.ContainsKey(key)) { Log.Warning("[EventCountlyService] EndEvent : Time event with key '" + key + "' doesn't exist."); return; } @@ -293,13 +294,12 @@ public void EndEvent(string key, IDictionary segmentation = null /// custom segmentation you want to set, leave null if you don't want to add anything /// how many of these events have occurred, default value is "1" /// set sum if needed, default value is "0" - /// set sum if needed, default value is "0" + /// set duration if needed, default value is "null" /// public async Task RecordEventAsync(string key, IDictionary segmentation = null, int? count = 1, double? sum = 0, double? duration = null) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[EventCountlyService] RecordEventAsync : key = " + key + ", segmentation = " + segmentation + ", count = " + count + ", sum = " + sum + ", duration = " + duration); _ = RecordEventInternal(key, segmentation, count, sum, duration); @@ -311,11 +311,10 @@ public async Task RecordEventAsync(string key, IDictionary segme #region override Methods internal override void ConsentChanged(List updatedConsents, bool newConsentValue, ConsentChangedAction action) { - if (updatedConsents.Contains(Consents.Events) && !newConsentValue) - { + if (updatedConsents.Contains(Consents.Events) && !newConsentValue) { CancelAllTimedEvents(); } } #endregion } -} +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/EventCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/EventCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/EventCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/EventCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/InitializationCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/InitializationCountlyService.cs similarity index 96% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/InitializationCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/InitializationCountlyService.cs index 78e67e26a..53eb3ea74 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/InitializationCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/InitializationCountlyService.cs @@ -20,8 +20,7 @@ internal InitializationCountlyService(CountlyConfiguration configuration, Countl internal async Task OnInitialisationComplete() { - lock (LockObj) - { + lock (LockObj) { _ = _consentService.SendConsentChanges(); _ = _sessionService.StartSessionService(); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/InitializationCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/InitializationCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/InitializationCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/InitializationCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/Legacy.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/Legacy.meta new file mode 100644 index 000000000..f2576f6dd --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/Legacy.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e79b3b516b5f84eacad0fd5ebff61be5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/UserDetailsCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/Legacy/UserDetailsCountlyService.cs similarity index 51% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/UserDetailsCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/Legacy/UserDetailsCountlyService.cs index 51845e627..c60f5ce05 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/UserDetailsCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/Legacy/UserDetailsCountlyService.cs @@ -12,7 +12,6 @@ namespace Plugins.CountlySDK.Services public class UserDetailsCountlyService : AbstractBaseService { internal Dictionary CustomDataProperties { get; private set; } - private readonly CountlyUtils _countlyUtils; internal readonly RequestCountlyHelper _requestCountlyHelper; internal UserDetailsCountlyService(CountlyConfiguration configuration, CountlyLogHelper logHelper, RequestCountlyHelper requestCountlyHelper, CountlyUtils countlyUtils, ConsentCountlyService consentService) : base(configuration, logHelper, consentService) @@ -24,58 +23,188 @@ internal UserDetailsCountlyService(CountlyConfiguration configuration, CountlyLo CustomDataProperties = new Dictionary(); } + #region PublicAPI /// /// Add user custom detail to request queue. /// - /// - private void AddCustomDetailToRequestQueue(IDictionary segments) + /// User Model with the specified params + public async Task SetUserDetailsAsync(CountlyUserDetailsModel userDetailsModel) { + Log.Info("[UserDetailsCountlyService] SetUserDetailsAsync"); + await SetUserDetailsInternal(userDetailsModel); + } - IDictionary customDetail = FixSegmentKeysAndValues(segments); + /// + /// Sets information about user with custom properties. + /// In custom properties you can provide any string key values to be stored with user. + /// + /// User custom detail + public void SetCustomUserDetails(Dictionary customDetail) + { + Log.Info("[UserDetailsCountlyService] SetCustomUserDetails," + (customDetail != null)); + AddCustomDetailToRequestQueue(customDetail); + } - Dictionary requestParams = - new Dictionary - { - { "user_details", - JsonConvert.SerializeObject( - new Dictionary - { - { "custom", customDetail } - }) - } - }; - _requestCountlyHelper.AddToRequestQueue(requestParams); - _ = _requestCountlyHelper.ProcessQueue(); + /// + /// Send provided values to server. + /// + public async Task SaveAsync() + { + Log.Info("[UserDetailsCountlyService] SaveAsync"); + await SaveAsyncInternal(); + } + + /// + /// Sets custom provide key/value as custom property. + /// + /// string with key for the property + /// string with value for the property + public void Set(string key, string value) + { + Log.Info("[UserDetailsCountlyService] Set," + "key:[" + key + "]" + " value:[" + value + "]"); + SetInternal(key, value); + } + + /// + /// Set value only if property does not exist yet. + /// + /// string with property name to set + /// string value to set + public void SetOnce(string key, string value) + { + Log.Info("[UserDetailsCountlyService] SetOnce," + "key:[" + key + "]" + " value:[" + value + "]"); + SetOnceInternal(key, value); + } + + /// + /// Increment custom property value by 1. + /// + /// string with property name to increment + public void Increment(string key) + { + Log.Info("[UserDetailsCountlyService] Increment," + "key:[" + key + "]"); + IncrementInternal(key, 1); + } + + /// + /// Increment custom property value by provided value. + /// + /// string with property name to increment + /// double value by which to increment + public void IncrementBy(string key, double value) + { + Log.Info("[UserDetailsCountlyService] IncrementBy," + "key:[" + key + "]" + " value:[" + value + "]"); + IncrementInternal(key, value); + } + + /// + /// Multiply custom property value by provided value. + /// + /// string with property name to multiply + /// double value by which to multiply + public void Multiply(string key, double value) + { + Log.Info("[UserDetailsCountlyService] Multiply," + "key:[" + key + "]" + " value:[" + value + "]"); + MultiplyInternal(key, value); + } + + /// + /// Save maximal value between existing and provided. + /// + /// String with property name to check for max + /// double value to check for max + public void Max(string key, double value) + { + Log.Info("[UserDetailsCountlyService] Max," + "key:[" + key + "]" + " value:[" + value + "]"); + MaxInternal(key, value); + } + + /// + /// Save minimal value between existing and provided. + /// + /// string with property name to check for min + /// double value to check for min + public void Min(string key, double value) + { + Log.Info("[UserDetailsCountlyService] Min," + "key:[" + key + "]" + " value:[" + value + "]"); + MinInternal(key, value); + } + + /// + /// Create array property, if property does not exist and add value to array + /// You can only use it on array properties or properties that do not exist yet. + /// + /// string with property name for array property + /// array with values to add + public void Push(string key, string[] value) + { + Log.Info("[UserDetailsCountlyService] Push," + "key:[" + key + "]" + " value:[" + value + "]"); + PushInternal(key, value); + } + + /// + /// Create array property, if property does not exist and add value to array, only if value is not yet in the array + /// You can only use it on array properties or properties that do not exist yet. + /// + /// string with property name for array property + /// array with values to add + public void PushUnique(string key, string[] value) + { + Log.Info("[UserDetailsCountlyService] PushUnique," + "key:[" + key + "]" + " value:[" + value + "]"); + PushUniqueInternal(key, value); + } + + /// + /// Create array property, if property does not exist and remove value from array. + /// + /// String with property name for array property + /// array with values to remove from array + public void Pull(string key, string[] value) + { + Log.Info("[UserDetailsCountlyService] Pull," + "key:[" + key + "]" + " value:[" + value + "]"); + PullInternal(key, value); + } + + /// + /// Checks if the specified key exists in the CustomDataProperties dictionary. + /// + public bool ContainsCustomDataKey(string key) + { + return CustomDataProperties.ContainsKey(key); } + /// + /// Retrieves the value for the specified key from the CustomDataProperties dictionary, or null if the key is not found. + /// + public object RetrieveCustomDataValue(string key) + { + return CustomDataProperties.ContainsKey(key) ? CustomDataProperties[key] : null; + } + #endregion + #region Internal Calls /// /// Sets information about user. /// /// User Model with the specified params - /// - public async Task SetUserDetailsAsync(CountlyUserDetailsModel userDetailsModel) + private async Task SetUserDetailsInternal(CountlyUserDetailsModel userDetailsModel) { - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] SetUserDetailsAsync " + (userDetailsModel != null)); + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] SetUserDetailsInternal, " + (userDetailsModel != null)); - if (!_consentService.CheckConsentInternal(Consents.Users)) - { + if (!_consentService.CheckConsentInternal(Consents.Users)) { + Log.Debug("[UserDetailsCountlyService] SetUserDetailsInternal, consent is not given, ignoring the request."); return; } - if (userDetailsModel == null) - { - Log.Warning("[UserDetailsCountlyService] SetUserDetailsAsync : The parameter 'userDetailsModel' can't be null."); + if (userDetailsModel == null) { + Log.Warning("[UserDetailsCountlyService] SetUserDetailsInternal, The parameter 'userDetailsModel' can't be null."); return; } - if (!_countlyUtils.IsPictureValid(userDetailsModel.PictureUrl)) - { - Log.Warning($"[UserDetailsCountlyService] SetUserDetailAsync: Picture format for URL '{userDetailsModel.PictureUrl}' is not as expected. Expected formats are .png, .gif, or .jpeg"); + if (!_countlyUtils.IsPictureValid(userDetailsModel.PictureUrl)) { + Log.Warning($"[UserDetailsCountlyService] SetUserDetailsInternal, Picture format for URL '{userDetailsModel.PictureUrl}' is not as expected. Expected formats are .png, .gif, or .jpeg"); } - userDetailsModel.Name = TrimValue("Name", userDetailsModel.Name); userDetailsModel.Phone = TrimValue("Phone", userDetailsModel.Phone); userDetailsModel.Email = TrimValue("Email", userDetailsModel.Email); @@ -84,9 +213,8 @@ public async Task SetUserDetailsAsync(CountlyUserDetailsModel userDetailsModel) userDetailsModel.BirthYear = TrimValue("BirthYear", userDetailsModel.BirthYear); userDetailsModel.Organization = TrimValue("Organization", userDetailsModel.Organization); - if (userDetailsModel.PictureUrl != null && userDetailsModel.PictureUrl.Length > 4096) - { - Log.Warning("[" + GetType().Name + "] TrimValue : Max allowed length of 'PictureUrl' is " + _configuration.MaxValueSize); + if (userDetailsModel.PictureUrl != null && userDetailsModel.PictureUrl.Length > 4096) { + Log.Warning("[" + GetType().Name + "] TrimValue : Max allowed length of 'PictureUrl' is " + _configuration.GetMaxValueSize()); userDetailsModel.PictureUrl = userDetailsModel.PictureUrl.Substring(0, 4096); } @@ -104,75 +232,77 @@ public async Task SetUserDetailsAsync(CountlyUserDetailsModel userDetailsModel) await Task.CompletedTask; } + /// - /// Sets information about user with custom properties. - /// In custom properties you can provide any string key values to be stored with user. + /// Add user custom detail to request queue. /// - /// User custom detail /// - public void SetCustomUserDetails(Dictionary customDetail) + private void AddCustomDetailToRequestQueue(IDictionary segments) { - Log.Info("[UserDetailsCountlyService] SetCustomUserDetails " + (customDetail != null)); - - if (!_consentService.CheckConsentInternal(Consents.Users)) - { + if (!_consentService.CheckConsentInternal(Consents.Users)) { + Log.Debug("[UserDetailsCountlyService] AddCustomDetailToRequestQueue, consent is not given, ignoring the request."); return; } - if (customDetail == null || customDetail.Count == 0) - { - Log.Warning("[UserDetailsCountlyService] SetCustomUserDetails : Provided custom detail 'customDetail' can't be null or empty."); - + if (segments == null || segments.Count == 0) { + Log.Warning("[UserDetailsCountlyService] AddCustomDetailToRequestQueue, Provided custom detail 'customDetail' can't be null or empty."); return; } - AddCustomDetailToRequestQueue(customDetail); + IDictionary customDetail = FixSegmentKeysAndValues(segments); + + Dictionary requestParams = + new Dictionary + { + { "user_details", + JsonConvert.SerializeObject( + new Dictionary + { + { "custom", customDetail } + }) + } + }; + _requestCountlyHelper.AddToRequestQueue(requestParams); + _ = _requestCountlyHelper.ProcessQueue(); } /// /// Send provided values to server. /// - /// - public async Task SaveAsync() + private async Task SaveAsyncInternal() { - lock (LockObj) - { - if (!CustomDataProperties.Any()) - { + if (!_consentService.CheckConsentInternal(Consents.Users)) { + Log.Debug("[UserDetailsCountlyService] SaveAsyncInternal, consent is not given, ignoring the request."); + return; + } + + lock (LockObj) { + if (!CustomDataProperties.Any()) { return; } - Log.Info("[UserDetailsCountlyService] SaveAsync"); - - + Log.Info("[UserDetailsCountlyService] SaveAsyncInternal"); CountlyUserDetailsModel model = new CountlyUserDetailsModel(CustomDataProperties); - CustomDataProperties = new Dictionary { }; AddCustomDetailToRequestQueue(CustomDataProperties); } + await Task.CompletedTask; } - /// /// Sets custom provide key/value as custom property. /// /// string with key for the property /// string with value for the property - public void Set(string key, string value) + private void SetInternal(string key, string value) { - - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] Set : key '" + key + "'isn't valid."); - + if (!ValidateConsentAndKey(key, "SetInternal")) { return; } - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] Set : key = " + key + ", value = " + value); - + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] SetInternal, key:[" + key + "]" + " value:[" + value + "]"); AddToCustomData(key, TrimValue(key, value)); } } @@ -180,63 +310,33 @@ public void Set(string key, string value) /// /// Set value only if property does not exist yet. /// - /// string with property name to set - /// string value to set - public void SetOnce(string key, string value) + /// string with key for the property + /// string with value for the property + private void SetOnceInternal(string key, string value) { - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] SetOnce : key '" + key + "'isn't valid."); - + if (!ValidateConsentAndKey(key, "SetOnceInternal")) { return; } - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] SetOnce : key = " + key + ", value = " + value); - + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] SetOnceInternal, key:[" + key + "]" + " value:[" + value + "]"); AddToCustomData(key, new Dictionary { { "$setOnce", TrimValue(key, value) } }); } } /// - /// Increment custom property value by 1. + /// Increments the custom data value by the specified amount. /// - /// string with property name to increment - public void Increment(string key) + /// The key for the custom data. + /// The amount by which to increment. + private void IncrementInternal(string key, double value) { - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] Increment : key '" + key + "'isn't valid."); - + if (!ValidateConsentAndKey(key, "IncrementInternal")) { return; } - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] Increment : key = " + key); - - AddToCustomData(key, new Dictionary { { "$inc", 1 } }); - } - } - - /// - /// Increment custom property value by provided value. - /// - /// string with property name to increment - /// double value by which to increment - public void IncrementBy(string key, double value) - { - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] IncrementBy : key '" + key + "'isn't valid."); - - return; - } - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] IncrementBy : key = " + key + ", value = " + value); - + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] IncrementInternal, key:[" + key + "]" + " value:[" + value + "]"); AddToCustomData(key, new Dictionary { { "$inc", value } }); } } @@ -246,19 +346,14 @@ public void IncrementBy(string key, double value) /// /// string with property name to multiply /// double value by which to multiply - public void Multiply(string key, double value) + private void MultiplyInternal(string key, double value) { - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] Multiply : key '" + key + "'isn't valid."); - + if (!ValidateConsentAndKey(key, "MultiplyInternal")) { return; } - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] Multiply : key = " + key + ", value = " + value); - + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] MultiplyInternal, key:[" + key + "]" + " value:[" + value + "]"); AddToCustomData(key, new Dictionary { { "$mul", value } }); } } @@ -268,19 +363,14 @@ public void Multiply(string key, double value) /// /// String with property name to check for max /// double value to check for max - public void Max(string key, double value) + private void MaxInternal(string key, double value) { - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] Max : key '" + key + "'isn't valid."); - + if (!ValidateConsentAndKey(key, "MaxInternal")) { return; } - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] Max : key = " + key + ", value = " + value); - + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] MaxInternal, key:[" + key + "]" + " value:[" + value + "]"); AddToCustomData(key, new Dictionary { { "$max", value } }); } } @@ -290,43 +380,31 @@ public void Max(string key, double value) /// /// string with property name to check for min /// double value to check for min - public void Min(string key, double value) + private void MinInternal(string key, double value) { - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] Min : key '" + key + "'isn't valid."); - + if (!ValidateConsentAndKey(key, "MinInternal")) { return; } - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] Min : key = " + key + ", value = " + value); - + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] MinInternal, key:[" + key + "]" + " value:[" + value + "]"); AddToCustomData(key, new Dictionary { { "$min", value } }); } } /// - /// Create array property, if property does not exist and add value to array - /// You can only use it on array properties or properties that do not exist yet. + /// Adds the values to the custom data array based on the pushUnique flag. /// - /// string with property name for array property - /// array with values to add - public void Push(string key, string[] value) + /// The key for the custom data. + /// The array of values to be added. + private void PushInternal(string key, string[] value) { - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] Push : key '" + key + "'isn't valid."); - + if (!ValidateConsentAndKey(key, "PushInternal")) { return; } - - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] Push : key = " + key + ", value = " + value); - + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] PushInternal, key:[" + key + "]" + " value:[" + string.Join(", ", value) + "]"); AddToCustomData(key, new Dictionary { { "$push", TrimValues(value) } }); } } @@ -335,21 +413,16 @@ public void Push(string key, string[] value) /// Create array property, if property does not exist and add value to array, only if value is not yet in the array /// You can only use it on array properties or properties that do not exist yet. /// - /// string with property name for array property - /// array with values to add - public void PushUnique(string key, string[] value) + /// The key for the custom data. + /// The array of values to be added. + private void PushUniqueInternal(string key, string[] value) { - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] PushUnique : key '" + key + "'isn't valid."); - + if (!ValidateConsentAndKey(key)) { return; } - - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] PushUnique : key = " + key + ", value = " + value); + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] PushInternal, key:[" + key + "]" + " value:[" + string.Join(", ", value) + "]"); AddToCustomData(key, new Dictionary { { "$addToSet", TrimValues(value) } }); } } @@ -359,25 +432,19 @@ public void PushUnique(string key, string[] value) /// /// String with property name for array property /// array with values to remove from array - public void Pull(string key, string[] value) + private void PullInternal(string key, string[] value) { - if (string.IsNullOrEmpty(key)) - { - Log.Warning("[UserDetailsCountlyService] Pull : key '" + key + "'isn't valid."); - + if (!ValidateConsentAndKey(key, "PullInternal")) { return; } - lock (LockObj) - { - Log.Info("[UserDetailsCountlyService] Pull : key = " + key + ", value = " + value); - + lock (LockObj) { + Log.Info("[UserDetailsCountlyService] PullInternal, key:[" + key + "]" + " value:[" + value + "]"); value = TrimValues(value); AddToCustomData(key, new Dictionary { { "$pull", value } }); } } - /// /// Create a property /// @@ -385,20 +452,17 @@ public void Pull(string key, string[] value) /// property value private void AddToCustomData(string key, object value) { - Log.Debug("[UserDetailsCountlyService] AddToCustomData: " + key + ", " + value); + Log.Debug("[UserDetailsCountlyService] AddToCustomData, key:[" + key + "]" + " value:[" + value + "]"); - if (!_consentService.CheckConsentInternal(Consents.Users)) - { + if (!ValidateConsentAndKey(key, "AddToCustomData")) { return; } key = TrimKey(key); - if (CustomDataProperties.ContainsKey(key)) - { + if (CustomDataProperties.ContainsKey(key)) { string item = CustomDataProperties.Select(x => x.Key).FirstOrDefault(x => x.Equals(key, StringComparison.OrdinalIgnoreCase)); - if (item != null) - { + if (item != null) { CustomDataProperties.Remove(item); } } @@ -406,7 +470,24 @@ private void AddToCustomData(string key, object value) CustomDataProperties.Add(key, value); } - #region override Methods + /// + /// Checks if an internal call is providing valid key and has consent + /// + /// property name + private bool ValidateConsentAndKey(string key, string caller = null) + { + if (!_consentService.CheckConsentInternal(Consents.Users)) { + Log.Debug($"[UserDetailsCountlyService][{caller}] Consent is not given, ignoring the request."); + return false; + } + + if (string.IsNullOrEmpty(key)) { + Log.Warning($"[UserDetailsCountlyService][{caller}] Provided key isn't valid."); + return false; + } + + return true; + } #endregion } -} +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/UserDetailsCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/Legacy/UserDetailsCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/UserDetailsCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/Legacy/UserDetailsCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/LocationService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/LocationService.cs similarity index 89% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/LocationService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/LocationService.cs index a6bc814ca..b734e82fb 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/LocationService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/LocationService.cs @@ -20,28 +20,23 @@ public class LocationService : AbstractBaseService internal LocationService(CountlyConfiguration configuration, CountlyLogHelper logHelper, RequestCountlyHelper requestCountlyHelper, ConsentCountlyService consentService) : base(configuration, logHelper, consentService) { Log.Debug("[LocationService] Initializing."); - if (configuration.IsLocationDisabled) - { + if (configuration.IsLocationDisabled) { Log.Debug("[LocationService] Disabling location"); } - if (configuration.CountryCode != null || configuration.City != null || configuration.Location != null || configuration.IPAddress != null) - { + if (configuration.CountryCode != null || configuration.City != null || configuration.Location != null || configuration.IPAddress != null) { Log.Debug("[LocationService] location: countryCode = [" + configuration.CountryCode + "], city = [" + configuration.City + "], gpsCoordinates = [" + configuration.Location + ",] ipAddress = [" + configuration.IPAddress + "]"); } _requestCountlyHelper = requestCountlyHelper; IsLocationDisabled = configuration.IsLocationDisabled; - if (IsLocationDisabled || !_consentService.CheckConsentInternal(Consents.Location)) - { + if (IsLocationDisabled || !_consentService.CheckConsentInternal(Consents.Location)) { City = null; Location = null; IPAddress = null; CountryCode = null; - } - else - { + } else { City = configuration.City; Location = configuration.Location; IPAddress = configuration.IPAddress; @@ -70,8 +65,7 @@ internal async Task SendIndependantLocationRequest() { Log.Debug("[LocationService] SendIndependantLocationRequest"); - if (!_consentService.CheckConsentInternal(Consents.Location)) - { + if (!_consentService.CheckConsentInternal(Consents.Location)) { return; } @@ -82,28 +76,23 @@ internal async Task SendIndependantLocationRequest() * Empty country code, city and IP address can not be sent. */ - if (!string.IsNullOrEmpty(IPAddress)) - { + if (!string.IsNullOrEmpty(IPAddress)) { requestParams.Add("ip_address", IPAddress); } - if (!string.IsNullOrEmpty(CountryCode)) - { + if (!string.IsNullOrEmpty(CountryCode)) { requestParams.Add("country_code", CountryCode); } - if (!string.IsNullOrEmpty(City)) - { + if (!string.IsNullOrEmpty(City)) { requestParams.Add("city", City); } - if (!string.IsNullOrEmpty(Location)) - { + if (!string.IsNullOrEmpty(Location)) { requestParams.Add("location", Location); } - if (requestParams.Count > 0) - { + if (requestParams.Count > 0) { _requestCountlyHelper.AddToRequestQueue(requestParams); await _requestCountlyHelper.ProcessQueue(); } @@ -116,12 +105,10 @@ internal async Task SendIndependantLocationRequest() /// public async void DisableLocation() { - lock (LockObj) - { + lock (LockObj) { Log.Info("[LocationService] DisableLocation"); - if (!_consentService.CheckConsentInternal(Consents.Location)) - { + if (!_consentService.CheckConsentInternal(Consents.Location)) { return; } @@ -152,12 +139,10 @@ public async void DisableLocation() /// public async void SetLocation(string countryCode, string city, string gpsCoordinates, string ipAddress) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[LocationService] SetLocation : countryCode = " + countryCode + ", city = " + city + ", gpsCoordinates = " + gpsCoordinates + ", ipAddress = " + ipAddress); - if (!_consentService.CheckConsentInternal(Consents.Location)) - { + if (!_consentService.CheckConsentInternal(Consents.Location)) { return; } @@ -165,8 +150,7 @@ public async void SetLocation(string countryCode, string city, string gpsCoordin * a warning should be printed that they should be set together. */ if ((!string.IsNullOrEmpty(CountryCode) && string.IsNullOrEmpty(City)) - || (!string.IsNullOrEmpty(City) && string.IsNullOrEmpty(CountryCode))) - { + || (!string.IsNullOrEmpty(City) && string.IsNullOrEmpty(CountryCode))) { Log.Warning("[LocationService] In \"SetLocation\" both country code and city should be set together"); } @@ -179,8 +163,7 @@ public async void SetLocation(string countryCode, string city, string gpsCoordin * If location consent is given and location gets re-enabled (previously was disabled), * we send that set location information in a separate request and save it in the internal location cache. */ - if (countryCode != null || city != null || gpsCoordinates != null || ipAddress != null) - { + if (countryCode != null || city != null || gpsCoordinates != null || ipAddress != null) { IsLocationDisabled = false; _ = SendIndependantLocationRequest(); } @@ -205,8 +188,7 @@ private async void OnLocationConsentRemoved() #region override Methods internal override void ConsentChanged(List updatedConsents, bool newConsentValue, ConsentChangedAction action) { - if (action != ConsentChangedAction.DeviceIDChangedNotMerged && updatedConsents.Contains(Consents.Location) && !newConsentValue) - { + if (action != ConsentChangedAction.DeviceIDChangedNotMerged && updatedConsents.Contains(Consents.Location) && !newConsentValue) { OnLocationConsentRemoved(); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/LocationService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/LocationService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/LocationService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/LocationService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/PushCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/PushCountlyService.cs similarity index 94% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/PushCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/PushCountlyService.cs index e74430ce5..9e1aacc7b 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/PushCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/PushCountlyService.cs @@ -5,6 +5,7 @@ using Plugins.CountlySDK.Enums; using Plugins.CountlySDK.Helpers; using Plugins.CountlySDK.Models; +#pragma warning disable CS0618 namespace Plugins.CountlySDK.Services { @@ -20,8 +21,7 @@ public class PushCountlyService : AbstractBaseService internal PushCountlyService(CountlyConfiguration configuration, CountlyLogHelper logHelper, RequestCountlyHelper requestCountlyHelper, INotificationsService notificationsService, NotificationsCallbackService notificationsCallbackService, ConsentCountlyService consentService) : base(configuration, logHelper, consentService) { Log.Debug("[PushCountlyService] Initializing."); - if (configuration.NotificationEventListeners.Count > 0) - { + if (configuration.NotificationEventListeners.Count > 0) { Log.Debug("[PushCountlyService] Registering " + configuration.NotificationEventListeners.Count + " notification event listeners."); } @@ -38,8 +38,7 @@ private void EnableNotification() Log.Debug("[PushCountlyService] EnableNotification"); //Enables push notification on start - if (_configuration.EnableTestMode || !_consentService.CheckConsentInternal(Consents.Push) || _configuration.NotificationMode == TestMode.None) - { + if (_configuration.EnableTestMode || !_consentService.CheckConsentInternal(Consents.Push) || _configuration.NotificationMode == TestMode.None) { return; } @@ -57,8 +56,7 @@ private void EnablePushNotificationAsync(TestMode mode) _mode = mode; _isDeviceRegistered = true; - _notificationsService.GetToken(async result => - { + _notificationsService.GetToken(async result => { _token = result; /* * When the push notification service gets enabled successfully for the device, @@ -68,14 +66,12 @@ private void EnablePushNotificationAsync(TestMode mode) await ReportPushActionAsync(); }); - _notificationsService.OnNotificationClicked(async (data, index) => - { + _notificationsService.OnNotificationClicked(async (data, index) => { _notificationsCallbackService.NotifyOnNotificationClicked(data, index); await ReportPushActionAsync(); }); - _notificationsService.OnNotificationReceived(data => - { + _notificationsService.OnNotificationReceived(data => { _notificationsCallbackService.NotifyOnNotificationReceived(data); }); @@ -89,8 +85,7 @@ private async Task PostToCountlyAsync(TestMode? mode, string token) { Log.Debug("[PushCountlyService] PostToCountlyAsync : token = " + token); - if (!_mode.HasValue || !_consentService.CheckConsentInternal(Consents.Push)) - { + if (!_mode.HasValue || !_consentService.CheckConsentInternal(Consents.Push)) { return; } @@ -113,8 +108,7 @@ private async Task ReportPushActionAsync() { Log.Debug("[PushCountlyService] ReportPushActionAsync"); - if (!_consentService.CheckConsentInternal(Consents.Push)) - { + if (!_consentService.CheckConsentInternal(Consents.Push)) { return new CountlyResponse { IsSuccess = false }; } @@ -129,8 +123,7 @@ internal override void OnInitializationCompleted() } internal override void ConsentChanged(List updatedConsents, bool newConsentValue, ConsentChangedAction action) { - if (updatedConsents.Contains(Consents.Push) && newConsentValue && !_isDeviceRegistered) - { + if (updatedConsents.Contains(Consents.Push) && newConsentValue && !_isDeviceRegistered) { EnableNotification(); } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/PushCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/PushCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/PushCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/PushCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs similarity index 89% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs index 106102e59..773d3f831 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs @@ -11,6 +11,7 @@ using Plugins.iBoxDB; using UnityEngine; using UnityEngine.Networking; +#pragma warning disable 0618 namespace Plugins.CountlySDK.Services { @@ -37,12 +38,9 @@ internal RemoteConfigCountlyService(CountlyConfiguration configuration, CountlyL _requestBuilder = requestBuilder; _requestCountlyHelper = requestCountlyHelper; - if (_consentService.CheckConsentInternal(Consents.RemoteConfig)) - { + if (_consentService.CheckConsentInternal(Consents.RemoteConfig)) { Configs = FetchConfigFromDB(); - } - else - { + } else { _configDao.RemoveAll(); } @@ -55,8 +53,7 @@ internal async Task InitConfig() { Log.Debug("[RemoteConfigCountlyService] InitConfig"); - if (_configuration.EnableTestMode) - { + if (_configuration.EnableTestMode) { return new CountlyResponse { IsSuccess = true }; } @@ -71,8 +68,7 @@ private Dictionary FetchConfigFromDB() { Dictionary config = null; List allConfigs = _configDao.LoadAll(); - if (allConfigs != null && allConfigs.Count > 0) - { + if (allConfigs != null && allConfigs.Count > 0) { config = Converter.ConvertJsonToDictionary(allConfigs[0].Json, Log); } @@ -89,10 +85,8 @@ public async Task Update() { Log.Info("[RemoteConfigCountlyService] Update"); - if (!_consentService.CheckConsentInternal(Consents.RemoteConfig)) - { - return new CountlyResponse - { + if (!_consentService.CheckConsentInternal(Consents.RemoteConfig)) { + return new CountlyResponse { IsSuccess = false }; } @@ -107,20 +101,15 @@ public async Task Update() string data = _requestBuilder.BuildQueryString(requestParams); CountlyResponse response; - if (_configuration.EnablePost) - { + if (_configuration.EnablePost) { response = await Task.Run(() => _requestCountlyHelper.PostAsync(_countlyUtils.ServerInputUrl, data)); - } - else - { + } else { response = await Task.Run(() => _requestCountlyHelper.GetAsync(_countlyUtils.ServerInputUrl, data)); } - if (response.IsSuccess) - { + if (response.IsSuccess) { _configDao.RemoveAll(); - ConfigEntity configEntity = new ConfigEntity - { + ConfigEntity configEntity = new ConfigEntity { Id = _configDao.GenerateNewId(), Json = response.Data }; @@ -137,8 +126,7 @@ public async Task Update() #region override Methods internal override void ConsentChanged(List updatedConsents, bool newConsentValue, ConsentChangedAction action) { - if (updatedConsents.Contains(Consents.RemoteConfig) && !newConsentValue) - { + if (updatedConsents.Contains(Consents.RemoteConfig) && !newConsentValue) { Configs = null; _configDao.RemoveAll(); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/RemoteConfigCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/SessionCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/SessionCountlyService.cs similarity index 89% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/SessionCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/SessionCountlyService.cs index d6e3396f1..8192c206a 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/SessionCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/SessionCountlyService.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using System.Timers; +using Newtonsoft.Json; using Plugins.CountlySDK.Enums; using Plugins.CountlySDK.Helpers; using Plugins.CountlySDK.Models; @@ -30,8 +31,7 @@ internal SessionCountlyService(CountlyConfiguration configuration, CountlyLogHel RequestCountlyHelper requestCountlyHelper, LocationService locationService, ConsentCountlyService consentService, MonoBehaviour monoBehaviour) : base(configuration, logHelper, consentService) { Log.Debug("[SessionCountlyService] Initializing."); - if (configuration.IsAutomaticSessionTrackingDisabled) - { + if (configuration.IsAutomaticSessionTrackingDisabled) { Log.Debug("[SessionCountlyService] Disabling automatic session tracking"); } @@ -40,8 +40,7 @@ internal SessionCountlyService(CountlyConfiguration configuration, CountlyLogHel _requestCountlyHelper = requestCountlyHelper; _monoBehaviour = monoBehaviour; - if (_configuration.IsAutomaticSessionTrackingDisabled) - { + if (_configuration.IsAutomaticSessionTrackingDisabled) { Log.Verbose("[Countly][CountlyConfiguration] Automatic session tracking disabled!"); } } @@ -51,25 +50,19 @@ internal SessionCountlyService(CountlyConfiguration configuration, CountlyLogHel /// internal async Task StartSessionService() { - if (_configuration.IsAutomaticSessionTrackingDisabled || !_consentService.CheckConsentInternal(Consents.Sessions)) - { + if (_configuration.IsAutomaticSessionTrackingDisabled || !_consentService.CheckConsentInternal(Consents.Sessions)) { /* If location is disabled in init and no session consent is given. Send empty location as separate request.*/ - if (_locationService.IsLocationDisabled || !_consentService.CheckConsentInternal(Consents.Location)) - { + if (_locationService.IsLocationDisabled || !_consentService.CheckConsentInternal(Consents.Location)) { await _locationService.SendRequestWithEmptyLocation(); - } - else - { + } else { /* * If there is no session consent or automatic session tracking is disabled, * location values set in init should be sent as a separate location request. */ await _locationService.SendIndependantLocationRequest(); } - } - else - { + } else { //Start Session await BeginSessionAsync(); } @@ -85,7 +78,7 @@ private void InitSessionTimer() #if UNITY_WEBGL _monoBehaviour.StartCoroutine(SessionTimerCoroutine()); #else - _sessionTimer = new Timer { Interval = _configuration.SessionDuration * 1000 }; + _sessionTimer = new Timer { Interval = _configuration.GetUpdateSessionTimerDelay() * 1000 }; _sessionTimer.Elapsed += SessionTimerOnElapsedAsync; _sessionTimer.AutoReset = true; _sessionTimer.Start(); @@ -94,12 +87,11 @@ private void InitSessionTimer() private void SendRequestsAndExtendSession() { - //Countly.Instance.UserProfile.Save(); + Countly.Instance.UserProfile.Save(); _eventService.AddEventsToRequestQueue(); _ = _requestCountlyHelper.ProcessQueue(); - if (!_configuration.IsAutomaticSessionTrackingDisabled) - { + if (!_configuration.IsAutomaticSessionTrackingDisabled) { _ = ExtendSessionAsync(); } } @@ -108,12 +100,11 @@ private IEnumerator SessionTimerCoroutine() { Log.Debug("[SessionCountlyService] SessionTimerCoroutine, Start"); - if (isInternalTimerStopped) - { + if (isInternalTimerStopped) { yield break; } - yield return new WaitForSeconds(_configuration.SessionDuration); + yield return new WaitForSeconds(_configuration.GetUpdateSessionTimerDelay()); SendRequestsAndExtendSession(); Log.Debug("[SessionCountlyService] SessionTimerCoroutine, Coroutine completed."); } @@ -126,9 +117,9 @@ internal void StopSessionTimer() { isInternalTimerStopped = true; -#if UNITY_WEBGL + #if UNITY_WEBGL _monoBehaviour.StopCoroutine(SessionTimerCoroutine()); -#else + #else if (_sessionTimer != null) { // Unsubscribe from the Elapsed event _sessionTimer.Elapsed -= SessionTimerOnElapsedAsync; @@ -137,7 +128,7 @@ internal void StopSessionTimer() _sessionTimer.Stop(); _sessionTimer.Dispose(); } -#endif + #endif } /// @@ -147,11 +138,9 @@ internal void StopSessionTimer() /// Provides data for Timer.Elapsedevent. private async void SessionTimerOnElapsedAsync(object sender, ElapsedEventArgs elapsedEventArgs) { - lock (LockObj) - { + lock (LockObj) { - if (isInternalTimerStopped) - { + if (isInternalTimerStopped) { return; } @@ -169,13 +158,11 @@ internal async Task BeginSessionAsync() { Log.Debug("[SessionCountlyService] BeginSessionAsync"); - if (!_consentService.CheckConsentInternal(Consents.Sessions)) - { + if (!_consentService.CheckConsentInternal(Consents.Sessions)) { return; } - if (IsSessionInitiated) - { + if (IsSessionInitiated) { Log.Warning("[SessionCountlyService] BeginSessionAsync: The session has already started!"); return; } @@ -189,29 +176,22 @@ internal async Task BeginSessionAsync() /* If location is disabled or no location consent is given, the SDK adds an empty location entry to every "begin_session" request. */ - if (_locationService.IsLocationDisabled || !_consentService.CheckConsentInternal(Consents.Location)) - { + if (_locationService.IsLocationDisabled || !_consentService.CheckConsentInternal(Consents.Location)) { requestParams.Add("location", string.Empty); - } - else - { - if (!string.IsNullOrEmpty(_locationService.IPAddress)) - { + } else { + if (!string.IsNullOrEmpty(_locationService.IPAddress)) { requestParams.Add("ip_address", _locationService.IPAddress); } - if (!string.IsNullOrEmpty(_locationService.CountryCode)) - { + if (!string.IsNullOrEmpty(_locationService.CountryCode)) { requestParams.Add("country_code", _locationService.CountryCode); } - if (!string.IsNullOrEmpty(_locationService.City)) - { + if (!string.IsNullOrEmpty(_locationService.City)) { requestParams.Add("city", _locationService.City); } - if (!string.IsNullOrEmpty(_locationService.Location)) - { + if (!string.IsNullOrEmpty(_locationService.Location)) { requestParams.Add("location", _locationService.Location); } } @@ -230,20 +210,18 @@ internal async Task EndSessionAsync() { Log.Debug("[SessionCountlyService] EndSessionAsync"); - if (!_consentService.CheckConsentInternal(Consents.Sessions)) - { + if (!_consentService.CheckConsentInternal(Consents.Sessions)) { return; } - if (!IsSessionInitiated) - { + if (!IsSessionInitiated) { Log.Warning("[SessionCountlyService] EndSessionAsync: The session isn't started yet!"); return; } IsSessionInitiated = false; _eventService.AddEventsToRequestQueue(); - // Countly.Instance.UserProfile.Save(); + Countly.Instance.UserProfile.Save(); Dictionary requestParams = new Dictionary { {"end_session", 1}, @@ -261,13 +239,11 @@ internal async Task ExtendSessionAsync() { Log.Debug("[SessionCountlyService] ExtendSessionAsync"); - if (!_consentService.CheckConsentInternal(Consents.Sessions)) - { + if (!_consentService.CheckConsentInternal(Consents.Sessions)) { return; } - if (!IsSessionInitiated) - { + if (!IsSessionInitiated) { Log.Warning("[SessionCountlyService] ExtendSessionAsync: The session isn't started yet!"); return; } @@ -283,19 +259,17 @@ internal async Task ExtendSessionAsync() _requestCountlyHelper.AddToRequestQueue(requestParams); await _requestCountlyHelper.ProcessQueue(); - -#if UNITY_WEBGL + + #if UNITY_WEBGL _monoBehaviour.StartCoroutine(SessionTimerCoroutine()); -#endif + #endif } #region override Methods internal override async void ConsentChanged(List updatedConsents, bool newConsentValue, ConsentChangedAction action) { - if (updatedConsents.Contains(Consents.Sessions) && newConsentValue) - { - if (!_configuration.IsAutomaticSessionTrackingDisabled) - { + if (updatedConsents.Contains(Consents.Sessions) && newConsentValue) { + if (!_configuration.IsAutomaticSessionTrackingDisabled) { IsSessionInitiated = false; await BeginSessionAsync(); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/SessionCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/SessionCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/SessionCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/SessionCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/StarRatingCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/StarRatingCountlyService.cs similarity index 91% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/StarRatingCountlyService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/StarRatingCountlyService.cs index 40175e3d9..1a1b0e4a0 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/StarRatingCountlyService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/StarRatingCountlyService.cs @@ -30,36 +30,30 @@ internal StarRatingCountlyService(CountlyConfiguration configuration, CountlyLog /// public async Task ReportStarRatingAsync(string platform, string appVersion, int rating) { - lock (LockObj) - { + lock (LockObj) { Log.Info("[StarRatingCountlyService] ReportStarRatingAsync"); - if (!_consentService.CheckConsentInternal(Consents.StarRating)) - { + if (!_consentService.CheckConsentInternal(Consents.StarRating)) { return; } - if (string.IsNullOrEmpty(platform) || string.IsNullOrWhiteSpace(platform)) - { + if (string.IsNullOrEmpty(platform) || string.IsNullOrWhiteSpace(platform)) { Log.Warning("[StarRatingCountlyService] ReportStarRatingAsync : The platform name'" + platform + "'isn't valid."); return; } - if (string.IsNullOrEmpty(appVersion) || string.IsNullOrWhiteSpace(appVersion)) - { + if (string.IsNullOrEmpty(appVersion) || string.IsNullOrWhiteSpace(appVersion)) { Log.Warning("[StarRatingCountlyService] ReportStarRatingAsync : The appVersion '" + appVersion + "'isn't valid."); return; } - if (rating < 1 || rating > 5) - { + if (rating < 1 || rating > 5) { Log.Warning("[StarRatingCountlyService] ReportStarRatingAsync : The rating value'" + rating + "'isn't valid."); return; } StarRatingSegment segment = - new StarRatingSegment - { + new StarRatingSegment { Platform = platform, AppVersion = appVersion, Rating = rating, diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/StarRatingCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/StarRatingCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/StarRatingCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/StarRatingCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/UserProfile.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/UserProfile.cs new file mode 100644 index 000000000..a5600cb33 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/UserProfile.cs @@ -0,0 +1,609 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Plugins.CountlySDK; +using Plugins.CountlySDK.Enums; +using Plugins.CountlySDK.Helpers; +using Plugins.CountlySDK.Models; +using Plugins.CountlySDK.Services; + +public class UserProfile : AbstractBaseService, IUserProfileModule +{ + #region UserProfileData Parameters and Keys + internal string Name { get; set; } + internal string Username { get; set; } + internal string Email { get; set; } + internal string Organization { get; set; } + internal string Phone { get; set; } + internal string PictureUrl { get; set; } + internal string Gender { get; set; } + internal int BirthYear { get; set; } + static string NAME_KEY = "name"; + static string USERNAME_KEY = "username"; + static string EMAIL_KEY = "email"; + static string ORG_KEY = "organization"; + static string PHONE_KEY = "phone"; + static string PICTURE_KEY = "picture"; + static string GENDER_KEY = "gender"; + static string BYEAR_KEY = "byear"; + static string CUSTOM_KEY = "custom"; + readonly string[] NamedFields = { NAME_KEY, USERNAME_KEY, EMAIL_KEY, ORG_KEY, PHONE_KEY, PICTURE_KEY, GENDER_KEY, BYEAR_KEY }; + #endregion + + internal Dictionary CustomDataProperties = new Dictionary(); + internal Dictionary CustomMods = new Dictionary(); + private readonly Countly cly; + private readonly CountlyConfiguration config; + private readonly CountlyUtils utils; + internal readonly RequestCountlyHelper requestHelper; + internal readonly EventCountlyService eventService; + internal UserProfile(Countly countly, CountlyConfiguration configuration, CountlyLogHelper logHelper, RequestCountlyHelper requestCountlyHelper, CountlyUtils countlyUtils, ConsentCountlyService consentService, EventCountlyService events) : base(configuration, logHelper, consentService) + { + Log.Debug("[UserProfile] Initializing."); + + cly = countly; + config = configuration; + utils = countlyUtils; + requestHelper = requestCountlyHelper; + eventService = events; + } + + #region PublicAPI + /// + /// Increment custom property value by 1. + /// + /// string with property name to increment + public void Increment(string key) + { + Log.Info($"[UserProfile] Increment, with key: [{key}]"); + IncrementInternal(key, 1); + } + + /// + /// Increment custom property value by provided value. + /// + /// string with property name to increment + /// value by which to increment + public void IncrementBy(string key, double value) + { + Log.Info($"[UserProfile] IncrementBy, with key: [{key}] and value: [{value}]"); + IncrementInternal(key, value); + } + + /// + /// Save maximal value between existing and provided. + /// + /// string with property name to check for max + /// value to check for max + public void SaveMax(string key, double value) + { + Log.Info($"[UserProfile] Max, with key: [{key}] and value: [{value}]"); + MaxInternal(key, value); + } + + /// + /// Save minimal value between existing and provided. + /// + /// string with property name to check for min + /// value to check for min + public void SaveMin(string key, double value) + { + Log.Info($"[UserProfile] Min, with key: [{key}] and value: [{value}]"); + MinInternal(key, value); + } + + /// + /// Multiply custom property value by provided value. + /// + /// string with property name to multiply + /// value by which to multiply + public void Multiply(string key, double value) + { + Log.Info($"[UserProfile] Multiply, with key: [{key}] and value: [{value}]"); + MultiplyInternal(key, value); + } + + /// + /// Removes existing property from array. + /// You can only use it on array properties + /// + /// string with property name for array property + /// string with value to remove from array + public void Pull(string key, string value) + { + Log.Info($"[UserProfile] Pull, with key: [{key}] and value: [{value}]"); + PullInternal(key, value); + } + + /// + /// Create array property, if property does not exist and add value to array. + /// You can only use it on array properties or properties that do not exist yet + /// + /// string with property name for array property + /// string with value to add to array + public void Push(string key, string value) + { + Log.Info($"[UserProfile] Push, with key: [{key}] and value: [{value}]"); + PushInternal(key, value); + } + + /// + /// Create array property, if property does not exist and add value to array, only if value is not yet in the array. + /// You can only use it on array properties or properties that do not exist yet + /// + /// string with property name for array property + /// string with value to add to array + public void PushUnique(string key, string value) + { + Log.Info($"[UserProfile] PushUnique, with key: [{key}] and value: [{value}]"); + PushUniqueInternal(key, value); + } + + /// + /// Send provided values to server. + /// + public void Save() + { + Log.Info("[UserProfile] Save"); + SaveInternal(); + } + + /// + /// Set value only if property does not exist yet. + /// + /// string with property name to set + /// value string value to set + public void SetOnce(string key, string value) + { + Log.Info($"[UserProfile] SetOnce, with key: [{key}] and value: [{value}]"); + SetOnceInternal(key, value); + } + + /// + /// Provide a Dictionary of user properties to set. + /// Those can be either custom user properties or predefined user properties. + /// + /// Dictionary with data to set + public void SetProperties(Dictionary data) + { + LogSegmentation(data, "[UserProfile] SetProperties,"); + SetPropertiesInternal(data); + } + + /// + /// Set a single user property. It can be either a custom one or one of the predefined ones. + /// + /// string with key for the user property + /// value for the user property to be set. The value should be the allowed data type. + public void SetProperty(string key, object value) + { + Log.Info($"[UserProfile] SetProperty, with key: [{key}] and value: [{value}]"); + SetPropertyInternal(key, value); + } + #endregion + #region Internal Calls + private void IncrementInternal(string key, double value) + { + if (!ValidateConsentAndKey(key, "IncrementInternal")) { + return; + } + + Log.Info($"[UserProfile] IncrementInternal, key: [{key}] and value: [{value}]"); + ModifyCustomData(key, value, "$inc"); + } + + private void MaxInternal(string key, double value) + { + if (!ValidateConsentAndKey(key, "MaxInternal")) { + return; + } + + Log.Info($"[UserProfile] MaxInternal, key: [{key}] and value: [{value}]"); + ModifyCustomData(key, value, "$max"); + } + + private void MinInternal(string key, double value) + { + if (!ValidateConsentAndKey(key, "MinInternal")) { + return; + } + + Log.Info($"[UserProfile] MinInternal, key: [{key}] and value: [{value}]"); + ModifyCustomData(key, value, "$min"); + } + + private void MultiplyInternal(string key, double value) + { + if (!ValidateConsentAndKey(key, "MultiplyInternal")) { + return; + } + + Log.Info($"[UserProfile] MultiplyInternal, key: [{key}] and value: [{value}]"); + ModifyCustomData(key, value, "$mul"); + } + + private void PullInternal(string key, string value) + { + if (!ValidateConsentAndKey(key, "PullInternal")) { + return; + } + + Log.Info($"[UserProfile] PullInternal, key: [{key}] and value: [{value}]"); + ModifyCustomData(key, value, "$pull"); + } + + private void PushInternal(string key, string value) + { + if (!ValidateConsentAndKey(key, "PushInternal")) { + return; + } + + Log.Info($"[UserProfile] PushInternal, key: [{key}] and value: [{value}]"); + ModifyCustomData(key, value, "$push"); + } + + private void PushUniqueInternal(string key, string value) + { + if (!ValidateConsentAndKey(key, "PushUniqueInternal")) { + return; + } + + Log.Info($"[UserProfile] PushUniqueInternal, key: [{key}] and value: [{value}]"); + ModifyCustomData(key, value, "$addToSet"); + } + + private void SaveInternal() + { + if (!cly.IsSDKInitialized) { + Log.Warning("[UserProfile] SaveInternal, Countly.Instance.Init() must be called before SaveInternal"); + return; + } + + if (!_consentService.CheckConsentInternal(Consents.Users)) { + Log.Debug("[UserProfile] SaveInternal, Consent is not given, ignoring the request."); + return; + } + + Dictionary cachedUserData = GetDataForRequest(); + + if (cachedUserData.Count <= 0) { + Log.Debug("[UserProfile] SaveInternal, No user data to save"); + return; + } + + // Serialize the dictionary to a JSON string + string jsonData; + try { + jsonData = JsonConvert.SerializeObject(cachedUserData); + } catch (JsonException ex) { + Log.Error($"[UserProfile] SaveInternal, failed to serialize cached user data: {ex.Message}"); + return; + } + + // Create a new dictionary to hold the modified data + var modifiedData = new Dictionary { + { "user_details", jsonData } + }; + + cly.Events.AddEventsToRequestQueue(); + requestHelper.AddToRequestQueue(modifiedData); + + _ = requestHelper.ProcessQueue(); + ClearInternal(); + } + + private void SetDataInternal(Dictionary userData) + { + if (!cly.IsSDKInitialized) { + Log.Warning("[UserProfile] SetDataInternal, Countly.Instance.Init() must be called before SetDataInternal"); + return; + } + + if (!_consentService.CheckConsentInternal(Consents.Users)) { + Log.Debug("[UserProfile] SetDataInternal, Consent is not given, ignoring the request."); + return; + } + + if (userData == null || userData.Count <= 0) { + Log.Debug("[UserProfile] SetDataInternal, Provided userData is empty, ignoring the request."); + return; + } + + LogSegmentation(userData, "[UserProfile] SetDataInternal,"); + + if (userData.TryGetValue(NAME_KEY, out object nameValue) && nameValue is string name) { + Name = TrimValue(NAME_KEY, name.Trim()); + } + + if (userData.TryGetValue(USERNAME_KEY, out object usernameValue) && usernameValue is string username) { + Username = TrimValue(USERNAME_KEY, username.Trim()); + } + + if (userData.TryGetValue(EMAIL_KEY, out object emailValue) && emailValue is string email) { + Email = TrimValue(EMAIL_KEY, email.Trim()); + } + + if (userData.TryGetValue(ORG_KEY, out object orgValue) && orgValue is string organization) { + Organization = TrimValue(ORG_KEY, organization.Trim()); + } + + if (userData.TryGetValue(PHONE_KEY, out object phoneValue) && phoneValue is string phone) { + Phone = TrimValue(PHONE_KEY, phone.Trim()); + } + + if (userData.TryGetValue(PICTURE_KEY, out object pictureValue) && pictureValue is string pictureUrl) { + if (utils.IsPictureValid(pictureUrl)) { + if (pictureUrl.Length > 4096) { + Log.Warning($"[UserDetailsCountlyService] SetDataInternal, Provided PictureURL length is more than 4096. Will be cropped."); + PictureUrl = pictureUrl.Substring(0, 4096); + } else { + PictureUrl = pictureUrl.Trim(); + } + } else { + Log.Warning($"[UserDetailsCountlyService] SetDataInternal, Picture format for URL '{pictureUrl}' is not as expected. Expected formats are .png, .gif, or .jpeg"); + } + } + + if (userData.TryGetValue(GENDER_KEY, out object genderValue) && genderValue is string gender) { + Gender = TrimValue(GENDER_KEY, gender.Trim()); + } + + if (userData.TryGetValue(BYEAR_KEY, out object birthYearValue) && birthYearValue is int birthYear) { + BirthYear = birthYear; + } + } + + private void SetPropertiesInternal(Dictionary data) + { + if (!cly.IsSDKInitialized) { + Log.Warning("[UserProfile] SetPropertiesInternal, Countly.Instance.Init() must be called before SetPropertiesInternal"); + return; + } + + if (!_consentService.CheckConsentInternal(Consents.Users)) { + Log.Debug("[UserProfile] SetPropertiesInternal, Consent is not given, ignoring the request."); + return; + } + + if (data == null || data.Count <= 0) { + Log.Debug("[UserProfile] SetPropertiesInternal, Provided data is empty, or null ignoring the request."); + return; + } + + LogSegmentation(data, "[UserProfile] SetPropertiesInternal,"); + + Dictionary namedFields = new Dictionary(); + Dictionary customFields = new Dictionary(); + + // separate named user fields and custom fields + foreach (KeyValuePair kvp in data) { + if (NamedFields.Contains(value: kvp.Key) && kvp.Value != null) { + namedFields.Add(kvp.Key, kvp.Value); + } else if (!NamedFields.Contains(kvp.Key) && kvp.Value != null) { + customFields.Add(kvp.Key, kvp.Value); + } + } + + // set user data + if (namedFields.Count > 0) { + FixSegmentKeysAndValues(namedFields); + SetDataInternal(namedFields); + } + + // set custom data + if (customFields.Count > 0) { + FixSegmentKeysAndValues(customFields); + foreach (KeyValuePair item in customFields) { + CustomDataProperties[item.Key] = item.Value; + } + } + } + + private void SetPropertyInternal(string key, object value) + { + if (!ValidateConsentAndKey(key, "SetPropertyInternal")) { + return; + } + + if (utils.IsNullEmptyOrWhitespace(key)) { + Log.Warning($"[UserProfile] SetPropertyInternal, Provided key is null, empty or whitespace. Ignoring."); + return; + } + + Dictionary data = new Dictionary { { key, value } }; + Log.Info($"[UserProfile] SetPropertyInternal, key: [{key}] and value: [{value}]"); + SetPropertiesInternal(data); + } + + private void SetOnceInternal(string key, string value) + { + if (!ValidateConsentAndKey(key, "SetOnceInternal")) { + return; + } + + Log.Info($"[UserProfile] SetOnceInternal, key: [{key}] and value: [{value}]"); + ModifyCustomData(key, value, "$setOnce"); + } + #endregion + #region Helper Methods + void ModifyCustomData(string key, object value, string mod) + { + try { + if (utils.IsNullEmptyOrWhitespace(key)) { + Log.Warning($"[UserProfile] ModifyCustomData, Provided key is null, empty or whitespace. Will be ignored."); + return; + } + + if (value == null || !(value is double || value is int || value is string || value is bool)) { + Log.Warning($"[UserProfile] ModifyCustomData, Provided 'value' is {(value == null ? "null" : "an unsupported type")}"); + return; + } + + string trimmedKey = key.Trim(); + if (key != trimmedKey) { + Log.Verbose($"[UserProfile] ModifyCustomData, Provided key: [{key}], for value: [{value}] has been trimmed."); + } + + string truncatedKey = TrimKey(trimmedKey); + object truncatedValue; + + if (value is string stringValue) { + string trimmed = stringValue.Trim(); + if (stringValue != trimmed) { + Log.Verbose($"[UserProfile] ModifyCustomData, Provided value: [{value}], for key: [{key}] has been trimmed. Current value: [{trimmed}]"); + } + truncatedValue = TrimValue(truncatedKey, trimmed); + } else { + truncatedValue = value; + } + + CustomMods ??= new Dictionary(); + + JObject ob; + if (mod != "$pull" && mod != "$push" && mod != "$addToSet") { + ob = new JObject { [mod] = JToken.FromObject(truncatedValue) }; + } else { + if (CustomMods.ContainsKey(truncatedKey)) { + ob = CustomMods[truncatedKey]; + } else { + ob = new JObject(); + } + + if (ob[mod] is JArray existingArray) { + existingArray.Add(JToken.FromObject(truncatedValue)); + } else { + ob[mod] = new JArray(truncatedValue); + } + } + CustomMods[truncatedKey] = ob; + } catch (Exception e) { + Log.Error($"[UserProfile] ModifyCustomData, An exception occured during modifying the custom data. Exception: {e}"); + } + } + + private void ClearInternal() + { + Log.Debug("[UserProfile] ClearInternal, Start"); + + Name = null; + Username = null; + Email = null; + Organization = null; + Phone = null; + PictureUrl = null; + Gender = null; + BirthYear = 0; + CustomDataProperties = new Dictionary(); + CustomMods = new Dictionary(); + } + + private void AddStringPropertyToJSON(JObject json, string key, object value) + { + if (value != null && value is string val) { + json.Add(key, val); + } + if (value != null && value is int v) { + if (v > 0) { + json.Add(BYEAR_KEY, v); + } + } + } + + private string ConvertToJSON() + { + JObject json = new JObject(); + + try { + AddStringPropertyToJSON(json, NAME_KEY, Name); + AddStringPropertyToJSON(json, USERNAME_KEY, Username); + AddStringPropertyToJSON(json, EMAIL_KEY, Email); + AddStringPropertyToJSON(json, ORG_KEY, Organization); + AddStringPropertyToJSON(json, PHONE_KEY, Phone); + AddStringPropertyToJSON(json, GENDER_KEY, Gender); + AddStringPropertyToJSON(json, PICTURE_KEY, PictureUrl); + AddStringPropertyToJSON(json, BYEAR_KEY, BirthYear); + + JObject ob = new JObject(); + + if (CustomDataProperties.Count > 0) { + utils.TruncateSegmentationValues(CustomDataProperties, config.GetMaxSegmentationValues(), "[UserProfile] ConvertToJSON", Log); + ob = JObject.FromObject(CustomDataProperties); + } + + if (CustomMods.Count > 0) { + foreach (KeyValuePair entry in CustomMods) { + ob[entry.Key] = entry.Value; + } + } + + if (ob != null && ob.Count > 0) { + json.Add(CUSTOM_KEY, ob); + } + + } catch (JsonException e) { + Log.Warning($"[UserProfile] ConvertToJSON, Got exception converting an UserData to JSON. Exception:{e}"); + } + + if (json.Count > 0) { + return json.ToString(); + } else { + return null; + } + } + + private Dictionary GetDataForRequest() + { + string json = ConvertToJSON(); + if (json != null) { + try { + Dictionary data = JsonConvert.DeserializeObject>(json); + return data; + } catch (JsonException ex) { + Log.Error($"[UserProfile] GetDataForRequest, Failed to deserialize cached user data: {ex.Message}"); + return new Dictionary(); + } + } + return new Dictionary(); + } + + private bool ValidateConsentAndKey(string key, string caller = null) + { + if (!cly.IsSDKInitialized) { + Log.Warning($"[UserProfile] {caller}, Countly.Instance.Init() must be called before first."); + return false; + } + + if (!_consentService.CheckConsentInternal(Consents.Users)) { + Log.Debug($"[UserProfile] {caller}, Consent is not given, ignoring the request."); + return false; + } + + if (string.IsNullOrEmpty(key)) { + Log.Warning($"[UserProfile] {caller}, Provided key isn't valid."); + return false; + } + + return true; + } + #endregion + #region Override Methods + internal override void OnInitializationCompleted() + { + if (config.GetUserProperties().Count() > 0) { + LogSegmentation(config.GetUserProperties(), "[UserProfile] OnInitializationCompleted,"); + SetPropertiesInternal(config.GetUserProperties()); + SaveInternal(); + } + } + + internal override void DeviceIdChanged(string deviceId, bool merged) + { + Log.Info($"[UserProfile] DeviceIdChanged, DeviceId change has occured. New DeviceId: [{deviceId}], Merged: [{merged}]. Calling Save"); + SaveInternal(); + } + #endregion +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/UserProfile.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/UserProfile.cs.meta new file mode 100644 index 000000000..ac0896f44 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/UserProfile.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 87188717b779c4c55a63a5514631403a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ViewCountlyService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ViewCountlyService.cs new file mode 100644 index 000000000..aaf8da8f2 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ViewCountlyService.cs @@ -0,0 +1,820 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Plugins.CountlySDK.Enums; +using Plugins.CountlySDK.Helpers; +using Plugins.CountlySDK.Models; +using UnityEngine; + +namespace Plugins.CountlySDK.Services +{ + public class ViewCountlyService : AbstractBaseService, IViewModule, IViewIDProvider + { + private class ViewData + { + public string ViewID; + public long ViewStartTimeSeconds; // If this is 0, the view is not started yet or was paused + public string ViewName; + public bool IsAutoStoppedView; // Views started with "startAutoStoppedView" would have this as "true". + public bool IsAutoPaused; // This marks that this view automatically paused when going to the background + public Dictionary ViewSegmentation; + } + + private string currentViewID; + private string previousViewID; + private readonly string viewEventKey = "[CLY]_view"; + + readonly Dictionary viewDataMap = new Dictionary(); + readonly Dictionary automaticViewSegmentation = new Dictionary(); + + internal bool _isFirstView = true; + internal readonly EventCountlyService _eventService; + internal readonly Countly _cly; + internal readonly CountlyUtils _utils; + + internal ISafeIDGenerator safeViewIDGenerator; + + readonly string[] reservedSegmentationKeysViews = { "name", "visit", "start", "segment" }; + private readonly Dictionary _viewToLastViewStartTime = new Dictionary(); + + internal ViewCountlyService(Countly countly, CountlyUtils utils, CountlyConfiguration configuration, CountlyLogHelper logHelper, EventCountlyService eventService, ConsentCountlyService consentService) : base(configuration, logHelper, consentService) + { + Log.Debug("[ViewCountlyService] Initializing."); + _cly = countly; + _utils = utils; + eventService.viewIDProvider = this; + _eventService = eventService; + safeViewIDGenerator = configuration.SafeViewIDGenerator; + } + + #region PublicAPI + + /// + /// Returns the current ViewID + /// + public string GetCurrentViewId() + { + return currentViewID == null ? "" : currentViewID; + } + + /// + /// Returns the previous ViewID + /// + public string GetPreviousViewId() + { + return previousViewID == null ? "" : previousViewID; + } + + /// + /// Manually starts a view with the given name. + /// It can be used to open multiple views in parallel. + /// + /// Name of the view + /// ViewId + public string StartView(string viewName) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] StartView, vn[" + viewName + "]"); + return StartViewInternal(viewName, null, false); + } + } + + /// + /// Manually starts a view with the given name. + /// It can be used to open multiple views in parallel. + /// + /// Name of the view + /// Segmentation that will be added to the view, set 'null' if none should be added + /// ViewId + public string StartView(string viewName, Dictionary viewSegmentation) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] StartView, vn[" + viewName + "] sg[" + (viewSegmentation == null ? "null" : JsonConvert.SerializeObject(viewSegmentation, new JsonSerializerSettings { Error = (_, args) => { args.ErrorContext.Handled = true; } })) + "]"); + return StartViewInternal(viewName, viewSegmentation, false); + } + } + + /// + /// Manually starts a view with the given name. Starting any other view or calling this again, + /// closes the one that's opened automatically.
+ /// This ensures a 'one view at a time' flow. + ///
+ /// Name of the view + /// ViewId + public string StartAutoStoppedView(string viewName) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] StartAutoStoppedView, vn[" + viewName + "]"); + return StartAutoStoppedView(viewName, null); + } + } + + /// + /// Manually starts a view with the given name. Starting any other view or calling this again, + /// closes the one that's opened automatically.
+ /// This ensures a 'one view at a time' flow. + ///
+ /// Name of the view + /// Segmentation that will be added to the view, set 'null' if none should be added + /// ViewId + public string StartAutoStoppedView(string viewName, Dictionary viewSegmentation) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] StartAutoStoppedView, vn[" + viewName + "] sg[" + (viewSegmentation == null ? "null" : JsonConvert.SerializeObject(viewSegmentation, new JsonSerializerSettings { Error = (_, args) => { args.ErrorContext.Handled = true; } })) + "]"); + return StartViewInternal(viewName, viewSegmentation, true); + } + } + + /// + /// Stops a view with the given name if it is open + /// If multiple views with same name are open, last opened view will be closed. + /// + /// Name of the view + public void StopViewWithName(string viewName) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] StopViewWithName, vn[" + viewName + "]"); + StopViewWithNameInternal(viewName, null); + } + } + + /// + /// Stops a view with the given name if it is open + /// If multiple views with same name are open, last opened view will be closed. + /// + /// Name of the view + /// Segmentation that will be added to the view, set 'null' if none should be added + public void StopViewWithName(string viewName, Dictionary viewSegmentation) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] StopViewWithName, vn[" + viewName + "] sg[" + (viewSegmentation == null ? "null" : JsonConvert.SerializeObject(viewSegmentation, new JsonSerializerSettings { Error = (_, args) => { args.ErrorContext.Handled = true; } })) + "]"); + StopViewWithNameInternal(viewName, viewSegmentation); + } + } + + /// + /// Stops a view with the given ID if it is open + /// + /// ID of the view + public void StopViewWithID(string viewID) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] StopViewWithID, vi[" + viewID + "]"); + StopViewWithIDInternal(viewID, null); + } + } + + /// + /// Stops a view with the given ID if it is open + /// + /// ID of the view + /// Segmentation that will be added to the view, set 'null' if none should be added + public void StopViewWithID(string viewID, Dictionary viewSegmentation) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] StopViewWithID, vi[" + viewID + "] sg[" + (viewSegmentation == null ? "null" : JsonConvert.SerializeObject(viewSegmentation, new JsonSerializerSettings { Error = (_, args) => { args.ErrorContext.Handled = true; } })) + "]"); + StopViewWithIDInternal(viewID, viewSegmentation); + } + } + + /// + /// Pauses a view with the given ID + /// + /// ID of the view + public void PauseViewWithID(string viewID) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] PauseViewWithID, vi[" + viewID + "]"); + PauseViewWithIDInternal(viewID, false); + } + } + + /// + /// Resumes a view with the given ID + /// + /// ID of the view + public void ResumeViewWithID(string viewID) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] ResumeViewWithID, vi[" + viewID + "]"); + ResumeViewWithIDInternal(viewID); + } + } + + /// + /// Stops all views and records a segmentation if set + /// + /// Segmentation that will be added, set 'null' if none should be added + public void StopAllViews(Dictionary viewSegmentation) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] StopAllViews, sg[" + (viewSegmentation == null ? "null" : JsonConvert.SerializeObject(viewSegmentation, new JsonSerializerSettings { Error = (_, args) => { args.ErrorContext.Handled = true; } })) + "]"); + StopAllViewsInternal(viewSegmentation); + } + } + + /// + /// Set a segmentation to be recorded with all views + /// + /// Global View Segmentation + public void SetGlobalViewSegmentation(Dictionary viewSegmentation) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] SetGlobalViewSegmentation, sg[" + (viewSegmentation == null ? "null" : JsonConvert.SerializeObject(viewSegmentation, new JsonSerializerSettings { Error = (_, args) => { args.ErrorContext.Handled = true; } })) + "]"); + SetGlobalViewSegmentationInternal(viewSegmentation); + } + } + + /// + /// Updates the segmentation of a view with view id. + /// + /// ID of the view + /// Segmentation that will be added to the view + public void AddSegmentationToViewWithID(string viewID, Dictionary viewSegmentation) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] AddSegmentationToViewWithID, for view ID: [" + viewID + "]"); + AddSegmentationToViewWithIDInternal(viewID, viewSegmentation); + } + } + + /// + /// Updates the segmentation of a view with view name. + /// If multiple views with same name are open, last opened view will be updated. + /// + /// Name of the view + /// Segmentation that will be added to the view + public void AddSegmentationToViewWithName(string viewName, Dictionary viewSegmentation) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] AddSegmentationToViewWithName, for Name: [" + viewName + "]"); + AddSegmentationToViewWithNameInternal(viewName, viewSegmentation); + } + } + + /// + /// Updates the global segmentation + /// + /// Segmentation that will be added to the view + public void UpdateGlobalViewSegmentation(Dictionary viewSegmentation) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] UpdateGlobalViewSegmentation, sg[" + (viewSegmentation == null ? "null" : JsonConvert.SerializeObject(viewSegmentation, new JsonSerializerSettings { Error = (_, args) => { args.ErrorContext.Handled = true; } })) + "]"); + UpdateGlobalViewSegmentationInternal(viewSegmentation); + } + } + #endregion + #region InternalMethods + /// + /// Starts the view with given viewName, segmentation + /// + /// name of the view + /// segmentation that will be added to the view, set 'null' if none should be added + /// + /// + private string StartViewInternal(string viewName, Dictionary customViewSegmentation, bool viewShouldBeAutomaticallyStopped) + { + if (!_cly.IsSDKInitialized) { + Log.Warning("[ViewCountlyService] StartViewInternal, Countly.Instance.Init() must be called before StartViewInternal"); + return null; + } + + if(!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] StartView, consent is not given, ignoring the request."); + return null; + } + + if (_utils.IsNullEmptyOrWhitespace(viewName)) { + Log.Warning("[ViewCountlyService] StartViewInternal, trying to record view with null or empty view name, ignoring request"); + return null; + } + + if (viewName.Length > _configuration.GetMaxKeyLength()) { + Log.Verbose("[ViewCountlyService] StartViewInternal, max allowed key length is " + _configuration.GetMaxKeyLength()); + viewName = viewName.Substring(0, _configuration.GetMaxKeyLength()); + } + + _utils.TruncateSegmentationValues(customViewSegmentation, _configuration.GetMaxSegmentationValues(), "[ViewCountlyService] StartViewInternal, ", Log); + _utils.RemoveReservedKeysFromSegmentation(customViewSegmentation, reservedSegmentationKeysViews, "[ViewCountlyService] StartViewInternal, ", Log); + + Log.Debug("[ViewCountlyService] StartViewInternal, recording view with name: [" + viewName + "], previous view ID:[" + currentViewID + "], custom view segmentation:[" + customViewSegmentation?.ToString() + "], first:[" + _isFirstView + "], autoStop:[" + viewShouldBeAutomaticallyStopped + "]"); + + AutoCloseRequiredViews(false, null); + + ViewData currentViewData = new ViewData(); + currentViewData.ViewID = safeViewIDGenerator.GenerateValue(); + currentViewData.ViewName = viewName; + currentViewData.ViewStartTimeSeconds = _utils.CurrentTimestampSeconds(); + currentViewData.IsAutoStoppedView = viewShouldBeAutomaticallyStopped; + + viewDataMap.Add(currentViewData.ViewID, currentViewData); + previousViewID = currentViewID; + currentViewID = currentViewData.ViewID; + + Dictionary accumulatedEventSegm = new Dictionary(automaticViewSegmentation); + + if (customViewSegmentation != null) { + _utils.CopyDictionaryToDestination(accumulatedEventSegm, customViewSegmentation, Log); + } + + Dictionary viewSegmentation = CreateViewEventSegmentation(currentViewData, _isFirstView, true, accumulatedEventSegm); + + if (_isFirstView) { + Log.Debug("[ViewCountlyService] StartViewInternal, recording view as the first one in the session. [" + viewName + "]"); + _isFirstView = false; + } + _ = _eventService.RecordEventInternal(viewEventKey, viewSegmentation, 1, 0, null, currentViewData.ViewID); + + return currentViewData.ViewID; + } + + /// + /// Stops a view with the given name if it was open. + /// + /// name of the view + /// + private void StopViewWithNameInternal(string viewName, Dictionary customViewSegmentation) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] StopViewWithNameInternal, consent is not given, ignoring the request."); + return; + } + + if (_utils.IsNullEmptyOrWhitespace(viewName)) { + Log.Warning("[ViewCountlyService] StopViewWithNameInternal, trying to record view with null or empty view name, ignoring request"); + return; + } + + if (viewName.Length > _configuration.GetMaxKeyLength()) { + Log.Verbose("[ViewCountlyService] StopViewWithNameInternal, max allowed key length is " + _configuration.GetMaxKeyLength()); + viewName = viewName.Substring(0, _configuration.GetMaxKeyLength()); + } + + customViewSegmentation = (Dictionary)RemoveSegmentInvalidDataTypes(customViewSegmentation); + + string viewID = null; + + foreach (KeyValuePair entry in viewDataMap) { + string key = entry.Key; + ViewData vd = entry.Value; + + if (vd != null && viewName.Equals(vd.ViewName)) { + viewID = key; + } + } + + if (viewID == null) { + Log.Warning("[ViewCountlyService] StopViewWithNameInternal, no view entry found with the provided name :[" + viewName + "]"); + return; + } + + StopViewWithIDInternal(viewID, customViewSegmentation); + } + + /// + /// Closes given views or all views. + /// + /// + /// + private void AutoCloseRequiredViews(bool closeAllViews, Dictionary customViewSegmentation) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] AutoCloseRequiredViews, consent is not given, ignoring the request."); + return; + } + + Log.Debug("[ViewCountlyService] AutoCloseRequiredViews, closing required views."); + List viewsToRemove = new List(1); + + foreach (var entry in viewDataMap) { + ViewData vd = entry.Value; + if (closeAllViews || vd.IsAutoStoppedView) { + viewsToRemove.Add(vd.ViewID); + } + } + + if (viewsToRemove.Count > 0) { + Log.Debug("[ViewCountlyService] AutoCloseRequiredViews, about to close [" + viewsToRemove.Count + "] views"); + } + + _utils.RemoveReservedKeysFromSegmentation(customViewSegmentation, reservedSegmentationKeysViews, "[ViewCountlyService] AutoCloseRequiredViews, ", Log); + + for (int i = 0; i < viewsToRemove.Count; i++) { + StopViewWithIDInternal(viewsToRemove[i], customViewSegmentation); + } + } + + /// + /// Stops a view with the given ID if it was open. + /// + /// ID of the view + /// view segmentation + private void StopViewWithIDInternal(string viewID, Dictionary customViewSegmentation) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] StopViewWithIDInternal, consent is not given, ignoring the request."); + return; + } + + if (_utils.IsNullEmptyOrWhitespace(viewID)) { + Log.Warning("[ViewCountlyService] StopViewWithIDInternal, trying to record view with null or empty view ID, ignoring request"); + return; + } + + if (!viewDataMap.ContainsKey(viewID)) { + Log.Warning("[ViewCountlyService] StopViewWithIDInternal, there is no view with the provided view id to close"); + return; + } + + ViewData vd = viewDataMap[viewID]; + if (vd == null) { + Log.Warning("[ViewCountlyService] StopViewWithIDInternal, view id:[" + viewID + "] has a 'null' value. This should not be happening"); + return; + } + + customViewSegmentation = (Dictionary)RemoveSegmentInvalidDataTypes(customViewSegmentation); + + Log.Debug("[ViewCountlyService] View [" + vd.ViewName + "], id:[" + vd.ViewID + "] is getting closed, reporting duration: [" + (_utils.CurrentTimestampSeconds() - vd.ViewStartTimeSeconds) + "] s, current timestamp: [" + _utils.CurrentTimestampSeconds() + "]"); + _utils.TruncateSegmentationValues(customViewSegmentation, _configuration.GetMaxSegmentationValues(), "[ViewCountlyService] StopViewWithIDInternal", Log); + RecordViewEndEvent(vd, customViewSegmentation, "StopViewWithIDInternal"); + viewDataMap.Remove(vd.ViewID); + } + + /// + /// Pauses a view with the given ID. + /// + /// + /// + private void PauseViewWithIDInternal(string viewID, bool pausedAutomatically) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] PauseViewWithIDInternal, consent is not given, ignoring the request."); + return; + } + + if (_utils.IsNullEmptyOrWhitespace(viewID)) { + Log.Warning("[ViewCountlyService] PauseViewWithIDInternal, trying to record view with null or empty view ID, ignoring request"); + return; + } + + if (!viewDataMap.ContainsKey(viewID)) { + Log.Warning("[ViewCountlyService] PauseViewWithIDInternal, there is no view with the provided view id to close"); + return; + } + + ViewData vd = viewDataMap[viewID]; + if (vd == null) { + Log.Warning("[ViewCountlyService] PauseViewWithIDInternal, view id:[" + viewID + "] has a 'null' value. This should not be happening, auto paused:[" + pausedAutomatically + "]"); + return; + } + + Log.Debug("[ViewCountlyService] PauseViewWithIDInternal, pausing view for ID:[" + viewID + "], name:[" + vd.ViewName + "]"); + + if (vd.ViewStartTimeSeconds == 0) { + Log.Warning("[ViewCountlyService] PauseViewWithIDInternal, pausing a view that is already paused. ID:[" + viewID + "], name:[" + vd.ViewName + "]"); + return; + } + + vd.IsAutoPaused = pausedAutomatically; + RecordViewEndEvent(vd, null, "PauseViewWithIDInternal"); + vd.ViewStartTimeSeconds = 0; + } + + /// + /// Records event with given ViewData and filtered segmentation. + /// + /// + /// + /// + private void RecordViewEndEvent(ViewData vd, Dictionary filteredCustomViewSegmentation, string viewRecordingSource) + { + long lastElapsedDurationSeconds = 0; + + if (vd.ViewStartTimeSeconds < 0) { + Log.Warning("[ViewCountlyService] " + viewRecordingSource + ", view start time value is not normal: [" + vd.ViewStartTimeSeconds + "], ignoring that duration"); + } else if (vd.ViewStartTimeSeconds == 0) { + Log.Info("[ViewCountlyService] " + viewRecordingSource + ", view is either paused or didn't run, ignoring start timestamp"); + } else { + lastElapsedDurationSeconds = _utils.CurrentTimestampSeconds() - vd.ViewStartTimeSeconds; + } + + if (vd.ViewName == null) { + Log.Warning("[ViewCountlyService] StopViewWithIDInternal, view has no internal name, ignoring it"); + return; + } + + Dictionary accumulatedEventSegm = new Dictionary(automaticViewSegmentation); + if (filteredCustomViewSegmentation != null) { + _utils.CopyDictionaryToDestination(accumulatedEventSegm, filteredCustomViewSegmentation, Log); + } + + if (vd.ViewSegmentation != null) { + _utils.CopyDictionaryToDestination(accumulatedEventSegm, vd.ViewSegmentation, Log); + } + + long viewDurationSeconds = lastElapsedDurationSeconds; + Dictionary segments = CreateViewEventSegmentation(vd, false, false, accumulatedEventSegm); + _ = _eventService.RecordEventInternal(CountlyEventModel.ViewEvent, segments, duration: viewDurationSeconds, eventIDOverride: vd.ViewID); + } + + /// + /// Creates view event segmentation + /// + /// + /// + /// + /// + /// + private Dictionary CreateViewEventSegmentation(ViewData vd, bool firstView, bool visit, Dictionary customViewSegmentation) + { + Dictionary viewSegmentation = new Dictionary(); + if (customViewSegmentation != null) { + _utils.CopyDictionaryToDestination(viewSegmentation, customViewSegmentation, Log); + } + + viewSegmentation.Add("name", vd.ViewName); + if (visit) { + viewSegmentation.Add("visit", 1); + } + if (firstView) { + viewSegmentation.Add("start", 1); + } + viewSegmentation.Add("segment", _configuration.metricHelper.OS); + + return viewSegmentation; + } + + /// + /// Resumes a paused view with the given ID. + /// + /// + private void ResumeViewWithIDInternal(string viewID) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] ResumeViewWithIDInternal, consent is not given, ignoring the request."); + return; + } + + if (_utils.IsNullEmptyOrWhitespace(viewID)) { + Log.Warning("[ViewCountlyService] ResumeViewWithIDInternal, trying to record view with null or empty view ID, ignoring request"); + return; + } + + if (!viewDataMap.ContainsKey(viewID)) { + Log.Warning("[ViewCountlyService] ResumeViewWithIDInternal, there is no view with the provided view id to close"); + return; + } + + ViewData vd = viewDataMap[viewID]; + if (vd == null) { + Log.Warning("[ViewCountlyService] ResumeViewWithIDInternal, view id:[" + viewID + "] has a 'null' value. This should not be happening"); + return; + } + + Log.Debug("[ViewCountlyService] ResumeViewWithIDInternal, resuming view for ID:[" + viewID + "], name:[" + vd.ViewName + "]"); + + if (vd.ViewStartTimeSeconds > 0) { + Log.Warning("[ViewCountlyService] ResumeViewWithIDInternal, resuming a view that is already running. ID:[" + viewID + "], name:[" + vd.ViewName + "]"); + return; + } + + vd.ViewStartTimeSeconds = _utils.CurrentTimestampSeconds(); + vd.IsAutoPaused = false; + } + + /// + /// Stops all open views and records a segmentation if set. + /// + /// + private void StopAllViewsInternal(Dictionary viewSegmentation) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] StopAllViewsInternal, consent is not given, ignoring the request."); + return; + } + + Log.Debug("[ViewCountlyService] StopAllViewsInternal"); + + viewSegmentation = (Dictionary)RemoveSegmentInvalidDataTypes(viewSegmentation); + + AutoCloseRequiredViews(true, viewSegmentation); + } + + /// + /// Set a segmentation to be recorded with all views + /// + /// + private void SetGlobalViewSegmentationInternal(Dictionary viewSegmentation) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] SetGlobalViewSegmentation, consent is not given, ignoring the request."); + return; + } + + Log.Debug("[ViewCountlyService] SetGlobalViewSegmentationInternal, with[" + (viewSegmentation == null ? "null" : viewSegmentation.Count.ToString()) + "] entries"); + automaticViewSegmentation.Clear(); + + if (viewSegmentation != null) { + _utils.RemoveReservedKeysFromSegmentation(viewSegmentation, reservedSegmentationKeysViews, "[ViewCountlyService] SetGlobalViewSegmentationInternal, ", Log); + viewSegmentation = (Dictionary)RemoveSegmentInvalidDataTypes(viewSegmentation); + _utils.CopyDictionaryToDestination(automaticViewSegmentation, viewSegmentation, Log); + } + } + + /// + /// Updates the segmentation of a view. + /// + /// + /// + private void AddSegmentationToViewWithIDInternal(string viewID, Dictionary viewSegmentation) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] AddSegmentationToViewWithIDInternal, consent is not given, ignoring the request."); + return; + } + + if (_utils.IsNullEmptyOrWhitespace(viewID) || viewSegmentation == null) { + Log.Warning("[ViewsCountlyService] AddSegmentationToViewWithIDInternal, null or empty parameters provided"); + return; + } + + if (!viewDataMap.ContainsKey(viewID)) { + Log.Warning("[ViewsCountlyService] AddSegmentationToViewWithIDInternal, there is no view with the provided view id"); + return; + } + + ViewData vd = viewDataMap[viewID]; + if (vd == null) { + Log.Warning("[ViewsCountlyService] AddSegmentationToViewWithIDInternal, view id:[" + viewID + "] has a 'null' view data. This should not be happening"); + return; + } + + _utils.TruncateSegmentationValues(viewSegmentation, _cly.Configuration.GetMaxSegmentationValues(), "[ViewsCountlyService] AddSegmentationToViewWithIDInternal", Log); + _utils.RemoveReservedKeysFromSegmentation(viewSegmentation, reservedSegmentationKeysViews, "[ViewsCountlyService] AddSegmentationToViewWithIDInternal, ", Log); + + if (vd.ViewSegmentation == null) { + vd.ViewSegmentation = new Dictionary(viewSegmentation); + } else { + _utils.CopyDictionaryToDestination(vd.ViewSegmentation, vd.ViewSegmentation, Log); + } + } + + /// + /// Updates the segmentation of a view. + /// + /// + /// + private void AddSegmentationToViewWithNameInternal(string viewName, Dictionary viewSegmentation) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] AddSegmentationToViewWithNameInternal, consent is not given, ignoring the request."); + return; + } + + string viewID = null; + + foreach (var entry in viewDataMap) { + string key = entry.Key; + ViewData vd = entry.Value; + + if (vd != null && viewName != null && viewName.Equals(vd.ViewName)) { + viewID = key; + } + } + + if (viewID == null) { + Log.Warning("[ViewsCountlyService] AddSegmentationToViewWithNameInternal, no view entry found with the provided name :[" + viewName + "]"); + return; + } + + Log.Info("[ViewsCountlyService] AddSegmentationToViewWithNameInternal, will add segmentation for view: [" + viewName + "] with ID:[" + viewID + "]"); + + AddSegmentationToViewWithIDInternal(viewID, viewSegmentation); + } + + /// + /// Updates the global segmentation + /// + /// + private void UpdateGlobalViewSegmentationInternal(Dictionary viewSegmentation) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] UpdateGlobalViewSegmentationInternal, consent is not given, ignoring the request."); + return; + } + + if (viewSegmentation == null) { + Log.Warning("[ViewCountlyService] UpdateGlobalViewSegmentationInternal, when updating segmentation values, they can't be 'null'. Ignoring request."); + return; + } + + viewSegmentation = (Dictionary)RemoveSegmentInvalidDataTypes(viewSegmentation); + + _utils.RemoveReservedKeysFromSegmentation(viewSegmentation, reservedSegmentationKeysViews, "[ViewsCountlyService] UpdateGlobalViewSegmentationInternal, ", Log); + _utils.CopyDictionaryToDestination(automaticViewSegmentation, viewSegmentation, Log); + } + #endregion + #region Deprecated Methods + /// + /// Records the opening of a view. This method is deprecated. + /// + /// + /// This method must be used in conjunction with . + /// Do not use with as it will not function correctly. + /// Please use and for new implementations. + /// + /// The name of the view to open. + /// Optional segmentation data for the view. + /// A task representing the asynchronous operation. + [Obsolete("RecordOpenViewAsync(string name, IDictionary segmentation = null) is deprecated and will be removed in the future. Please use StartView instead.")] + public async Task RecordOpenViewAsync(string name, IDictionary segmentation = null) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] RecordOpenViewAsync, consent is not given, ignoring the request."); + return; + } + + lock (LockObj) { + Log.Info("[ViewCountlyService] RecordOpenViewAsync: name = " + name); + StartViewInternal(name, (Dictionary)segmentation, false); + } + + await Task.CompletedTask; + } + + /// + /// Records the closing of a view. This method is deprecated. + /// + /// + /// This method should only be used to close views that were opened using . + /// Do not use to close views started with . + /// + /// The name of the view to close. + /// A task representing the asynchronous operation. + [Obsolete("RecordCloseViewAsync(string name) is deprecated and will be removed in the future. Please use StopView instead.")] + public async Task RecordCloseViewAsync(string name) + { + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] RecordCloseViewAsync, consent is not given, ignoring the request."); + return; + } + + lock (LockObj) { + Log.Info("[ViewCountlyService] RecordCloseViewAsync: name = " + name); + StopViewWithNameInternal(name, null); + } + + await Task.CompletedTask; + } + + /// + /// Reports a particular action with the specified details. + /// + /// + /// This method is deprecated and will be removed in a future release. There is no direct replacement for this method. + /// Consider re-evaluating the need for this functionality or implementing a custom solution as needed. + /// + /// The type of action. + /// The x-coordinate. + /// The y-coordinate. + /// The width of the screen. + /// The height of the screen. + /// A task representing the asynchronous operation. + [Obsolete("ReportActionAsync(string type, int x, int y, int width, int height) is deprecated and will be removed in the future.")] + public async Task ReportActionAsync(string type, int x, int y, int width, int height) + { + lock (LockObj) { + Log.Info("[ViewCountlyService] ReportActionAsync : type = " + type + ", x = " + x + ", y = " + y + ", width = " + width + ", height = " + height); + + if (!_consentService.CheckConsentInternal(Consents.Views)) { + Log.Debug("[ViewCountlyService] ReportActionAsync, consent is not given, ignoring the request."); + return; + } + + IDictionary segmentation = new Dictionary() + { + {"type", type}, + {"x", x}, + {"y", y}, + {"width", width}, + {"height", height}, + }; + CountlyEventModel currentView = new CountlyEventModel(CountlyEventModel.ViewActionEvent, segmentation); + _ = _eventService.RecordEventAsync(currentView); + } + await Task.CompletedTask; + } + + #region override Methods + internal override void DeviceIdChanged(string deviceId, bool merged) + { + if (!merged) { + _isFirstView = true; + } + } + #endregion + + #endregion + } +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ViewCountlyService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ViewCountlyService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/CountlySDK/Services/ViewCountlyService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/CountlySDK/Services/ViewCountlyService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Editor.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Editor.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Editor.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Editor.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Editor/CountlyEditorMenu.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Editor/CountlyEditorMenu.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Editor/CountlyEditorMenu.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Editor/CountlyEditorMenu.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Editor/CountlyEditorMenu.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Editor/CountlyEditorMenu.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Editor/CountlyEditorMenu.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Editor/CountlyEditorMenu.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/INotificationsService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/INotificationsService.cs similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/INotificationsService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/INotificationsService.cs diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/INotificationsService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/INotificationsService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/INotificationsService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/INotificationsService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidBridge.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidBridge.cs similarity index 97% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidBridge.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidBridge.cs index 548c743ab..56e321345 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidBridge.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidBridge.cs @@ -43,8 +43,7 @@ public void OnNotificationClicked(string data) JObject jObject = JObject.Parse(data); - if (jObject != null) - { + if (jObject != null) { index = (int)jObject.GetValue("click_index"); } _OnNotificationClickResult?.Invoke(data, index); diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidBridge.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidBridge.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidBridge.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidBridge.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs similarity index 91% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs index b6a7ffd56..06c068992 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs @@ -7,7 +7,7 @@ using System.IO; using System.Threading.Tasks; using UnityEngine; - +#pragma warning disable 0618 namespace Notifications.Impls.Android { public class AndroidNotificationsService : INotificationsService @@ -38,14 +38,11 @@ internal AndroidNotificationsService(Transform countlyGameObject, CountlyConfigu _bridge = gameObject.AddComponent(); _bridge.Log = Log; - try - { + try { AndroidJavaClass countlyPushPlugin = new AndroidJavaClass(CountlyPushPluginPackageName); countlyPushPlugin.CallStatic("setEnableLog", config.EnableConsoleLogging); IsInitializedWithoutError = true; - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Error("[AndroidNotificationsService] Exception in initializing service: " + ex.Message); IsInitializedWithoutError = false; } @@ -86,8 +83,7 @@ public async Task ReportPushActionAsync() AndroidJavaClass store = new AndroidJavaClass(StorePackageName); bool isInitialized = store.CallStatic("isInitialized"); - if (!isInitialized) - { + if (!isInitialized) { AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject activity = unityPlayer.GetStatic("currentActivity"); AndroidJavaObject applicationContext = activity.Call("getApplicationContext"); @@ -96,10 +92,8 @@ public async Task ReportPushActionAsync() } string data = store.CallStatic("getMessagesData"); - if (string.IsNullOrEmpty(data)) - { - return new CountlyResponse - { + if (string.IsNullOrEmpty(data)) { + return new CountlyResponse { IsSuccess = false, ErrorMessage = "Key is required." }; @@ -107,10 +101,8 @@ public async Task ReportPushActionAsync() JArray jArray = JArray.Parse(data); - if (jArray != null) - { - foreach (JObject item in jArray) - { + if (jArray != null) { + foreach (JObject item in jArray) { string mesageId = item.GetValue("messageId").ToString(); string identifier = item.GetValue("action_index").ToString(); Dictionary segment = new Dictionary() @@ -131,8 +123,7 @@ public async Task ReportPushActionAsync() } - return new CountlyResponse - { + return new CountlyResponse { IsSuccess = true, }; } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/Android/AndroidNotificationsService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/NotificationsCallbackService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/NotificationsCallbackService.cs similarity index 90% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/NotificationsCallbackService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/NotificationsCallbackService.cs index cfe6fe5c8..66f63500e 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/NotificationsCallbackService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/NotificationsCallbackService.cs @@ -23,8 +23,7 @@ internal NotificationsCallbackService(CountlyConfiguration configuration, Countl /// public void AddListener(INotificationListener listener) { - if (_listeners.Contains(listener)) - { + if (_listeners.Contains(listener)) { return; } @@ -38,8 +37,7 @@ public void AddListener(INotificationListener listener) /// public void RemoveListener(INotificationListener listener) { - if (!_listeners.Contains(listener)) - { + if (!_listeners.Contains(listener)) { return; } @@ -54,10 +52,8 @@ public void RemoveListener(INotificationListener listener) /// internal void NotifyOnNotificationReceived(string data) { - foreach (INotificationListener listener in _listeners) - { - if (listener != null) - { + foreach (INotificationListener listener in _listeners) { + if (listener != null) { listener.OnNotificationReceived(data); } } @@ -73,10 +69,8 @@ internal void NotifyOnNotificationReceived(string data) /// internal void NotifyOnNotificationClicked(string data, int index) { - foreach (INotificationListener listener in _listeners) - { - if (listener != null) - { + foreach (INotificationListener listener in _listeners) { + if (listener != null) { listener.OnNotificationClicked(data, index); } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/NotificationsCallbackService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/NotificationsCallbackService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/NotificationsCallbackService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/NotificationsCallbackService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/ProxyNotificationsService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/ProxyNotificationsService.cs similarity index 88% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/ProxyNotificationsService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/ProxyNotificationsService.cs index 2a1daa41e..4b19c0450 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/ProxyNotificationsService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/ProxyNotificationsService.cs @@ -7,7 +7,7 @@ using Plugins.CountlySDK.Models; using Plugins.CountlySDK.Services; using UnityEngine; - +#pragma warning disable 0618 namespace Notifications.Impls { public class ProxyNotificationsService : INotificationsService @@ -24,8 +24,7 @@ internal ProxyNotificationsService(Transform countlyGameObject, CountlyConfigura _countlyGameObject = countlyGameObject; - if (config.NotificationMode == TestMode.None) - { + if (config.NotificationMode == TestMode.None) { return; } @@ -35,8 +34,7 @@ internal ProxyNotificationsService(Transform countlyGameObject, CountlyConfigura _service = new Notifications.Impls.iOs.IOsNotificationsService(_countlyGameObject, config, logHelper, startCoroutine, eventCountlyService); #endif IsInitializedWithoutError = true; - if (_service != null && !_service.IsInitializedWithoutError) - { + if (_service != null && !_service.IsInitializedWithoutError) { _service = null; IsInitializedWithoutError = false; } @@ -46,8 +44,7 @@ public void GetToken(Action result) { _logHelper.Verbose("[ProxyNotificationsService] GetToken"); - if (_service != null) - { + if (_service != null) { _service.GetToken(result); } @@ -57,8 +54,7 @@ public void OnNotificationClicked(Action result) { _logHelper.Verbose("[ProxyNotificationsService] OnNotificationClicked"); - if (_service != null) - { + if (_service != null) { _service.OnNotificationClicked(result); } } @@ -68,8 +64,7 @@ public void OnNotificationReceived(Action result) { _logHelper.Verbose("[ProxyNotificationsService] OnNotificationReceived"); - if (_service != null) - { + if (_service != null) { _service.OnNotificationReceived(result); } } @@ -78,13 +73,11 @@ public async Task ReportPushActionAsync() { _logHelper.Verbose("[ProxyNotificationsService] ReportPushActionAsync"); - if (_service != null) - { + if (_service != null) { return await _service.ReportPushActionAsync(); } - return new CountlyResponse - { + return new CountlyResponse { IsSuccess = true, }; } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/ProxyNotificationsService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/ProxyNotificationsService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/ProxyNotificationsService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/ProxyNotificationsService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/IOSBridge.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/IOSBridge.cs similarity index 97% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/IOSBridge.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/IOSBridge.cs index e85377684..7514f79e8 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/IOSBridge.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/IOSBridge.cs @@ -43,8 +43,7 @@ void OnDidRegisterForRemoteNotificationsWithDeviceToken(string deviceToken) { Log.Debug("[IOSBridge] OnDidRegisterForRemoteNotificationsWithDeviceToken Token: " + deviceToken); - if (deviceToken != null && deviceToken.Length != 0) - { + if (deviceToken != null && deviceToken.Length != 0) { _onTokenResult?.Invoke(deviceToken); } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/IOSBridge.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/IOSBridge.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/IOSBridge.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/IOSBridge.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs similarity index 96% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs index a250b3a65..4fbe626b5 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs @@ -49,8 +49,7 @@ public async Task ReportPushActionAsync() string mesageId = _bridge.MessageId; string identifier = _bridge.ButtonIndex; - if (_bridge.MessageId != null) - { + if (_bridge.MessageId != null) { IDictionary segment = new Dictionary() { {"b", mesageId}, @@ -67,8 +66,7 @@ public async Task ReportPushActionAsync() _bridge.MessageId = null; _bridge.ButtonIndex = null; - return new CountlyResponse - { + return new CountlyResponse { IsSuccess = true, }; } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/Notifications/Impls/iOs/iOsNotificationsService.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB/Dao.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB/Dao.cs similarity index 76% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB/Dao.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB/Dao.cs index cdf722fe5..7e249738a 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB/Dao.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB/Dao.cs @@ -22,17 +22,13 @@ public Dao(AutoBox auto, string table, CountlyLogHelper log) public bool Save(TEntity entity) { - try - { + try { bool insertionResult = Auto.Insert(Table, entity); - if (!insertionResult) - { + if (!insertionResult) { Log.Info("[Dao] Save: Auto.Insert result: [" + insertionResult + "]"); } return insertionResult; - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Error("[Dao] Save: Couldn't complete db operation, [" + ex.Message + "]"); } @@ -41,17 +37,13 @@ public bool Save(TEntity entity) public bool Update(TEntity entity) { - try - { + try { bool updateResult = Auto.Update(Table, entity); - if (!updateResult) - { + if (!updateResult) { Log.Info("[Dao] Update: Auto.Update result: [" + updateResult + "]"); } return updateResult; - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Error("[Dao] Update: Couldn't complete db operation, [" + ex.Message + "]"); } @@ -61,17 +53,13 @@ public bool Update(TEntity entity) public List LoadAll() { List result = new List(); - try - { + try { result = Auto.Select("from " + Table + " order by Id asc"); - if (result.Count == 0) - { + if (result.Count == 0) { Log.Info("[Dao] LoadAll: Auto.Select result: [" + string.Join(", ", result) + "]"); } return result; - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Error("[Dao] LoadAll: Couldn't complete db operation, [" + ex.Message + "]"); } @@ -80,40 +68,30 @@ public List LoadAll() public void Remove(params object[] key) { - try - { + try { bool deletionResult = Auto.Delete(Table, key); - if (!deletionResult) - { + if (!deletionResult) { Log.Info("[Dao] Remove: Auto.Delete result: [" + deletionResult + "]"); } - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Error("[Dao] Remove: Couldn't complete db operation, [" + ex.Message + "]"); } } public void RemoveAll() { - try - { + try { List list = Auto.Select("from " + Table); - if (list.Count == 0) - { + if (list.Count == 0) { Log.Info("[Dao] RemoveAll: Auto.Select result: [" + string.Join(", ", list) + "]"); } - foreach (TEntity entity in list) - { + foreach (TEntity entity in list) { bool deletionResult = Auto.Delete(Table, entity.GetId()); - if (!deletionResult) - { + if (!deletionResult) { Log.Info("[Dao] RemoveAll: Auto.Delete result: [" + deletionResult + "]"); } } - } - catch (Exception ex) - { + } catch (Exception ex) { Log.Error("[Dao] RemoveAll: Couldn't complete db operation, [" + ex.Message + "]"); } } @@ -121,17 +99,13 @@ public void RemoveAll() public long GenerateNewId() { long result; - try - { + try { result = Auto.NewId(); - if (result < 0) - { + if (result < 0) { Log.Info("[Dao] GenerateNewId: Auto.NewId result: [" + result + "]"); } return result; - } - catch (Exception ex) - { + } catch (Exception ex) { result = 0; Log.Error("[Dao] GenerateNewId: Couldn't complete db operation, [" + ex.Message + "]"); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB/Dao.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB/Dao.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB/Dao.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB/Dao.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB/iBoxDB.NET2.dll b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB/iBoxDB.NET2.dll old mode 100755 new mode 100644 similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB/iBoxDB.NET2.dll rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB/iBoxDB.NET2.dll diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB/iBoxDB.NET2.dll.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB/iBoxDB.NET2.dll.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iBoxDB/iBoxDB.NET2.dll.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iBoxDB/iBoxDB.NET2.dll.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyNotificationService.h b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyNotificationService.h similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyNotificationService.h rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyNotificationService.h diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyNotificationService.h.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyNotificationService.h.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyNotificationService.h.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyNotificationService.h.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyNotificationService.m b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyNotificationService.m similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyNotificationService.m rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyNotificationService.m diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyNotificationService.m.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyNotificationService.m.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyNotificationService.m.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyNotificationService.m.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyPushHandlerInternal.h b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyPushHandlerInternal.h similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyPushHandlerInternal.h rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyPushHandlerInternal.h diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyPushHandlerInternal.h.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyPushHandlerInternal.h.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyPushHandlerInternal.h.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyPushHandlerInternal.h.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyPushHandlerInternal.m b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyPushHandlerInternal.m similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyPushHandlerInternal.m rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyPushHandlerInternal.m diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyPushHandlerInternal.m.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyPushHandlerInternal.m.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly SDK/Plugins/iOS/CountlyPushHandlerInternal.m.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/Plugins/iOS/CountlyPushHandlerInternal.m.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/csc.rsp.meta b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/csc.rsp.meta new file mode 100644 index 000000000..b29495dcd --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/Countly/csc.rsp.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a24005f16a377574c88b9a818a391065 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/WebSocket/CSWebSocket.cs b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/WebSocket/CSWebSocket.cs index 812e2d308..2f800671d 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Plugins/WebSocket/CSWebSocket.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Plugins/WebSocket/CSWebSocket.cs @@ -6,198 +6,238 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - -using AOT; -using System.Runtime.InteropServices; using UnityEngine; using System.Collections; +using AOT; +using System.Runtime.InteropServices; -public class MainThreadUtil : MonoBehaviour +namespace Chainsafe.Gaming.Unity { - public static MainThreadUtil Instance { get; private set; } - public static SynchronizationContext synchronizationContext { get; private set; } - - [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] - public static void Setup() + public class MainThreadUtil : MonoBehaviour { - Instance = new GameObject("MainThreadUtil") - .AddComponent(); - synchronizationContext = SynchronizationContext.Current; - } + public static MainThreadUtil Instance { get; private set; } + public static SynchronizationContext synchronizationContext { get; private set; } - public static void Run(IEnumerator waitForUpdate) - { - synchronizationContext.Post(_ => Instance.StartCoroutine( - waitForUpdate), null); - } + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + public static void Setup() + { + Instance = new GameObject("MainThreadUtil") + .AddComponent(); + synchronizationContext = SynchronizationContext.Current; + } - void Awake() - { - gameObject.hideFlags = HideFlags.HideAndDontSave; - DontDestroyOnLoad(gameObject); - } -} + public static void Run(IEnumerator waitForUpdate) + { + synchronizationContext.Post(_ => Instance.StartCoroutine( + waitForUpdate), null); + } -public class WaitForUpdate : CustomYieldInstruction -{ - public override bool keepWaiting - { - get { return false; } + void Awake() + { + gameObject.hideFlags = HideFlags.HideAndDontSave; + DontDestroyOnLoad(gameObject); + } } - public MainThreadAwaiter GetAwaiter() + public class WaitForUpdate : CustomYieldInstruction { - var awaiter = new MainThreadAwaiter(); - MainThreadUtil.Run(CoroutineWrapper(this, awaiter)); - return awaiter; - } + public override bool keepWaiting + { + get { return false; } + } - public class MainThreadAwaiter : INotifyCompletion - { - Action continuation; + public MainThreadAwaiter GetAwaiter() + { + var awaiter = new MainThreadAwaiter(); + MainThreadUtil.Run(CoroutineWrapper(this, awaiter)); + return awaiter; + } + + public class MainThreadAwaiter : INotifyCompletion + { + Action continuation; - public bool IsCompleted { get; set; } + public bool IsCompleted { get; set; } - public void GetResult() { } + public void GetResult() + { + } - public void Complete() - { - IsCompleted = true; - continuation?.Invoke(); + public void Complete() + { + IsCompleted = true; + continuation?.Invoke(); + } + + void INotifyCompletion.OnCompleted(Action continuation) + { + this.continuation = continuation; + } } - void INotifyCompletion.OnCompleted(Action continuation) + public static IEnumerator CoroutineWrapper(IEnumerator theWorker, MainThreadAwaiter awaiter) { - this.continuation = continuation; + yield return theWorker; + awaiter.Complete(); } } - public static IEnumerator CoroutineWrapper(IEnumerator theWorker, MainThreadAwaiter awaiter) + namespace NativeWebSocket { - yield return theWorker; - awaiter.Complete(); - } -} + public delegate void WebSocketOpenEventHandler(); -namespace NativeWebSocket -{ - public delegate void WebSocketOpenEventHandler(); - public delegate void WebSocketMessageEventHandler(byte[] data); - public delegate void WebSocketErrorEventHandler(string errorMsg); - public delegate void WebSocketCloseEventHandler(WebSocketCloseCode closeCode); + public delegate void WebSocketMessageEventHandler(byte[] data); - public enum WebSocketCloseCode - { - /* Do NOT use NotSet - it's only purpose is to indicate that the close code cannot be parsed. */ - NotSet = 0, - Normal = 1000, - Away = 1001, - ProtocolError = 1002, - UnsupportedData = 1003, - Undefined = 1004, - NoStatus = 1005, - Abnormal = 1006, - InvalidData = 1007, - PolicyViolation = 1008, - TooBig = 1009, - MandatoryExtension = 1010, - ServerError = 1011, - TlsHandshakeFailure = 1015 - } + public delegate void WebSocketErrorEventHandler(string errorMsg); - public enum WebSocketState - { - Connecting, - Open, - Closing, - Closed - } + public delegate void WebSocketCloseEventHandler(WebSocketCloseCode closeCode); - public interface IWebSocket - { - event WebSocketOpenEventHandler OnOpen; - event WebSocketMessageEventHandler OnMessage; - event WebSocketErrorEventHandler OnError; - event WebSocketCloseEventHandler OnClose; + public enum WebSocketCloseCode + { + /* Do NOT use NotSet - it's only purpose is to indicate that the close code cannot be parsed. */ + NotSet = 0, + Normal = 1000, + Away = 1001, + ProtocolError = 1002, + UnsupportedData = 1003, + Undefined = 1004, + NoStatus = 1005, + Abnormal = 1006, + InvalidData = 1007, + PolicyViolation = 1008, + TooBig = 1009, + MandatoryExtension = 1010, + ServerError = 1011, + TlsHandshakeFailure = 1015 + } - WebSocketState State { get; } - } + public enum WebSocketState + { + Connecting, + Open, + Closing, + Closed + } - public static class WebSocketHelpers - { - public static WebSocketCloseCode ParseCloseCodeEnum(int closeCode) + public interface IWebSocket { + event WebSocketOpenEventHandler OnOpen; + event WebSocketMessageEventHandler OnMessage; + event WebSocketErrorEventHandler OnError; + event WebSocketCloseEventHandler OnClose; - if (WebSocketCloseCode.IsDefined(typeof(WebSocketCloseCode), closeCode)) + WebSocketState State { get; } + } + + public static class WebSocketHelpers + { + public static WebSocketCloseCode ParseCloseCodeEnum(int closeCode) { - return (WebSocketCloseCode)closeCode; + + if (WebSocketCloseCode.IsDefined(typeof(WebSocketCloseCode), closeCode)) + { + return (WebSocketCloseCode)closeCode; + } + else + { + return WebSocketCloseCode.Undefined; + } + } - else + + public static WebSocketException GetErrorMessageFromCode(int errorCode, Exception inner) + { + switch (errorCode) + { + case -1: + return new WebSocketUnexpectedException("WebSocket instance not found.", inner); + case -2: + return new WebSocketInvalidStateException( + "WebSocket is already connected or in connecting state.", inner); + case -3: + return new WebSocketInvalidStateException("WebSocket is not connected.", inner); + case -4: + return new WebSocketInvalidStateException("WebSocket is already closing.", inner); + case -5: + return new WebSocketInvalidStateException("WebSocket is already closed.", inner); + case -6: + return new WebSocketInvalidStateException("WebSocket is not in open state.", inner); + case -7: + return new WebSocketInvalidArgumentException( + "Cannot close WebSocket. An invalid code was specified or reason is too long.", inner); + default: + return new WebSocketUnexpectedException("Unknown error.", inner); + } + } + } + + public class WebSocketException : Exception + { + public WebSocketException() + { + } + + public WebSocketException(string message) : base(message) { - return WebSocketCloseCode.Undefined; } + public WebSocketException(string message, Exception inner) : base(message, inner) + { + } } - public static WebSocketException GetErrorMessageFromCode(int errorCode, Exception inner) + public class WebSocketUnexpectedException : WebSocketException { - switch (errorCode) - { - case -1: - return new WebSocketUnexpectedException("WebSocket instance not found.", inner); - case -2: - return new WebSocketInvalidStateException("WebSocket is already connected or in connecting state.", inner); - case -3: - return new WebSocketInvalidStateException("WebSocket is not connected.", inner); - case -4: - return new WebSocketInvalidStateException("WebSocket is already closing.", inner); - case -5: - return new WebSocketInvalidStateException("WebSocket is already closed.", inner); - case -6: - return new WebSocketInvalidStateException("WebSocket is not in open state.", inner); - case -7: - return new WebSocketInvalidArgumentException("Cannot close WebSocket. An invalid code was specified or reason is too long.", inner); - default: - return new WebSocketUnexpectedException("Unknown error.", inner); + public WebSocketUnexpectedException() + { + } + + public WebSocketUnexpectedException(string message) : base(message) + { + } + + public WebSocketUnexpectedException(string message, Exception inner) : base(message, inner) + { } } - } - public class WebSocketException : Exception - { - public WebSocketException() { } - public WebSocketException(string message) : base(message) { } - public WebSocketException(string message, Exception inner) : base(message, inner) { } - } + public class WebSocketInvalidArgumentException : WebSocketException + { + public WebSocketInvalidArgumentException() + { + } - public class WebSocketUnexpectedException : WebSocketException - { - public WebSocketUnexpectedException() { } - public WebSocketUnexpectedException(string message) : base(message) { } - public WebSocketUnexpectedException(string message, Exception inner) : base(message, inner) { } - } + public WebSocketInvalidArgumentException(string message) : base(message) + { + } - public class WebSocketInvalidArgumentException : WebSocketException - { - public WebSocketInvalidArgumentException() { } - public WebSocketInvalidArgumentException(string message) : base(message) { } - public WebSocketInvalidArgumentException(string message, Exception inner) : base(message, inner) { } - } + public WebSocketInvalidArgumentException(string message, Exception inner) : base(message, inner) + { + } + } - public class WebSocketInvalidStateException : WebSocketException - { - public WebSocketInvalidStateException() { } - public WebSocketInvalidStateException(string message) : base(message) { } - public WebSocketInvalidStateException(string message, Exception inner) : base(message, inner) { } - } + public class WebSocketInvalidStateException : WebSocketException + { + public WebSocketInvalidStateException() + { + } - public class WaitForBackgroundThread - { - public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() + public WebSocketInvalidStateException(string message) : base(message) + { + } + + public WebSocketInvalidStateException(string message, Exception inner) : base(message, inner) + { + } + } + + public class WaitForBackgroundThread { - return Task.Run(() => { }).ConfigureAwait(false).GetAwaiter(); + public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() + { + return Task.Run(() => { }).ConfigureAwait(false).GetAwaiter(); + } } - } #if UNITY_WEBGL && !UNITY_EDITOR @@ -363,371 +403,374 @@ public void DelegateOnCloseEvent (int closeCode) { #else - public class WebSocket : IWebSocket - { - public event WebSocketOpenEventHandler OnOpen; - public event WebSocketMessageEventHandler OnMessage; - public event WebSocketErrorEventHandler OnError; - public event WebSocketCloseEventHandler OnClose; - - private Uri uri; - private Dictionary headers; - private List subprotocols; - private ClientWebSocket m_Socket = new ClientWebSocket(); - - private CancellationTokenSource m_TokenSource; - private CancellationToken m_CancellationToken; - - private readonly object OutgoingMessageLock = new object(); - private readonly object IncomingMessageLock = new object(); - - private bool isSending = false; - private List> sendBytesQueue = new List>(); - private List> sendTextQueue = new List>(); - - public WebSocket(string url, Dictionary headers = null) + public class WebSocket : IWebSocket { - uri = new Uri(url); + public event WebSocketOpenEventHandler OnOpen; + public event WebSocketMessageEventHandler OnMessage; + public event WebSocketErrorEventHandler OnError; + public event WebSocketCloseEventHandler OnClose; - if (headers == null) - { - this.headers = new Dictionary(); - } - else - { - this.headers = headers; - } + private Uri uri; + private Dictionary headers; + private List subprotocols; + private ClientWebSocket m_Socket = new ClientWebSocket(); - subprotocols = new List(); + private CancellationTokenSource m_TokenSource; + private CancellationToken m_CancellationToken; - string protocol = uri.Scheme; - if (!protocol.Equals("ws") && !protocol.Equals("wss")) - throw new ArgumentException("Unsupported protocol: " + protocol); - } + private readonly object OutgoingMessageLock = new object(); + private readonly object IncomingMessageLock = new object(); - public WebSocket(string url, string subprotocol, Dictionary headers = null) - { - uri = new Uri(url); + private bool isSending = false; + private List> sendBytesQueue = new List>(); + private List> sendTextQueue = new List>(); - if (headers == null) - { - this.headers = new Dictionary(); - } - else + public WebSocket(string url, Dictionary headers = null) { - this.headers = headers; - } - - subprotocols = new List { subprotocol }; + uri = new Uri(url); - string protocol = uri.Scheme; - if (!protocol.Equals("ws") && !protocol.Equals("wss")) - throw new ArgumentException("Unsupported protocol: " + protocol); - } + if (headers == null) + { + this.headers = new Dictionary(); + } + else + { + this.headers = headers; + } - public WebSocket(string url, List subprotocols, Dictionary headers = null) - { - uri = new Uri(url); + subprotocols = new List(); - if (headers == null) - { - this.headers = new Dictionary(); + string protocol = uri.Scheme; + if (!protocol.Equals("ws") && !protocol.Equals("wss")) + throw new ArgumentException("Unsupported protocol: " + protocol); } - else + + public WebSocket(string url, string subprotocol, Dictionary headers = null) { - this.headers = headers; - } + uri = new Uri(url); - this.subprotocols = subprotocols; + if (headers == null) + { + this.headers = new Dictionary(); + } + else + { + this.headers = headers; + } - string protocol = uri.Scheme; - if (!protocol.Equals("ws") && !protocol.Equals("wss")) - throw new ArgumentException("Unsupported protocol: " + protocol); - } + subprotocols = new List { subprotocol }; - public void CancelConnection() - { - m_TokenSource?.Cancel(); - } + string protocol = uri.Scheme; + if (!protocol.Equals("ws") && !protocol.Equals("wss")) + throw new ArgumentException("Unsupported protocol: " + protocol); + } - public async Task Connect() - { - try + public WebSocket(string url, List subprotocols, Dictionary headers = null) { - m_TokenSource = new CancellationTokenSource(); - m_CancellationToken = m_TokenSource.Token; + uri = new Uri(url); - m_Socket = new ClientWebSocket(); - - foreach (var header in headers) + if (headers == null) { - m_Socket.Options.SetRequestHeader(header.Key, header.Value); + this.headers = new Dictionary(); } - - foreach (string subprotocol in subprotocols) + else { - m_Socket.Options.AddSubProtocol(subprotocol); + this.headers = headers; } - await m_Socket.ConnectAsync(uri, m_CancellationToken); - OnOpen?.Invoke(); + this.subprotocols = subprotocols; - await Receive(); + string protocol = uri.Scheme; + if (!protocol.Equals("ws") && !protocol.Equals("wss")) + throw new ArgumentException("Unsupported protocol: " + protocol); } - catch (Exception ex) - { - OnError?.Invoke(ex.Message); - OnClose?.Invoke(WebSocketCloseCode.Abnormal); - } - finally + + public void CancelConnection() { - if (m_Socket != null) - { - m_TokenSource.Cancel(); - m_Socket.Dispose(); - } + m_TokenSource?.Cancel(); } - } - public WebSocketState State - { - get + public async Task Connect() { - switch (m_Socket.State) + try { - case System.Net.WebSockets.WebSocketState.Connecting: - return WebSocketState.Connecting; + m_TokenSource = new CancellationTokenSource(); + m_CancellationToken = m_TokenSource.Token; - case System.Net.WebSockets.WebSocketState.Open: - return WebSocketState.Open; + m_Socket = new ClientWebSocket(); - case System.Net.WebSockets.WebSocketState.CloseSent: - case System.Net.WebSockets.WebSocketState.CloseReceived: - return WebSocketState.Closing; + foreach (var header in headers) + { + m_Socket.Options.SetRequestHeader(header.Key, header.Value); + } + + foreach (string subprotocol in subprotocols) + { + m_Socket.Options.AddSubProtocol(subprotocol); + } - case System.Net.WebSockets.WebSocketState.Closed: - return WebSocketState.Closed; + await m_Socket.ConnectAsync(uri, m_CancellationToken); + OnOpen?.Invoke(); - default: - return WebSocketState.Closed; + await Receive(); + } + catch (Exception ex) + { + OnError?.Invoke(ex.Message); + OnClose?.Invoke(WebSocketCloseCode.Abnormal); + } + finally + { + if (m_Socket != null) + { + m_TokenSource.Cancel(); + m_Socket.Dispose(); + } } } - } - public Task Send(byte[] bytes) - { - // return m_Socket.SendAsync(buffer, WebSocketMessageType.Binary, true, CancellationToken.None); - return SendMessage(sendBytesQueue, WebSocketMessageType.Binary, new ArraySegment(bytes)); - } + public WebSocketState State + { + get + { + switch (m_Socket.State) + { + case System.Net.WebSockets.WebSocketState.Connecting: + return WebSocketState.Connecting; - public Task SendText(string message) - { - var encoded = Encoding.UTF8.GetBytes(message); + case System.Net.WebSockets.WebSocketState.Open: + return WebSocketState.Open; - // m_Socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); - return SendMessage(sendTextQueue, WebSocketMessageType.Text, new ArraySegment(encoded, 0, encoded.Length)); - } + case System.Net.WebSockets.WebSocketState.CloseSent: + case System.Net.WebSockets.WebSocketState.CloseReceived: + return WebSocketState.Closing; - private async Task SendMessage(List> queue, WebSocketMessageType messageType, ArraySegment buffer) - { - // Return control to the calling method immediately. - // await Task.Yield (); + case System.Net.WebSockets.WebSocketState.Closed: + return WebSocketState.Closed; - // Make sure we have data. - if (buffer.Count == 0) - { - return; + default: + return WebSocketState.Closed; + } + } } - // The state of the connection is contained in the context Items dictionary. - bool sending; + public Task Send(byte[] bytes) + { + // return m_Socket.SendAsync(buffer, WebSocketMessageType.Binary, true, CancellationToken.None); + return SendMessage(sendBytesQueue, WebSocketMessageType.Binary, new ArraySegment(bytes)); + } - lock (OutgoingMessageLock) + public Task SendText(string message) { - sending = isSending; + var encoded = Encoding.UTF8.GetBytes(message); - // If not, we are now. - if (!isSending) - { - isSending = true; - } + // m_Socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); + return SendMessage(sendTextQueue, WebSocketMessageType.Text, + new ArraySegment(encoded, 0, encoded.Length)); } - if (!sending) + private async Task SendMessage(List> queue, WebSocketMessageType messageType, + ArraySegment buffer) { - // Lock with a timeout, just in case. - if (!Monitor.TryEnter(m_Socket, 1000)) + // Return control to the calling method immediately. + // await Task.Yield (); + + // Make sure we have data. + if (buffer.Count == 0) { - // If we couldn't obtain exclusive access to the socket in one second, something is wrong. - await m_Socket.CloseAsync(WebSocketCloseStatus.InternalServerError, string.Empty, m_CancellationToken); return; } - try + // The state of the connection is contained in the context Items dictionary. + bool sending; + + lock (OutgoingMessageLock) { - // Send the message synchronously. - var t = m_Socket.SendAsync(buffer, messageType, true, m_CancellationToken); - t.Wait(m_CancellationToken); + sending = isSending; + + // If not, we are now. + if (!isSending) + { + isSending = true; + } } - finally + + if (!sending) { - Monitor.Exit(m_Socket); - } + // Lock with a timeout, just in case. + if (!Monitor.TryEnter(m_Socket, 1000)) + { + // If we couldn't obtain exclusive access to the socket in one second, something is wrong. + await m_Socket.CloseAsync(WebSocketCloseStatus.InternalServerError, string.Empty, + m_CancellationToken); + return; + } - // Note that we've finished sending. - lock (OutgoingMessageLock) + try + { + // Send the message synchronously. + var t = m_Socket.SendAsync(buffer, messageType, true, m_CancellationToken); + t.Wait(m_CancellationToken); + } + finally + { + Monitor.Exit(m_Socket); + } + + // Note that we've finished sending. + lock (OutgoingMessageLock) + { + isSending = false; + } + + // Handle any queued messages. + await HandleQueue(queue, messageType); + } + else { - isSending = false; + // Add the message to the queue. + lock (OutgoingMessageLock) + { + queue.Add(buffer); + } } - - // Handle any queued messages. - await HandleQueue(queue, messageType); } - else + + private async Task HandleQueue(List> queue, WebSocketMessageType messageType) { - // Add the message to the queue. + var buffer = new ArraySegment(); lock (OutgoingMessageLock) { - queue.Add(buffer); + // Check for an item in the queue. + if (queue.Count > 0) + { + // Pull it off the top. + buffer = queue[0]; + queue.RemoveAt(0); + } } - } - } - private async Task HandleQueue(List> queue, WebSocketMessageType messageType) - { - var buffer = new ArraySegment(); - lock (OutgoingMessageLock) - { - // Check for an item in the queue. - if (queue.Count > 0) + // Send that message. + if (buffer.Count > 0) { - // Pull it off the top. - buffer = queue[0]; - queue.RemoveAt(0); + await SendMessage(queue, messageType, buffer); } } - // Send that message. - if (buffer.Count > 0) - { - await SendMessage(queue, messageType, buffer); - } - } + private List m_MessageList = new List(); - private List m_MessageList = new List(); - - // simple dispatcher for queued messages. - public void DispatchMessageQueue() - { - if (m_MessageList.Count == 0) + // simple dispatcher for queued messages. + public void DispatchMessageQueue() { - return; - } + if (m_MessageList.Count == 0) + { + return; + } - List messageListCopy; + List messageListCopy; - lock (IncomingMessageLock) - { - messageListCopy = new List(m_MessageList); - m_MessageList.Clear(); - } + lock (IncomingMessageLock) + { + messageListCopy = new List(m_MessageList); + m_MessageList.Clear(); + } - var len = messageListCopy.Count; - for (int i = 0; i < len; i++) - { - OnMessage?.Invoke(messageListCopy[i]); + var len = messageListCopy.Count; + for (int i = 0; i < len; i++) + { + OnMessage?.Invoke(messageListCopy[i]); + } } - } - - public async Task Receive() - { - WebSocketCloseCode closeCode = WebSocketCloseCode.Abnormal; - await new WaitForBackgroundThread(); - ArraySegment buffer = new ArraySegment(new byte[8192]); - try + public async Task Receive() { - while (m_Socket.State == System.Net.WebSockets.WebSocketState.Open) - { - WebSocketReceiveResult result = null; + WebSocketCloseCode closeCode = WebSocketCloseCode.Abnormal; + await new WaitForBackgroundThread(); - using (var ms = new MemoryStream()) + ArraySegment buffer = new ArraySegment(new byte[8192]); + try + { + while (m_Socket.State == System.Net.WebSockets.WebSocketState.Open) { - do + WebSocketReceiveResult result = null; + + using (var ms = new MemoryStream()) { - result = await m_Socket.ReceiveAsync(buffer, m_CancellationToken); - ms.Write(buffer.Array, buffer.Offset, result.Count); - } - while (!result.EndOfMessage); + do + { + result = await m_Socket.ReceiveAsync(buffer, m_CancellationToken); + ms.Write(buffer.Array, buffer.Offset, result.Count); + } while (!result.EndOfMessage); - ms.Seek(0, SeekOrigin.Begin); + ms.Seek(0, SeekOrigin.Begin); - if (result.MessageType == WebSocketMessageType.Text) - { - lock (IncomingMessageLock) + if (result.MessageType == WebSocketMessageType.Text) { - m_MessageList.Add(ms.ToArray()); + lock (IncomingMessageLock) + { + m_MessageList.Add(ms.ToArray()); + } + + //using (var reader = new StreamReader(ms, Encoding.UTF8)) + //{ + // string message = reader.ReadToEnd(); + // OnMessage?.Invoke(this, new MessageEventArgs(message)); + //} } - - //using (var reader = new StreamReader(ms, Encoding.UTF8)) - //{ - // string message = reader.ReadToEnd(); - // OnMessage?.Invoke(this, new MessageEventArgs(message)); - //} - } - else if (result.MessageType == WebSocketMessageType.Binary) - { - lock (IncomingMessageLock) + else if (result.MessageType == WebSocketMessageType.Binary) { - m_MessageList.Add(ms.ToArray()); + lock (IncomingMessageLock) + { + m_MessageList.Add(ms.ToArray()); + } + } + else if (result.MessageType == WebSocketMessageType.Close) + { + await Close(); + closeCode = WebSocketHelpers.ParseCloseCodeEnum((int)result.CloseStatus); + break; } - } - else if (result.MessageType == WebSocketMessageType.Close) - { - await Close(); - closeCode = WebSocketHelpers.ParseCloseCodeEnum((int)result.CloseStatus); - break; } } } + catch (Exception) + { + m_TokenSource.Cancel(); + } + finally + { + await new WaitForUpdate(); + OnClose?.Invoke(closeCode); + } } - catch (Exception) - { - m_TokenSource.Cancel(); - } - finally - { - await new WaitForUpdate(); - OnClose?.Invoke(closeCode); - } - } - public async Task Close() - { - if (State == WebSocketState.Open) + public async Task Close() { - try - { - await m_Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, m_CancellationToken); - } - catch (Exception e) + if (State == WebSocketState.Open) { - UnityEngine.Debug.LogError(">> WebSocket exception: " + e.Message); + try + { + await m_Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, + m_CancellationToken); + } + catch (Exception e) + { + UnityEngine.Debug.LogError(">> WebSocket exception: " + e.Message); + } } } } - } #endif - /// - /// Factory - /// + /// + /// Factory + /// - /// - /// Class providing static access methods to work with JSLIB WebSocket or WebSocketSharp interface - /// - public static class WebSocketFactory - { + /// + /// Class providing static access methods to work with JSLIB WebSocket or WebSocketSharp interface + /// + public static class WebSocketFactory + { #if UNITY_WEBGL && !UNITY_EDITOR /* Map of websocket instances */ @@ -841,16 +884,17 @@ public static void DelegateOnCloseEvent (int instanceId, int closeCode) { } #endif - /// - /// Create WebSocket client instance - /// - /// The WebSocket instance. - /// WebSocket valid URL. - public static WebSocket CreateInstance(string url) - { - return new WebSocket(url); + /// + /// Create WebSocket client instance + /// + /// The WebSocket instance. + /// WebSocket valid URL. + public static WebSocket CreateInstance(string url) + { + return new WebSocket(url); + } + } } - } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/CountlyAnalytics.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/CountlyAnalytics.cs index 1cc8b2c1f..3c4cc5d71 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/CountlyAnalytics.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/CountlyAnalytics.cs @@ -39,7 +39,7 @@ public CountlyAnalytics(IChainConfigSet chainConfigSet, IChainManager chainManag { "analyticsVersion", AnalyticsVersion } }; - Countly.Instance.UserDetails.SetCustomUserDetails(userDetails); + Countly.Instance.UserProfile.SetProperties(userDetails); ProjectConfig = projectConfig; } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/IPFS/UploadPlatforms.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/IPFS/UploadPlatforms.cs index beb043b75..65ba925fc 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/IPFS/UploadPlatforms.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/IPFS/UploadPlatforms.cs @@ -9,8 +9,9 @@ public class UploadPlatforms { #region Fields - +#if UNITY_WEBGL && !UNITY_EDITOR public static event EventHandler ImageSelected; +#endif #endregion diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/LocalWalletButton.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/LocalWalletButton.cs index 0b1fd9b91..c5e9abe4b 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/LocalWalletButton.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/LocalWalletButton.cs @@ -43,7 +43,7 @@ private void Awake() ); } - public async void Set(WalletModel data, string walletIconEndpoint, HttpHeader[] httpHeaders, Action onClick) + public void Set(WalletModel data, string walletIconEndpoint, HttpHeader[] httpHeaders, Action onClick) { walletData = data; this.walletIconEndpoint = walletIconEndpoint; diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/WebSocketConnection.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/WebSocketConnection.cs index f19745ba9..e6d565ca0 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/WebSocketConnection.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/WebSocketConnection.cs @@ -1,8 +1,9 @@ +#pragma warning disable 00067 using System; using System.IO; using System.Threading.Tasks; using ChainSafe.Gaming.Evm.Unity; -using NativeWebSocket; +using Chainsafe.Gaming.Unity.NativeWebSocket; using Newtonsoft.Json; using Reown.Core.Common; using Reown.Core.Common.Logging; diff --git a/Packages/io.chainsafe.web3-unity/Runtime/chainsafe.web3-unity.asmdef b/Packages/io.chainsafe.web3-unity/Runtime/chainsafe.web3-unity.asmdef index 3db91aa8a..148c10f74 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/chainsafe.web3-unity.asmdef +++ b/Packages/io.chainsafe.web3-unity/Runtime/chainsafe.web3-unity.asmdef @@ -4,7 +4,8 @@ "references": [ "GUID:6055be8ebefd69e48b49212b09b47b2f", "GUID:1e69005fbbf5a4cd0a6c61596a74886e", - "GUID:75469ad4d38634e559750d17036d5f7c" + "GUID:75469ad4d38634e559750d17036d5f7c", + "GUID:097393a5382fd4a89a5a9de92743d1db" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/src/UnitySampleProject/Assets/Samples/web3.unity SDK/3.0.6/Web3.Unity Samples/Scripts/Samples/EvmSample.cs b/src/UnitySampleProject/Assets/Samples/web3.unity SDK/3.0.6/Web3.Unity Samples/Scripts/Samples/EvmSample.cs index 90d4607ad..1264f278c 100644 --- a/src/UnitySampleProject/Assets/Samples/web3.unity SDK/3.0.6/Web3.Unity Samples/Scripts/Samples/EvmSample.cs +++ b/src/UnitySampleProject/Assets/Samples/web3.unity SDK/3.0.6/Web3.Unity Samples/Scripts/Samples/EvmSample.cs @@ -15,7 +15,6 @@ using Newtonsoft.Json; using Scripts.EVM.Token; using UnityEngine; - public class EvmSample : MonoBehaviour, ISample { #region Fields @@ -42,27 +41,11 @@ public class EvmSample : MonoBehaviour, ISample [SerializeField] private string methodCall = "myTotal"; #endregion - - #region Get Send Array - - [Header("Array Calls")] - [SerializeField] private string methodArrayGet = "getStore"; - [SerializeField] private string methodArraySend = "setStore"; - [SerializeField] - private string[] stringArraySend = - { - "0xFb3aECf08940785D4fB3Ad87cDC6e1Ceb20e9aac", - "0x92d4040e4f3591e60644aaa483821d1bd87001e3" - }; - - #endregion - + #region Sign Verify Sha3 [Header("Sign Verify SHA3 calls")] [SerializeField] private string messageSign = "The right man in the wrong place can make all the difference in the world."; - [SerializeField] private string messageSignVerify = "A man chooses, a slave obeys."; - [SerializeField] private string messageSha = "It’s dangerous to go alone, take this!"; #endregion @@ -74,22 +57,7 @@ public class EvmSample : MonoBehaviour, ISample #endregion - #region Registered Contract - - [Header("Registered Contract Call")] - [SerializeField] private string registeredContractName = "CsTestErc20"; - - #endregion - #region ECDSA - - [Header("ECDSA Calls")] - [SerializeField] private string ecdsaKey = "0x78dae1a22c7507a4ed30c06172e7614eb168d3546c13856340771e63ad3c0081"; - [SerializeField] private string ecdsaMessage = "This is a test message"; - [SerializeField] private string transactionHash = "0x123456789"; - [SerializeField] private string chainId = "11155111"; - - #endregion #region Multi Call