From 84207b9450bb0412208603ec59e67535632d717d Mon Sep 17 00:00:00 2001 From: Fadi George Date: Wed, 8 Oct 2025 14:27:54 -0700 Subject: [PATCH 1/3] add formatting checks --- .github/workflows/ci.yml | 24 ++ .vscode/extensions.json | 3 + .vscode/settings.json | 7 + .../Example/OneSignalExampleBehaviour.cs | 278 +++++++++++------- 4 files changed, 212 insertions(+), 100 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .vscode/extensions.json create mode 100644 .vscode/settings.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..7b2b08069 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: Run Checks +on: + pull_request: + branches: + - "**" + +jobs: + test: + runs-on: ubuntu-22.04 + + steps: + - name: Checkout code + uses: actions/checkout@v5 + + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: "8.0.x" + + - name: Install CSharpier + run: dotnet tool install -g csharpier + + - name: Check formatting + run: csharpier check . diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..6a14f76f5 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["csharpier.csharpier-vscode"] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..2ac044a84 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true, + "[csharp]": { + "editor.defaultFormatter": "csharpier.csharpier-vscode" + } +} diff --git a/OneSignalExample/Assets/OneSignal/Example/OneSignalExampleBehaviour.cs b/OneSignalExample/Assets/OneSignal/Example/OneSignalExampleBehaviour.cs index 9df95bfd2..5198ab7f9 100644 --- a/OneSignalExample/Assets/OneSignal/Example/OneSignalExampleBehaviour.cs +++ b/OneSignalExample/Assets/OneSignal/Example/OneSignalExampleBehaviour.cs @@ -43,7 +43,8 @@ /// /// Example class to show how an application can utilize the public methods of the OneSignal SDK /// -public class OneSignalExampleBehaviour : MonoBehaviour { +public class OneSignalExampleBehaviour : MonoBehaviour +{ /// /// set to an email address you would like to test notifications against /// @@ -71,72 +72,72 @@ public class OneSignalExampleBehaviour : MonoBehaviour { public bool consentRequired; /// - /// + /// /// public bool consentGiven; /// - /// + /// /// public string language; /// - /// + /// /// public string aliasKey; /// - /// + /// /// public string aliasValue; /// - /// + /// /// public string tagKey; /// - /// + /// /// public string tagValue; /// - /// + /// /// public string triggerKey; /// - /// + /// /// public string triggerValue; /// - /// + /// /// public string outcomeKey; /// - /// + /// /// public float outcomeValue; /// - /// + /// /// public string liveActivityId; /// - /// + /// /// public string liveActivityIdToken; /// - /// + /// /// public string liveActivityType; /// - /// + /// /// public string liveActivityTypeToken; @@ -144,7 +145,8 @@ public class OneSignalExampleBehaviour : MonoBehaviour { /// we recommend initializing OneSignal early in your application's lifecycle such as in the Start method of a /// MonoBehaviour in your opening Scene /// - private void Start() { + private void Start() + { // Enable lines below to debug issues with OneSignal OneSignal.Debug.LogLevel = LogLevel.Verbose; OneSignal.Debug.AlertLevel = LogLevel.Fatal; @@ -179,54 +181,70 @@ private void Start() { /* * SDK events */ - - private void _notificationOnClick(object sender, NotificationClickEventArgs e) { + + private void _notificationOnClick(object sender, NotificationClickEventArgs e) + { _log($"Notification was clicked with Notification: {JsonUtility.ToJson(e.Notification)}"); _log($"Notification was clicked with Result: {JsonUtility.ToJson(e.Result)}"); } - private void _notificationOnDisplay(object sender, NotificationWillDisplayEventArgs e) { - var additionalData = e.Notification.AdditionalData != null - ? Json.Serialize(e.Notification.AdditionalData) + private void _notificationOnDisplay(object sender, NotificationWillDisplayEventArgs e) + { + var additionalData = + e.Notification.AdditionalData != null + ? Json.Serialize(e.Notification.AdditionalData) : null; - _log($"Notification was received in foreground: {JsonUtility.ToJson(e.Notification)}\n{additionalData}"); - + _log( + $"Notification was received in foreground: {JsonUtility.ToJson(e.Notification)}\n{additionalData}" + ); + e.Notification.Display(); } - private void _notificationPermissionChanged(object sender, NotificationPermissionChangedEventArgs e) { + private void _notificationPermissionChanged( + object sender, + NotificationPermissionChangedEventArgs e + ) + { _log($"Notification Permission changed to: {e.Permission}"); } - private void _iamWillDisplay(object sender, InAppMessageWillDisplayEventArgs e) { + private void _iamWillDisplay(object sender, InAppMessageWillDisplayEventArgs e) + { _log($"IAM will display: {JsonUtility.ToJson(e.Message)}"); } - private void _iamDidDisplay(object sender, InAppMessageDidDisplayEventArgs e) { + private void _iamDidDisplay(object sender, InAppMessageDidDisplayEventArgs e) + { _log($"IAM did display: {JsonUtility.ToJson(e.Message)}"); } - private void _iamWillDismiss(object sender, InAppMessageWillDismissEventArgs e) { + private void _iamWillDismiss(object sender, InAppMessageWillDismissEventArgs e) + { _log($"IAM will dismiss: {JsonUtility.ToJson(e.Message)}"); } - private void _iamDidDismiss(object sender, InAppMessageDidDismissEventArgs e) { + private void _iamDidDismiss(object sender, InAppMessageDidDismissEventArgs e) + { _log($"IAM did dismiss: {JsonUtility.ToJson(e.Message)}"); } - private void _iamOnClick(object sender, InAppMessageClickEventArgs e) { + private void _iamOnClick(object sender, InAppMessageClickEventArgs e) + { _log($"IAM was clicked with Message: {JsonUtility.ToJson(e.Message)}"); _log($"IAM was clicked with Result: {JsonUtility.ToJson(e.Result)}"); _log($"IAM was clicked with Result UrlTarget: " + e.Result.UrlTarget.ToString()); } - private void _pushSubscriptionChanged(object sender, PushSubscriptionChangedEventArgs e) { + private void _pushSubscriptionChanged(object sender, PushSubscriptionChangedEventArgs e) + { _log($"Push subscription changed from previous: {JsonUtility.ToJson(e.State.Previous)}"); _log($"Push subscription changed to current: {JsonUtility.ToJson(e.State.Current)}"); } - private void _userStateChanged(object sender, UserStateChangedEventArgs e) { + private void _userStateChanged(object sender, UserStateChangedEventArgs e) + { _log($"OneSignalId changed : {e.State.Current.OneSignalId}"); _log($"ExternalId changed : {e.State.Current.ExternalId}"); } @@ -235,25 +253,29 @@ private void _userStateChanged(object sender, UserStateChangedEventArgs e) { * SDK setup */ - public void ToggleConsentRequired() { + public void ToggleConsentRequired() + { consentRequired = !consentRequired; _log($"Toggling ConsentRequired to {consentRequired}"); OneSignal.ConsentRequired = consentRequired; } - public void ToggleConsentGiven() { + public void ToggleConsentGiven() + { consentGiven = !consentGiven; _log($"Toggling ConsentGiven to {consentGiven}"); OneSignal.ConsentGiven = consentGiven; } - public void SetLogLevel() { + public void SetLogLevel() + { var newLevel = _nextEnum(OneSignal.Debug.LogLevel); _log($"Setting LogLevel to {newLevel}"); OneSignal.Debug.LogLevel = newLevel; } - public void SetAlertLevel() { + public void SetAlertLevel() + { var newLevel = _nextEnum(OneSignal.Debug.AlertLevel); _log($"Setting AlertLevel to {newLevel}"); OneSignal.Debug.AlertLevel = newLevel; @@ -263,67 +285,80 @@ public void SetAlertLevel() { * User identification */ - public void LoginOneSignalUser() { + public void LoginOneSignalUser() + { _log($"Logging in user ({externalId})"); OneSignal.Login(externalId); } - - public void LogoutOneSignalUser() { + + public void LogoutOneSignalUser() + { _log($"Logging out user"); OneSignal.Logout(); } - public void PushSubscriptionOptIn() { + public void PushSubscriptionOptIn() + { _log($"Opting in push subscription"); OneSignal.User.PushSubscription.OptIn(); } - public void PushSubscriptionOptOut() { + public void PushSubscriptionOptOut() + { _log($"Opting out push subscription"); OneSignal.User.PushSubscription.OptOut(); } - public void AddEmail() { + public void AddEmail() + { _log($"Adding email ({email})"); OneSignal.User.AddEmail(email); } - - public void RemoveEmail() { + + public void RemoveEmail() + { _log($"Removing email ({email})"); OneSignal.User.RemoveEmail(email); } - public void AddSms() { + public void AddSms() + { _log($"Adding sms ({phoneNumber})"); OneSignal.User.AddSms(phoneNumber); } - - public void RemoveSms() { + + public void RemoveSms() + { _log($"Removing sms ({phoneNumber})"); OneSignal.User.RemoveSms(phoneNumber); } - public void SetLanguage() { + public void SetLanguage() + { _log($"Setting language for the user to ({language})"); OneSignal.User.Language = language; } - public void AddAlias() { + public void AddAlias() + { _log($"Adding alias with label {aliasKey} and id {aliasValue}"); OneSignal.User.AddAlias(aliasKey, aliasValue); } - public void RemoveAlias() { + public void RemoveAlias() + { _log($"Removing alias with label {aliasKey}"); OneSignal.User.RemoveAlias(aliasKey); } - public void GetOneSignalId() { + public void GetOneSignalId() + { string onesignalId = OneSignal.User.OneSignalId ?? "null"; _log($"Get OneSignalId {onesignalId}"); } - public void GetExternalId() { + public void GetExternalId() + { string externalId = OneSignal.User.ExternalId ?? "null"; _log($"Get ExternalId {externalId}"); } @@ -332,8 +367,11 @@ public void GetExternalId() { * Push */ - public async void PromptForPush() { - _log($"Can request push notification permission: {OneSignal.Notifications.CanRequestPermission}"); + public async void PromptForPush() + { + _log( + $"Can request push notification permission: {OneSignal.Notifications.CanRequestPermission}" + ); _log("Opening permission prompt for push notifications and awaiting result..."); @@ -345,21 +383,24 @@ public async void PromptForPush() { _log("Notification permission denied"); } - public void ClearPush() { + public void ClearPush() + { _log("Clearing existing OneSignal push notifications"); - + OneSignal.Notifications.ClearAllNotifications(); - + _log("Notifications cleared"); } - public void GetNotificationsPermission() { + public void GetNotificationsPermission() + { var permission = OneSignal.Notifications.Permission; _log($"Notifications permission is: {permission}"); } - public void GetNotificationsPermissionNative() { + public void GetNotificationsPermissionNative() + { var permissionNative = OneSignal.Notifications.PermissionNative; _log($"Notifications native permission is: {permissionNative.ToString()}"); @@ -369,22 +410,26 @@ public void GetNotificationsPermissionNative() { * In-App Messages */ - public void AddTrigger() { + public void AddTrigger() + { _log($"Adding trigger with key {triggerKey} and value {triggerValue}"); OneSignal.InAppMessages.AddTrigger(triggerKey, triggerValue); } - public void RemoveTrigger() { + public void RemoveTrigger() + { _log($"Removing trigger for key {triggerKey}"); OneSignal.InAppMessages.RemoveTrigger(triggerKey); } - public void ClearTriggers() { + public void ClearTriggers() + { _log("Clearing all trigger keys and values from user"); OneSignal.InAppMessages.ClearTriggers(); } - public void TogglePauseInAppMessages() { + public void TogglePauseInAppMessages() + { _log($"Toggling Pausing InAppMessages to {!OneSignal.InAppMessages.Paused}"); OneSignal.InAppMessages.Paused = !OneSignal.InAppMessages.Paused; } @@ -393,21 +438,24 @@ public void TogglePauseInAppMessages() { * Tags */ - public void AddTag() { + public void AddTag() + { _log($"Adding tag with key {tagKey} and value {tagValue}"); OneSignal.User.AddTag(tagKey, tagValue); } - public void RemoveTag() { + public void RemoveTag() + { _log($"Removing tag for key {tagKey}"); OneSignal.User.RemoveTag(tagKey); - } - public void GetTags() { + public void GetTags() + { Dictionary dict = OneSignal.User.GetTags(); string dictionaryString = "{"; - foreach(KeyValuePair keyValues in dict) { + foreach (KeyValuePair keyValues in dict) + { dictionaryString += keyValues.Key + " : " + keyValues.Value + ", "; } _log($"Get all user tags " + dictionaryString.TrimEnd(',', ' ') + "}"); @@ -417,17 +465,20 @@ public void GetTags() { * Outcomes */ - public void AddOutcome() { + public void AddOutcome() + { _log($"Adding outcome with key {outcomeKey}"); OneSignal.Session.AddOutcome(outcomeKey); } - public void AddUniqueOutcome() { + public void AddUniqueOutcome() + { _log($"Adding unique outcome with key {outcomeKey}"); OneSignal.Session.AddUniqueOutcome(outcomeKey); } - public void AddOutcomeWithValue() { + public void AddOutcomeWithValue() + { _log($"Adding outcome with key {outcomeKey} and value {outcomeValue}"); OneSignal.Session.AddOutcomeWithValue(outcomeKey, outcomeValue); } @@ -436,12 +487,14 @@ public void AddOutcomeWithValue() { * Location */ - public void PromptLocation() { + public void PromptLocation() + { _log("Opening permission prompt for location"); OneSignal.Location.RequestPermission(); } - public void ToggleShareLocation() { + public void ToggleShareLocation() + { _log($"Toggling Location IsShared to {!OneSignal.Location.IsShared}"); OneSignal.Location.IsShared = !OneSignal.Location.IsShared; } @@ -450,26 +503,31 @@ public void ToggleShareLocation() { * iOS */ - public void StartDefaultLiveActivity() { + public void StartDefaultLiveActivity() + { _log($"Start Default Live Activity with id: {liveActivityId}..."); OneSignal.LiveActivities.StartDefault( liveActivityId, - new Dictionary() { - { "title", "Welcome!" } - }, - new Dictionary() { - { "message", new Dictionary() { - { "en", "Hello World!"} - }}, + new Dictionary() { { "title", "Welcome!" } }, + new Dictionary() + { + { + "message", + new Dictionary() { { "en", "Hello World!" } } + }, { "intValue", 3 }, { "doubleValue", 3.14 }, - { "boolValue", true } - }); + { "boolValue", true }, + } + ); } - public async void EnterLiveActivityAsync() { - _log($"Entering Live Activity with id: {liveActivityId} and token: {liveActivityIdToken} and awaiting result..."); + public async void EnterLiveActivityAsync() + { + _log( + $"Entering Live Activity with id: {liveActivityId} and token: {liveActivityIdToken} and awaiting result..." + ); var result = await OneSignal.LiveActivities.EnterAsync(liveActivityId, liveActivityIdToken); @@ -479,7 +537,8 @@ public async void EnterLiveActivityAsync() { _log("Live Activity enter failed"); } - public async void ExitLiveActivityAsync() { + public async void ExitLiveActivityAsync() + { _log($"Exiting Live Activity with id: {liveActivityId} and awaiting result..."); var result = await OneSignal.LiveActivities.ExitAsync(liveActivityId); @@ -490,19 +549,23 @@ public async void ExitLiveActivityAsync() { _log("Live Activity exit failed"); } - public void SetPushToStartToken() { - _log($"Set Push To Start Token for type: {liveActivityType} with token: {liveActivityTypeToken}..."); + public void SetPushToStartToken() + { + _log( + $"Set Push To Start Token for type: {liveActivityType} with token: {liveActivityTypeToken}..." + ); OneSignal.LiveActivities.SetPushToStartToken(liveActivityType, liveActivityTypeToken); } - public void RemovePushToStartToken() { + public void RemovePushToStartToken() + { _log($"Remove Push To Start Token for type: {liveActivityType}..."); OneSignal.LiveActivities.RemovePushToStartToken(liveActivityType); } -#region Rendering + #region Rendering /* * You can safely ignore everything in this region and below */ @@ -513,62 +576,77 @@ public void RemovePushToStartToken() { public void SetAppIdString(string newVal) => appId = newVal; public void SetExternalIdString(string newVal) => externalId = newVal; + public void SetEmailString(string newVal) => email = newVal; + public void SetPhoneNumberString(string newVal) => phoneNumber = newVal; + public void SetLanguageString(string newVal) => language = newVal; public void SetAliasKey(string newVal) => aliasKey = newVal; + public void SetAliasValue(string newVal) => aliasValue = newVal; public void SetTriggerKey(string newVal) => triggerKey = newVal; + public void SetTriggerValue(string newVal) => triggerValue = newVal; public void SetTagKey(string newVal) => tagKey = newVal; + public void SetTagValue(string newVal) => tagValue = newVal; public void SetOutcomeKey(string newVal) => outcomeKey = newVal; + public void SetOutcomeValue(string newVal) => outcomeValue = Convert.ToSingle(newVal); public void SetLiveActivityId(string newVal) => liveActivityId = newVal; + public void SetLiveActivityIdToken(string newVal) => liveActivityIdToken = newVal; public void SetLiveActivityType(string newVal) => liveActivityType = newVal; + public void SetLiveActivityTypeToken(string newVal) => liveActivityTypeToken = newVal; - private void Awake() { - SDKDebug.LogIntercept += _log; - SDKDebug.WarnIntercept += _warn; + private void Awake() + { + SDKDebug.LogIntercept += _log; + SDKDebug.WarnIntercept += _warn; SDKDebug.ErrorIntercept += _error; appIdText.text = appId; } - private void _log(object message) { + private void _log(object message) + { string green = "#3BB674"; UnityEngine.Debug.Log(message); console.text += $"\nI> {message}"; } - private void _warn(object message) { + private void _warn(object message) + { string yellow = "#FFA940"; UnityEngine.Debug.LogWarning(message); console.text += $"\nW> {message}"; } - private void _error(object message) { + private void _error(object message) + { string red = "#E54B4D"; UnityEngine.Debug.LogError(message); console.text += $"\nE> {message}"; } -#endregion + #endregion -#region Helpers - private static T _nextEnum(T src) where T : struct { + #region Helpers + private static T _nextEnum(T src) + where T : struct + { if (!typeof(T).IsEnum) throw new ArgumentException($"Argument {typeof(T).FullName} is not an Enum"); var vals = (T[])Enum.GetValues(src.GetType()); var next = Array.IndexOf(vals, src) + 1; return vals.Length == next ? vals[0] : vals[next]; } -#endregion + #endregion } -#endif \ No newline at end of file +#endif From 72c4c92c29c50fb8da58d7141bad948bf46076a9 Mon Sep 17 00:00:00 2001 From: Fadi George Date: Wed, 8 Oct 2025 14:30:04 -0700 Subject: [PATCH 2/3] add csharperignore --- .csharpierignore | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .csharpierignore diff --git a/.csharpierignore b/.csharpierignore new file mode 100644 index 000000000..d0f9d4c20 --- /dev/null +++ b/.csharpierignore @@ -0,0 +1,2 @@ +# Exclude Packages folders (Unity packages and third-party code) +**/Packages/** \ No newline at end of file From edb99b18de94e7cc34608f474347992bbb3cb3cd Mon Sep 17 00:00:00 2001 From: Fadi George Date: Wed, 8 Oct 2025 14:30:08 -0700 Subject: [PATCH 3/3] format files --- .../App/Editor/iOS/BuildPostProcessor.cs | 86 ++++-- .../Attribution/OneSignalVSAttribution.cs | 26 +- .../OneSignal/Attribution/VSAttribution.cs | 119 ++++---- .../Assets/OneSignal/Editor/AssemblyInfo.cs | 2 +- .../OneSignal/Editor/OneSignalBootstrapper.cs | 30 +- .../Editor/OneSignalFileInventory.cs | 23 +- .../Editor/PackageManagement/Dependency.cs | 19 +- .../Editor/PackageManagement/Manifest.cs | 88 ++++-- .../Editor/PackageManagement/ScopeRegistry.cs | 54 ++-- .../Editor/Setup/OneSignalSetupStep.cs | 19 +- .../Editor/Setup/OneSignalSetupWindow.cs | 67 +++-- .../Editor/SetupSteps/CleanUpLegacyStep.cs | 33 ++- .../Editor/SetupSteps/ImportPackagesStep.cs | 82 +++--- .../OneSignal/Editor/Utilities/MiniJSON.cs | 95 +++--- .../Editor/Utilities/ReflectionHelpers.cs | 25 +- OneSignalExample/Assets/OneSignal/link.xml | 8 +- .../Editor/OneSignalFileInventoryGenerator.cs | 11 +- .../Editor/OneSignalPackagePublisher.cs | 27 +- .../Editor/OneSignalSetupReset.cs | 19 +- .../Plugins/Android/AndroidManifest.xml | 38 +-- .../AndroidManifest.xml | 12 +- .../AndroidResolverDependencies.xml | 2 +- .../ProjectSettings/GvhProjectSettings.xml | 7 +- .../Migration/MigrateAndroidResources.cs | 16 +- .../Editor/OneSignalAndroidDependencies.xml | 2 +- .../AndroidManifest.xml | 12 +- .../SetupSteps/ExportAndroidResourcesStep.cs | 123 +++++--- .../Runtime/AndroidDebugManager.cs | 34 ++- .../Runtime/AndroidDisplayableNotification.cs | 13 +- .../Runtime/AndroidInAppMessagesManager.cs | 90 +++--- .../Runtime/AndroidLiveActivitiesManager.cs | 26 +- .../Runtime/AndroidLocationManager.cs | 23 +- .../Runtime/AndroidNotificationsManager.cs | 142 ++++++--- .../Runtime/AndroidPushSubscription.cs | 57 ++-- .../Runtime/AndroidSessionManager.cs | 25 +- .../Runtime/AndroidUserManager.cs | 99 ++++--- .../Runtime/AssemblyInfo.cs | 2 +- .../Runtime/OneSignalAndroid.cs | 96 +++--- .../Utilities/AndroidJavaObjectExtensions.cs | 94 ++++-- .../Runtime/Utilities/AndroidJavaProxy.cs | 67 +++-- .../Utilities/AwaitableAndroidJavaProxy.cs | 66 +++-- .../Editor/Platform/DebugManager.cs | 8 +- .../Editor/Platform/InAppMessagesManager.cs | 28 +- .../Editor/Platform/LiveActivitiesManager.cs | 38 ++- .../Editor/Platform/LocationManager.cs | 12 +- .../Editor/Platform/NotificationsManager.cs | 15 +- .../Editor/Platform/OneSignalNative.cs | 65 ++-- .../Editor/Platform/PushSubscription.cs | 18 +- .../Editor/Platform/SessionManager.cs | 20 +- .../Editor/Platform/UserManager.cs | 75 ++--- .../Editor/Setup/OneSignalSetupStep.cs | 19 +- .../Editor/Setup/OneSignalSetupWindow.cs | 67 +++-- .../Editor/SetupSteps/InstallEdm4uStep.cs | 81 +++-- .../Editor/SetupSteps/LinkXMLStep.cs | 67 +++-- .../Editor/SetupSteps/SyncCodeBundleStep.cs | 73 +++-- .../Editor/Utilities/EditorWebRequest.cs | 45 ++- .../Editor/Utilities/UnityPackageInstaller.cs | 43 ++- com.onesignal.unity.core/Editor/link.xml | 8 +- .../Runtime/Behaviors/OneSignalBehaviour.cs | 23 +- .../Runtime/Debug/IDebugManager.cs | 12 +- .../Runtime/Debug/Models/LogLevel.cs | 24 +- .../Runtime/Debug/Utilities/SDKDebug.cs | 23 +- .../InAppMessages/IInAppMessagesManager.cs | 23 +- .../InAppMessages/Internal/InAppMessage.cs | 16 +- .../Internal/InAppMessageAction.cs | 19 +- .../Internal/InAppMessageClickResult.cs | 30 +- .../InAppMessages/Models/IInAppMessage.cs | 8 +- .../Models/IInAppMessageAction.cs | 8 +- .../Models/IInAppMessageClickResult.cs | 8 +- .../Models/InAppMessageActionUrlType.cs | 19 +- .../LiveActivities/ILiveActivitiesManager.cs | 22 +- .../LiveActivitiesSetupOptions.cs | 5 +- .../Runtime/Location/ILocationManager.cs | 8 +- .../Notifications/INotificationsManager.cs | 26 +- .../Notifications/Internal/Notification.cs | 144 ++++----- .../Internal/NotificationClickResult.cs | 20 +- .../Models/IDisplayableNotification.cs | 6 +- .../Notifications/Models/INotification.cs | 64 ++-- .../Models/INotificationClickResult.cs | 10 +- .../Models/NotificationPermission.cs | 18 +- .../Runtime/OneSignal.Internal.cs | 30 +- com.onesignal.unity.core/Runtime/OneSignal.cs | 97 +++--- .../Runtime/OneSignalPlatform.cs | 36 ++- .../Runtime/Session/ISessionManager.cs | 8 +- .../Runtime/User/IUserManager.cs | 17 +- .../User/Internal/PushSubscriptionState.cs | 24 +- .../Runtime/User/Internal/UserState.cs | 16 +- .../Runtime/User/Models/IPushSubscription.cs | 11 +- .../User/Models/IPushSubscriptionState.cs | 12 +- .../Runtime/User/Models/IUserState.cs | 10 +- .../Models/PushSubscriptionChangedState.cs | 14 +- .../Runtime/User/Models/UserChangedState.cs | 11 +- .../Runtime/Utilities/MiniJSON.cs | 95 +++--- .../Runtime/Utilities/ReflectionHelpers.cs | 25 +- .../Utilities/UnityMainThreadDispatch.cs | 8 +- .../Samples~/OneSignalExampleBehaviour.cs | 278 +++++++++++------- .../Editor/BuildPostProcessor.cs | 186 ++++++++---- .../Editor/OneSignaliOSDependencies.xml | 8 +- .../Editor/PBXProjectExtensions.cs | 31 +- .../Runtime/AssemblyInfo.cs | 2 +- .../Runtime/OneSignaliOS.cs | 125 +++++--- .../Runtime/Utilities/Later.cs | 30 +- .../Runtime/Utilities/WaitingProxy.cs | 25 +- .../Runtime/iOSDebugManager.cs | 33 ++- .../Runtime/iOSDisplayableNotification.cs | 16 +- .../Runtime/iOSInAppMessagesManager.cs | 123 +++++--- .../Runtime/iOSLiveActivitiesManager.cs | 83 ++++-- .../Runtime/iOSLocationManager.cs | 29 +- .../Runtime/iOSNotificationsManager.cs | 157 +++++++--- .../Runtime/iOSPushSubscription.cs | 62 ++-- .../Runtime/iOSSessionManager.cs | 33 ++- .../Runtime/iOSUserManager.cs | 154 ++++++---- 112 files changed, 3017 insertions(+), 1869 deletions(-) diff --git a/OneSignalExample/Assets/App/Editor/iOS/BuildPostProcessor.cs b/OneSignalExample/Assets/App/Editor/iOS/BuildPostProcessor.cs index fd90164d4..87662db2c 100644 --- a/OneSignalExample/Assets/App/Editor/iOS/BuildPostProcessor.cs +++ b/OneSignalExample/Assets/App/Editor/iOS/BuildPostProcessor.cs @@ -35,17 +35,23 @@ using System.IO; using System.Linq; -namespace App.Editor.iOS { +namespace App.Editor.iOS +{ /// /// Adds the ExampleWidgetExtension to the iOS project frameworks to the iOS project and enables the main target /// for Live Activities. /// - public class BuildPostProcessor : IPostprocessBuildWithReport { - + public class BuildPostProcessor : IPostprocessBuildWithReport + { private static readonly string WdigetExtensionTargetRelativePath = "ExampleWidget"; private static readonly string WidgetExtensionTargetName = "ExampleWidgetExtension"; private static readonly string WidgetExtensionPath = Path.Combine("iOS", "ExampleWidget"); - private static readonly string[] WidgetExtensionFiles = new string[] { "Assets.xcassets", "ExampleWidgetBundle.swift", "ExampleWidgetLiveActivity.swift" }; + private static readonly string[] WidgetExtensionFiles = new string[] + { + "Assets.xcassets", + "ExampleWidgetBundle.swift", + "ExampleWidgetLiveActivity.swift", + }; /// /// must be between 40 and 50 to ensure that it's not overriden by Podfile generation (40) and that it's @@ -54,22 +60,32 @@ public class BuildPostProcessor : IPostprocessBuildWithReport { /// public int callbackOrder => 45; - public void OnPostprocessBuild(BuildReport report) { + public void OnPostprocessBuild(BuildReport report) + { if (report.summary.platform != BuildTarget.iOS) return; - Debug.Log("BuildPostProcessor.OnPostprocessBuild for target " + report.summary.platform + " at path " + report.summary.outputPath + " with CWD " + Directory.GetCurrentDirectory()); + Debug.Log( + "BuildPostProcessor.OnPostprocessBuild for target " + + report.summary.platform + + " at path " + + report.summary.outputPath + + " with CWD " + + Directory.GetCurrentDirectory() + ); EnableAppForLiveActivities(report.summary.outputPath); CreateWidgetExtension(report.summary.outputPath); - + Debug.Log("BuildPostProcessor.OnPostprocessBuild complete"); } - static void EnableAppForLiveActivities(string outputPath) { + static void EnableAppForLiveActivities(string outputPath) + { var plistPath = Path.Combine(outputPath, "Info.plist"); - if (!File.Exists(plistPath)) { + if (!File.Exists(plistPath)) + { Debug.LogError($"Could not find PList {plistPath}!"); return; } @@ -80,12 +96,14 @@ static void EnableAppForLiveActivities(string outputPath) { mainPlist.WriteToFile(plistPath); } - static void CreateWidgetExtension(string outputPath) { + static void CreateWidgetExtension(string outputPath) + { AddWidgetExtensionToProject(outputPath); AddWidgetExtensionToPodFile(outputPath); } - static void AddWidgetExtensionToProject(string outputPath) { + static void AddWidgetExtensionToProject(string outputPath) + { var project = new PBXProject(); var projectPath = PBXProject.GetPBXProjectPath(outputPath); project.ReadFromString(File.ReadAllText(projectPath)); @@ -99,9 +117,13 @@ static void AddWidgetExtensionToProject(string outputPath) { var widgetDestPath = Path.Combine(outputPath, WdigetExtensionTargetRelativePath); Directory.CreateDirectory(widgetDestPath); - CopyFileOrDirectory(Path.Combine(WidgetExtensionPath, "Info.plist"), Path.Combine(widgetDestPath, "Info.plist")); + CopyFileOrDirectory( + Path.Combine(WidgetExtensionPath, "Info.plist"), + Path.Combine(widgetDestPath, "Info.plist") + ); - extensionGuid = project.AddAppExtension(project.GetUnityMainTargetGuid(), + extensionGuid = project.AddAppExtension( + project.GetUnityMainTargetGuid(), WidgetExtensionTargetName, $"{PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS)}.{WidgetExtensionTargetName}", $"{WdigetExtensionTargetRelativePath}/Info.plist" @@ -109,11 +131,15 @@ static void AddWidgetExtensionToProject(string outputPath) { var buildPhaseID = project.AddSourcesBuildPhase(extensionGuid); - foreach (var file in WidgetExtensionFiles) { + foreach (var file in WidgetExtensionFiles) + { var destPathRelative = Path.Combine(WdigetExtensionTargetRelativePath, file); var sourceFileGuid = project.AddFile(destPathRelative, destPathRelative); project.AddFileToBuildSection(extensionGuid, buildPhaseID, sourceFileGuid); - CopyFileOrDirectory(Path.Combine(WidgetExtensionPath, file), Path.Combine(outputPath, destPathRelative)); + CopyFileOrDirectory( + Path.Combine(WidgetExtensionPath, file), + Path.Combine(outputPath, destPathRelative) + ); } project.SetBuildProperty(extensionGuid, "TARGETED_DEVICE_FAMILY", "1,2"); @@ -123,16 +149,19 @@ static void AddWidgetExtensionToProject(string outputPath) { project.WriteToFile(projectPath); } - static void AddWidgetExtensionToPodFile(string outputPath) { + static void AddWidgetExtensionToPodFile(string outputPath) + { var podfilePath = Path.Combine(outputPath, "Podfile"); - if (!File.Exists(podfilePath)) { + if (!File.Exists(podfilePath)) + { Debug.LogError($"Could not find Podfile {podfilePath}!"); return; } var podfile = File.ReadAllText(podfilePath); - podfile += $"target '{WidgetExtensionTargetName}' do\n pod 'OneSignalXCFramework', '>= 5.0.2', '< 6.0.0'\nend\n"; + podfile += + $"target '{WidgetExtensionTargetName}' do\n pod 'OneSignalXCFramework', '>= 5.0.2', '< 6.0.0'\nend\n"; File.WriteAllText(podfilePath, podfile); } @@ -150,20 +179,29 @@ static void CopyFileOrDirectory(string sourcePath, string destinationPath) { file.CopyTo(destinationPath, true); } - else { - Directory.CreateDirectory(destinationPath); + else + { + Directory.CreateDirectory(destinationPath); - foreach (FileInfo childFile in dir.EnumerateFiles().Where(f => !f.Name.EndsWith(".meta"))) + foreach ( + FileInfo childFile in dir.EnumerateFiles().Where(f => !f.Name.EndsWith(".meta")) + ) { - CopyFileOrDirectory(childFile.FullName, Path.Combine(destinationPath, childFile.Name)); + CopyFileOrDirectory( + childFile.FullName, + Path.Combine(destinationPath, childFile.Name) + ); } foreach (DirectoryInfo subDir in dir.GetDirectories()) { - CopyFileOrDirectory(subDir.FullName, Path.Combine(destinationPath, subDir.Name)); + CopyFileOrDirectory( + subDir.FullName, + Path.Combine(destinationPath, subDir.Name) + ); } } } } } -#endif \ No newline at end of file +#endif diff --git a/OneSignalExample/Assets/OneSignal/Attribution/OneSignalVSAttribution.cs b/OneSignalExample/Assets/OneSignal/Attribution/OneSignalVSAttribution.cs index 72c6b5c20..b810d2857 100644 --- a/OneSignalExample/Assets/OneSignal/Attribution/OneSignalVSAttribution.cs +++ b/OneSignalExample/Assets/OneSignal/Attribution/OneSignalVSAttribution.cs @@ -25,19 +25,23 @@ * THE SOFTWARE. */ -using UnityEngine; using UnityEditor.VSAttribution.OneSignalSDK; +using UnityEngine; namespace OneSignalSDK { - internal static class AttachToInit { - #if ONE_SIGNAL_INSTALLED - [RuntimeInitializeOnLoadMethod] public static void Init() { - if (string.IsNullOrEmpty(OneSignalPlatform.AppId)) - OneSignalPlatform.OnInitialize += appId => VSAttribution.SendAttributionEvent("Login", "OneSignal", appId); - else - VSAttribution.SendAttributionEvent("Login", "OneSignal", OneSignalPlatform.AppId); - } - #endif + internal static class AttachToInit + { +#if ONE_SIGNAL_INSTALLED + [RuntimeInitializeOnLoadMethod] + public static void Init() + { + if (string.IsNullOrEmpty(OneSignalPlatform.AppId)) + OneSignalPlatform.OnInitialize += appId => + VSAttribution.SendAttributionEvent("Login", "OneSignal", appId); + else + VSAttribution.SendAttributionEvent("Login", "OneSignal", OneSignalPlatform.AppId); + } +#endif } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/Attribution/VSAttribution.cs b/OneSignalExample/Assets/OneSignal/Attribution/VSAttribution.cs index 983db0fc1..190b56ce3 100644 --- a/OneSignalExample/Assets/OneSignal/Attribution/VSAttribution.cs +++ b/OneSignalExample/Assets/OneSignal/Attribution/VSAttribution.cs @@ -3,66 +3,75 @@ namespace UnityEditor.VSAttribution.OneSignalSDK { - public static class VSAttribution - { - const int k_VersionId = 4; - const int k_MaxEventsPerHour = 10; - const int k_MaxNumberOfElements = 1000; + public static class VSAttribution + { + const int k_VersionId = 4; + const int k_MaxEventsPerHour = 10; + const int k_MaxNumberOfElements = 1000; - const string k_VendorKey = "unity.vsp-attribution"; - const string k_EventName = "vspAttribution"; + const string k_VendorKey = "unity.vsp-attribution"; + const string k_EventName = "vspAttribution"; - static bool RegisterEvent() - { - AnalyticsResult result = EditorAnalytics.RegisterEventWithLimit(k_EventName, k_MaxEventsPerHour, - k_MaxNumberOfElements, k_VendorKey, k_VersionId); + static bool RegisterEvent() + { + AnalyticsResult result = EditorAnalytics.RegisterEventWithLimit( + k_EventName, + k_MaxEventsPerHour, + k_MaxNumberOfElements, + k_VendorKey, + k_VersionId + ); - var isResultOk = result == AnalyticsResult.Ok; - return isResultOk; - } + var isResultOk = result == AnalyticsResult.Ok; + return isResultOk; + } - [Serializable] - struct VSAttributionData - { - public string actionName; - public string partnerName; - public string customerUid; - public string extra; - } + [Serializable] + struct VSAttributionData + { + public string actionName; + public string partnerName; + public string customerUid; + public string extra; + } - /// - /// Registers and attempts to send a Verified Solutions Attribution event. - /// - /// Name of the action, identifying a place this event was called from. - /// Identifiable Verified Solutions Partner's name. - /// Unique identifier of the customer using Partner's Verified Solution. - public static AnalyticsResult SendAttributionEvent(string actionName, string partnerName, string customerUid) - { - try - { - // Are Editor Analytics enabled ? (Preferences) - if (!EditorAnalytics.enabled) - return AnalyticsResult.AnalyticsDisabled; + /// + /// Registers and attempts to send a Verified Solutions Attribution event. + /// + /// Name of the action, identifying a place this event was called from. + /// Identifiable Verified Solutions Partner's name. + /// Unique identifier of the customer using Partner's Verified Solution. + public static AnalyticsResult SendAttributionEvent( + string actionName, + string partnerName, + string customerUid + ) + { + try + { + // Are Editor Analytics enabled ? (Preferences) + if (!EditorAnalytics.enabled) + return AnalyticsResult.AnalyticsDisabled; - if (!RegisterEvent()) - return AnalyticsResult.InvalidData; + if (!RegisterEvent()) + return AnalyticsResult.InvalidData; - // Create an expected data object - var eventData = new VSAttributionData - { - actionName = actionName, - partnerName = partnerName, - customerUid = customerUid, - extra = "{}" - }; + // Create an expected data object + var eventData = new VSAttributionData + { + actionName = actionName, + partnerName = partnerName, + customerUid = customerUid, + extra = "{}", + }; - return EditorAnalytics.SendEventWithLimit(k_EventName, eventData, k_VersionId); - } - catch - { - // Fail silently - return AnalyticsResult.AnalyticsDisabled; - } - } - } -} \ No newline at end of file + return EditorAnalytics.SendEventWithLimit(k_EventName, eventData, k_VersionId); + } + catch + { + // Fail silently + return AnalyticsResult.AnalyticsDisabled; + } + } + } +} diff --git a/OneSignalExample/Assets/OneSignal/Editor/AssemblyInfo.cs b/OneSignalExample/Assets/OneSignal/Editor/AssemblyInfo.cs index 518b784b8..07e934721 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/AssemblyInfo.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/AssemblyInfo.cs @@ -27,4 +27,4 @@ using System.Runtime.CompilerServices; -[assembly: InternalsVisibleTo("OneSignal.Packager")] \ No newline at end of file +[assembly: InternalsVisibleTo("OneSignal.Packager")] diff --git a/OneSignalExample/Assets/OneSignal/Editor/OneSignalBootstrapper.cs b/OneSignalExample/Assets/OneSignal/Editor/OneSignalBootstrapper.cs index 60b1063bc..240291528 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/OneSignalBootstrapper.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/OneSignalBootstrapper.cs @@ -28,15 +28,19 @@ using System.Linq; using UnityEditor; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Handles informing the user on startup/import if the legacy SDK has been detected /// - public static class OneSignalBootstrapper { + public static class OneSignalBootstrapper + { /// /// Asks to open the SDK Setup if legacy files are found or core is missing /// - [InitializeOnLoadMethod] public static void CheckForLegacy() { + [InitializeOnLoadMethod] + public static void CheckForLegacy() + { if (SessionState.GetBool(_sessionCheckKey, false)) return; @@ -45,24 +49,28 @@ [InitializeOnLoadMethod] public static void CheckForLegacy() { EditorApplication.delayCall += _checkForLegacy; } - private static void _checkForLegacy() { - #if !ONE_SIGNAL_INSTALLED + private static void _checkForLegacy() + { +#if !ONE_SIGNAL_INSTALLED EditorApplication.delayCall += _showOpenSetupDialog; - #else - var inventory = AssetDatabase.LoadAssetAtPath(OneSignalFileInventory.AssetPath); +#else + var inventory = AssetDatabase.LoadAssetAtPath( + OneSignalFileInventory.AssetPath + ); if (inventory == null) return; // error var currentPaths = OneSignalFileInventory.GetCurrentPaths(); - var diff = currentPaths.Except(inventory.DistributedPaths); + var diff = currentPaths.Except(inventory.DistributedPaths); if (diff.Any()) EditorApplication.delayCall += _showOpenSetupDialog; - #endif +#endif } - private static void _showOpenSetupDialog() { + private static void _showOpenSetupDialog() + { var dialogResult = EditorUtility.DisplayDialog( "OneSignal", "The project contains an outdated or incomplete install of OneSignal SDK! We recommend running the OneSignal SDK Setup.", @@ -76,4 +84,4 @@ private static void _showOpenSetupDialog() { private const string _sessionCheckKey = "onesignal.bootstrapper.check"; } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/Editor/OneSignalFileInventory.cs b/OneSignalExample/Assets/OneSignal/Editor/OneSignalFileInventory.cs index 09c729220..578cf5853 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/OneSignalFileInventory.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/OneSignalFileInventory.cs @@ -29,11 +29,13 @@ using System.Linq; using UnityEngine; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Inventory distributed with the *.unitypackage in order to determine if there are any legacy files in need of removal /// - internal sealed class OneSignalFileInventory : ScriptableObject { + internal sealed class OneSignalFileInventory : ScriptableObject + { /// /// Array of paths within the OneSignal directory which were determined to be part of the distributed unitypackage /// @@ -42,8 +44,10 @@ internal sealed class OneSignalFileInventory : ScriptableObject { /// /// Array of current paths within the OneSignal directory /// - public static string[] GetCurrentPaths() - => ConvertPathsToUnix(Directory.GetFiles(PackageAssetsPath, "*", SearchOption.AllDirectories)); + public static string[] GetCurrentPaths() => + ConvertPathsToUnix( + Directory.GetFiles(PackageAssetsPath, "*", SearchOption.AllDirectories) + ); /// /// Makes sure are using forward slash to be Unix compatible. @@ -51,7 +55,8 @@ public static string[] GetCurrentPaths() /// /// the paths to check and convert /// paths with / as the directory separator - public static string[] ConvertPathsToUnix(string[] paths) { + public static string[] ConvertPathsToUnix(string[] paths) + { if (Path.DirectorySeparatorChar == Path.AltDirectorySeparatorChar) return paths; @@ -64,7 +69,11 @@ public static string[] ConvertPathsToUnix(string[] paths) { public const string AssetName = "OneSignalFileInventory.asset"; public static readonly string PackageAssetsPath = Path.Combine("Assets", "OneSignal"); - public static readonly string EditorResourcesPath = Path.Combine(PackageAssetsPath, "Editor", "Resources"); + public static readonly string EditorResourcesPath = Path.Combine( + PackageAssetsPath, + "Editor", + "Resources" + ); public static readonly string AssetPath = Path.Combine(EditorResourcesPath, AssetName); } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Dependency.cs b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Dependency.cs index 7339fad33..c85b4fb4d 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Dependency.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Dependency.cs @@ -27,11 +27,13 @@ using System.Collections.Generic; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Representation of the manifest file "dependency" entry. /// - public class Dependency { + public class Dependency + { /// /// The dependency name. /// @@ -47,8 +49,9 @@ public class Dependency { /// /// Dependency name. /// Dependency version. - public Dependency(string name, string version) { - Name = name; + public Dependency(string name, string version) + { + Name = name; Version = version; } @@ -56,7 +59,8 @@ public Dependency(string name, string version) { /// Sets new dependency version. /// /// The version to be set for this dependency - public void SetVersion(string version) { + public void SetVersion(string version) + { Version = version; } @@ -64,11 +68,12 @@ public void SetVersion(string version) { /// Creates a dictionary from this object. /// /// Dependency object representation as Dictionary<string, object>. - public Dictionary ToDictionary() { + public Dictionary ToDictionary() + { Dictionary result = new Dictionary(); result.Add(Name, Version); return result; } } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Manifest.cs b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Manifest.cs index 14d4d43e6..fcbccbff4 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Manifest.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Manifest.cs @@ -29,12 +29,14 @@ using System.IO; using OneSignalSDK.Installer; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Representation of Manifest JSON file. /// Can be used for adding dependencies, scopeRegistries, etc to .json file /// - public class Manifest { + public class Manifest + { const string k_ProjectManifestPath = "Packages/manifest.json"; const string k_DependenciesKey = "dependencies"; const string k_ScopedRegistriesKey = "scopedRegistries"; @@ -53,33 +55,44 @@ public class Manifest { /// Initializes a new instance of the class. /// /// Path to manifest file. - public Manifest(string pathToFile = k_ProjectManifestPath) { - Path = pathToFile; + public Manifest(string pathToFile = k_ProjectManifestPath) + { + Path = pathToFile; m_ScopeRegistries = new Dictionary(); - m_Dependencies = new Dictionary(); + m_Dependencies = new Dictionary(); } /// /// Read the Manifest file and deserialize its content from JSON. /// - public void Fetch() { + public void Fetch() + { var manifestText = File.ReadAllText(Path); m_RawContent = (Dictionary)Json.Deserialize(manifestText); - if (m_RawContent.TryGetValue(k_ScopedRegistriesKey, out var registriesBlob)) { - if (registriesBlob is List registries) { - foreach (var registry in registries) { - var registryDict = (Dictionary)registry; + if (m_RawContent.TryGetValue(k_ScopedRegistriesKey, out var registriesBlob)) + { + if (registriesBlob is List registries) + { + foreach (var registry in registries) + { + var registryDict = (Dictionary)registry; var scopeRegistry = new ScopeRegistry(registryDict); m_ScopeRegistries.Add(scopeRegistry.Url, scopeRegistry); } } } - if (m_RawContent.TryGetValue(k_DependenciesKey, out var dependenciesBlob)) { - if (dependenciesBlob is Dictionary dependencies) { - foreach (var dependencyData in dependencies) { - var dependency = new Dependency(dependencyData.Key, dependencyData.Value.ToString()); + if (m_RawContent.TryGetValue(k_DependenciesKey, out var dependenciesBlob)) + { + if (dependenciesBlob is Dictionary dependencies) + { + foreach (var dependencyData in dependencies) + { + var dependency = new Dependency( + dependencyData.Key, + dependencyData.Value.ToString() + ); m_Dependencies.Add(dependency.Name, dependency); } } @@ -91,7 +104,8 @@ public void Fetch() { /// /// Name of the dependency. /// Dependency with given name. - public Dependency GetDependency(string name) { + public Dependency GetDependency(string name) + { return m_Dependencies[name]; } @@ -100,7 +114,8 @@ public Dependency GetDependency(string name) { /// /// Scope registry url. /// Scope registry with the given url. - public ScopeRegistry GetScopeRegistry(string url) { + public ScopeRegistry GetScopeRegistry(string url) + { return m_ScopeRegistries[url]; } @@ -108,8 +123,10 @@ public ScopeRegistry GetScopeRegistry(string url) { /// Adds scope registry. /// /// An entry to add. - public void AddScopeRegistry(ScopeRegistry registry) { - if (!IsRegistryPresent(registry.Url)) { + public void AddScopeRegistry(ScopeRegistry registry) + { + if (!IsRegistryPresent(registry.Url)) + { m_ScopeRegistries.Add(registry.Url, registry); } } @@ -118,8 +135,10 @@ public void AddScopeRegistry(ScopeRegistry registry) { /// Removes a scope registry /// /// - public void RemoveScopeRegistry(string url) { - if (IsRegistryPresent(url)) { + public void RemoveScopeRegistry(string url) + { + if (IsRegistryPresent(url)) + { m_ScopeRegistries.Remove(url); } } @@ -129,8 +148,10 @@ public void RemoveScopeRegistry(string url) { /// /// Dependency name. /// Dependency version. - public void AddDependency(string name, string version) { - if (!IsDependencyPresent(name)) { + public void AddDependency(string name, string version) + { + if (!IsDependencyPresent(name)) + { var dependency = new Dependency(name, version); m_Dependencies.Add(dependency.Name, dependency); } @@ -140,8 +161,10 @@ public void AddDependency(string name, string version) { /// Removes a dependency /// /// - public void RemoveDependency(string name) { - if (IsDependencyPresent(name)) { + public void RemoveDependency(string name) + { + if (IsDependencyPresent(name)) + { m_Dependencies.Remove(name); } } @@ -149,10 +172,12 @@ public void RemoveDependency(string name) { /// /// Writes changes back to the manifest file. /// - public void ApplyChanges() { + public void ApplyChanges() + { var registries = new List(); - foreach (var registry in m_ScopeRegistries.Values) { + foreach (var registry in m_ScopeRegistries.Values) + { registries.Add(registry.ToDictionary()); } @@ -165,7 +190,8 @@ public void ApplyChanges() { Dictionary dependencies = new Dictionary(); - foreach (var dependency in m_Dependencies.Values) { + foreach (var dependency in m_Dependencies.Values) + { dependencies.Add(dependency.Name, dependency.Version); } @@ -180,7 +206,8 @@ public void ApplyChanges() { /// /// ScopeRegistry url to search for. /// `true` if scoped registry found, `false` otherwise. - public bool IsRegistryPresent(string url) { + public bool IsRegistryPresent(string url) + { return m_ScopeRegistries.ContainsKey(url); } @@ -189,8 +216,9 @@ public bool IsRegistryPresent(string url) { /// /// The dependency name to search for. /// `true` if found, `false` otherwise. - public bool IsDependencyPresent(string name) { + public bool IsDependencyPresent(string name) + { return m_Dependencies.ContainsKey(name); } } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs index 7bdfd7fae..eda4e1ac0 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs @@ -28,11 +28,13 @@ using System.Collections.Generic; using System.Linq; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Representation of "scopeRegistries" entry of the manifest file. /// - public class ScopeRegistry { + public class ScopeRegistry + { const string k_KeyName = "name"; const string k_KeyUrl = "url"; const string k_KeyScopes = "scopes"; @@ -58,9 +60,10 @@ public class ScopeRegistry { /// Name of new scope registry. /// Url of new scope registry. /// Scopes of new scope registry. - public ScopeRegistry(string name, string url, HashSet scopes) { - Name = name; - Url = url; + public ScopeRegistry(string name, string url, HashSet scopes) + { + Name = name; + Url = url; Scopes = scopes; } @@ -69,13 +72,15 @@ public ScopeRegistry(string name, string url, HashSet scopes) { /// /// Data to fill this object. Must contain name, /// url and scopes. - public ScopeRegistry(Dictionary dictionary) { + public ScopeRegistry(Dictionary dictionary) + { Name = (string)dictionary[k_KeyName]; - Url = (string)dictionary[k_KeyUrl]; + Url = (string)dictionary[k_KeyUrl]; var scopes = (List)dictionary[k_KeyScopes]; Scopes = new HashSet(); - foreach (var scope in scopes) { + foreach (var scope in scopes) + { Scopes.Add((string)scope); } } @@ -85,7 +90,8 @@ public ScopeRegistry(Dictionary dictionary) { /// /// string scope to check if exists in this scope registry. /// 'true' if this ScopeRegistry contains scope, `false` otherwise. - public bool HasScope(string scope) { + public bool HasScope(string scope) + { return Scopes.Contains(scope); } @@ -93,7 +99,8 @@ public bool HasScope(string scope) { /// Adds scope. /// /// A scope to add. - public void AddScope(string scope) { + public void AddScope(string scope) + { if (!HasScope(scope)) Scopes.Add(scope); } @@ -102,13 +109,16 @@ public void AddScope(string scope) { /// Generates a hash of this object data, excluding Name. /// /// Hash of this object. - public override int GetHashCode() { + public override int GetHashCode() + { int hash = 0; if (!string.IsNullOrEmpty(Url)) hash ^= Url.GetHashCode(); - if (Scopes != null) { - foreach (var scope in Scopes) { + if (Scopes != null) + { + foreach (var scope in Scopes) + { hash ^= scope.GetHashCode(); } } @@ -121,19 +131,21 @@ public override int GetHashCode() { /// /// Object to compare with. /// 'true' if url and scopes match, 'false' otherwise. - public override bool Equals(object obj) { - return obj is ScopeRegistry other && - Url == other.Url && - Scopes != null && - other.Scopes != null && - new HashSet(Scopes).SetEquals(other.Scopes); + public override bool Equals(object obj) + { + return obj is ScopeRegistry other + && Url == other.Url + && Scopes != null + && other.Scopes != null + && new HashSet(Scopes).SetEquals(other.Scopes); } /// /// Creates dictionary from this object. /// /// ScopeRegistry object representation as Dictionary<string, object>. - public Dictionary ToDictionary() { + public Dictionary ToDictionary() + { Dictionary result = new Dictionary(); result.Add(k_KeyName, Name); result.Add(k_KeyUrl, Url); @@ -142,4 +154,4 @@ public Dictionary ToDictionary() { return result; } } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupStep.cs b/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupStep.cs index 83fab505d..c2d863954 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupStep.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupStep.cs @@ -26,11 +26,13 @@ * THE SOFTWARE. */ -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Abstract class which must be inherited from in order to create a new setup step /// - public abstract class OneSignalSetupStep { + public abstract class OneSignalSetupStep + { /// /// Short description of what this step will do /// @@ -52,12 +54,14 @@ public abstract class OneSignalSetupStep { /// /// The result is cached and only reset on run or specific other conditions /// - public bool IsStepCompleted { - get { + public bool IsStepCompleted + { + get + { if (!_shouldCheckForCompletion) return _isComplete; - _isComplete = _getIsStepCompleted(); + _isComplete = _getIsStepCompleted(); _shouldCheckForCompletion = false; return _isComplete; @@ -67,7 +71,8 @@ public bool IsStepCompleted { /// /// Runs all code necessary in order to fulfill the step /// - public void RunStep() { + public void RunStep() + { if (IsStepCompleted) return; @@ -82,4 +87,4 @@ public void RunStep() { protected bool _shouldCheckForCompletion = true; } } -#endif \ No newline at end of file +#endif diff --git a/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupWindow.cs b/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupWindow.cs index 3e6e95cff..3c0aba98c 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupWindow.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupWindow.cs @@ -32,18 +32,23 @@ using UnityEditor; using UnityEngine; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Pop up window which displays any additional required or optional setup steps by the SDK /// - public sealed class OneSignalSetupWindow : EditorWindow { - [MenuItem("Window/OneSignal SDK Setup")] public static void ShowWindow() { + public sealed class OneSignalSetupWindow : EditorWindow + { + [MenuItem("Window/OneSignal SDK Setup")] + public static void ShowWindow() + { var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); window.minSize = _minSize; window.Show(); } - public static void CloseWindow() { + public static void CloseWindow() + { var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); window.Close(); } @@ -51,7 +56,8 @@ public static void CloseWindow() { private static readonly Vector2 _minSize = new Vector2(300, 400); private const string _title = "OneSignal SDK Setup"; - private const string _description = "Additional steps required to get the OneSignal Unity SDK up and running"; + private const string _description = + "Additional steps required to get the OneSignal Unity SDK up and running"; private IReadOnlyList _setupSteps; private readonly Queue _stepsToRun = new Queue(); @@ -67,21 +73,28 @@ public static void CloseWindow() { private Vector2 _scrollPosition; - private void OnEnable() { - var stepTypes = ReflectionHelpers.FindAllAssignableTypes("OneSignal"); - var steps = new List(); + private void OnEnable() + { + var stepTypes = ReflectionHelpers.FindAllAssignableTypes( + "OneSignal" + ); + var steps = new List(); - foreach (var stepType in stepTypes) { + foreach (var stepType in stepTypes) + { if (Activator.CreateInstance(stepType) is OneSignalSetupStep step) steps.Add(step); else - UnityEngine.Debug.LogWarning($"could not create setup step from type {stepType.Name}"); + UnityEngine.Debug.LogWarning( + $"could not create setup step from type {stepType.Name}" + ); } _setupSteps = steps; } - private void OnGUI() { + private void OnGUI() + { _setupGUI(); GUILayout.Label(_description); @@ -90,13 +103,15 @@ private void OnGUI() { if (_setupSteps == null) return; - var willDisableControls = _stepsToRun.Count > 0 + var willDisableControls = + _stepsToRun.Count > 0 || EditorApplication.isUpdating || EditorApplication.isCompiling; EditorGUI.BeginDisabledGroup(willDisableControls); - if (GUILayout.Button("Run All Steps")) { + if (GUILayout.Button("Run All Steps")) + { foreach (var step in _setupSteps) _stepsToRun.Enqueue(step); } @@ -109,11 +124,12 @@ private void OnGUI() { EditorGUILayout.BeginHorizontal(); _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); - foreach (var step in _setupSteps) { + foreach (var step in _setupSteps) + { EditorGUILayout.BeginHorizontal(); var sumContent = new GUIContent(step.Summary); - var sumRect = GUILayoutUtility.GetRect(sumContent, _summaryStyle); + var sumRect = GUILayoutUtility.GetRect(sumContent, _summaryStyle); var checkRect = new Rect(sumRect.x, sumRect.y, sumRect.height, sumRect.height); GUI.DrawTexture(checkRect, step.IsStepCompleted ? _checkTexture : _boxTexture); @@ -144,10 +160,12 @@ private void OnGUI() { EditorGUILayout.EndHorizontal(); } - private void OnInspectorUpdate() { + private void OnInspectorUpdate() + { var runnerCount = _stepsToRun.Count + 1.0f; - while (_stepsToRun.Count > 0) { + while (_stepsToRun.Count > 0) + { var step = _stepsToRun.Dequeue(); EditorUtility.DisplayProgressBar( @@ -162,24 +180,25 @@ private void OnInspectorUpdate() { EditorUtility.ClearProgressBar(); } - private void _setupGUI() { + private void _setupGUI() + { if (_guiSetupComplete) return; _summaryStyle = EditorStyles.boldLabel; - _detailsStyle = new GUIStyle(GUI.skin.textField); + _detailsStyle = new GUIStyle(GUI.skin.textField); _detailsStyle.wordWrap = true; - _runStyle = new GUIStyle(GUI.skin.button); + _runStyle = new GUIStyle(GUI.skin.button); _runStyle.fixedWidth = _minSize.x * .3f; - _requiredStyle = new GUIStyle(EditorStyles.miniBoldLabel); + _requiredStyle = new GUIStyle(EditorStyles.miniBoldLabel); _requiredStyle.normal.textColor = Color.red; - _optionalStyle = new GUIStyle(EditorStyles.miniBoldLabel); + _optionalStyle = new GUIStyle(EditorStyles.miniBoldLabel); _optionalStyle.normal.textColor = Color.yellow; - _optionalStyle.fontStyle = FontStyle.Italic; + _optionalStyle.fontStyle = FontStyle.Italic; var checkContent = EditorGUIUtility.IconContent("TestPassed"); _checkTexture = checkContent.image; @@ -191,4 +210,4 @@ private void _setupGUI() { } } } -#endif \ No newline at end of file +#endif diff --git a/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/CleanUpLegacyStep.cs b/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/CleanUpLegacyStep.cs index d75159e2c..63489d01d 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/CleanUpLegacyStep.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/CleanUpLegacyStep.cs @@ -30,23 +30,24 @@ using System.Linq; using UnityEditor; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Handles if there are files within the Assets/OneSignal folder which should not be there. Typically this /// indicates the presence of legacy files. /// - public sealed class CleanUpLegacyStep : OneSignalSetupStep { - public override string Summary - => "Remove legacy files"; + public sealed class CleanUpLegacyStep : OneSignalSetupStep + { + public override string Summary => "Remove legacy files"; - public override string Details - => "Checks for the diff between the files distributed with the package and those which are in the " + - OneSignalFileInventory.PackageAssetsPath; + public override string Details => + "Checks for the diff between the files distributed with the package and those which are in the " + + OneSignalFileInventory.PackageAssetsPath; - public override bool IsRequired - => true; + public override bool IsRequired => true; - protected override bool _getIsStepCompleted() { + protected override bool _getIsStepCompleted() + { var diff = _getDiff(); if (diff == null) @@ -55,7 +56,8 @@ protected override bool _getIsStepCompleted() { return !diff.Any(); } - protected override void _runStep() { + protected override void _runStep() + { var diff = _getDiff(); if (diff == null) @@ -65,9 +67,12 @@ protected override void _runStep() { File.Delete(path); } - private IEnumerable _getDiff() { + private IEnumerable _getDiff() + { if (_inventory == null) - _inventory = AssetDatabase.LoadAssetAtPath(OneSignalFileInventory.AssetPath); + _inventory = AssetDatabase.LoadAssetAtPath( + OneSignalFileInventory.AssetPath + ); if (_inventory == null) return null; // error @@ -79,4 +84,4 @@ private IEnumerable _getDiff() { private OneSignalFileInventory _inventory; } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/ImportPackagesStep.cs b/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/ImportPackagesStep.cs index c3b5a789a..463bc0a1d 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/ImportPackagesStep.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/ImportPackagesStep.cs @@ -30,28 +30,29 @@ using UnityEditor; using UnityEngine; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Checks for whether the OneSignal Unity Core package has been added to the project and does so if not /// - public sealed class ImportPackagesStep : OneSignalSetupStep { - public override string Summary - => "Import OneSignal packages"; + public sealed class ImportPackagesStep : OneSignalSetupStep + { + public override string Summary => "Import OneSignal packages"; - public override string Details - => "Add the OneSignal registry and core, ios, and android packages to the project manifest so they will be " + - "downloaded and imported"; + public override string Details => + "Add the OneSignal registry and core, ios, and android packages to the project manifest so they will be " + + "downloaded and imported"; - public override bool IsRequired - => true; + public override bool IsRequired => true; - #if ONE_SIGNAL_INSTALLED +#if ONE_SIGNAL_INSTALLED protected override bool _getIsStepCompleted() => true; - #else +#else protected override bool _getIsStepCompleted() => false; - #endif +#endif - protected override void _runStep() { + protected override void _runStep() + { var manifest = new Manifest(); manifest.Fetch(); @@ -60,39 +61,40 @@ protected override void _runStep() { var scopeRegistry = manifest.GetScopeRegistry(_registryUrl); scopeRegistry.AddScope(_packagesScope); - #if UNITY_2017_3_OR_NEWER - manifest.ApplyChanges(); - - var addRequest = UnityEditor.PackageManager.Client.Add(_coreVersion); - while (!addRequest.IsCompleted) { } - - addRequest = UnityEditor.PackageManager.Client.Add(_androidVersion); - while (!addRequest.IsCompleted) { } - - addRequest = UnityEditor.PackageManager.Client.Add(_iosVersion); - while (!addRequest.IsCompleted) { } +#if UNITY_2017_3_OR_NEWER + manifest.ApplyChanges(); + + var addRequest = UnityEditor.PackageManager.Client.Add(_coreVersion); + while (!addRequest.IsCompleted) { } + + addRequest = UnityEditor.PackageManager.Client.Add(_androidVersion); + while (!addRequest.IsCompleted) { } + + addRequest = UnityEditor.PackageManager.Client.Add(_iosVersion); + while (!addRequest.IsCompleted) { } #else - manifest.AddDependency(_corePackageName, _coreVersion); + manifest.AddDependency(_corePackageName, _coreVersion); manifest.AddDependency(_androidPackageName, _androidVersion); manifest.AddDependency(_iosPackageName, _iosVersion); manifest.ApplyChanges(); AssetDatabase.Refresh(); - #endif +#endif OneSignalSetupWindow.CloseWindow(); SessionState.SetBool(_shouldShowWindowKey, true); } - #if ONE_SIGNAL_INSTALLED - [InitializeOnLoadMethod] - public static void _showCoreInstallerWindow() { +#if ONE_SIGNAL_INSTALLED + [InitializeOnLoadMethod] + public static void _showCoreInstallerWindow() + { if (!SessionState.GetBool(_shouldShowWindowKey, false)) return; SessionState.EraseBool(_shouldShowWindowKey); EditorApplication.delayCall += OneSignalSetupWindow.ShowWindow; } - #endif +#endif private const string _shouldShowWindowKey = "onesignal.importpackage.shouldshow"; private const string _packagesScope = "com.onesignal"; @@ -101,14 +103,14 @@ public static void _showCoreInstallerWindow() { private static readonly string _androidPackageName = $"{_packagesScope}.unity.android"; private static readonly string _iosPackageName = $"{_packagesScope}.unity.ios"; - #if IS_ONESIGNAL_EXAMPLE_APP +#if IS_ONESIGNAL_EXAMPLE_APP private static readonly string _coreVersion = $"file:../../{_corePackageName}"; private static readonly string _androidVersion = $"file:../../{_androidPackageName}"; private static readonly string _iosVersion = $"file:../../{_iosPackageName}"; private const string _registryName = "npmjs"; private const string _registryUrl = "https://registry.npmjs.org"; - #else +#else private static string _coreVersion => $"{_corePackageName}@{_version}"; private static string _androidVersion => $"{_androidPackageName}@{_version}"; private static string _iosVersion => $"{_iosPackageName}@{_version}"; @@ -116,11 +118,19 @@ public static void _showCoreInstallerWindow() { private const string _registryName = "npmjs"; private const string _registryUrl = "https://registry.npmjs.org"; - private static readonly string _versionPath = Path.Combine("Assets", "OneSignal", "VERSION"); + private static readonly string _versionPath = Path.Combine( + "Assets", + "OneSignal", + "VERSION" + ); private static string _version => File.ReadAllText(_versionPath); - #endif +#endif private static readonly HashSet _scopes = new HashSet { _packagesScope }; - private static readonly ScopeRegistry _scopeRegistry = new ScopeRegistry(_registryName, _registryUrl, _scopes); + private static readonly ScopeRegistry _scopeRegistry = new ScopeRegistry( + _registryName, + _registryUrl, + _scopes + ); } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs b/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs index efd19f558..6f4b8d29d 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs @@ -33,7 +33,8 @@ using System.IO; using System.Text; -namespace OneSignalSDK.Installer { +namespace OneSignalSDK.Installer +{ // Forked from https://github.com/Jackyjjc/MiniJSON.cs // version: 6de00beb134bbab9d873033a48b32e4067ed0c25 @@ -117,7 +118,7 @@ enum TOKEN NUMBER, TRUE, FALSE, - NULL + NULL, }; StringReader json; @@ -304,7 +305,7 @@ string ParseString() hex[i] = NextChar; } - s.Append((char) Convert.ToInt32(new string(hex), 16)); + s.Append((char)Convert.ToInt32(new string(hex), 16)); break; default: s.Append(c); @@ -325,17 +326,29 @@ object ParseNumber() { string number = NextWord; - if (number.IndexOf('.') == -1 && number.IndexOf('E') == -1 && number.IndexOf('e') == -1) + if ( + number.IndexOf('.') == -1 + && number.IndexOf('E') == -1 + && number.IndexOf('e') == -1 + ) { long parsedInt; - Int64.TryParse(number, System.Globalization.NumberStyles.Any, - System.Globalization.CultureInfo.InvariantCulture, out parsedInt); + Int64.TryParse( + number, + System.Globalization.NumberStyles.Any, + System.Globalization.CultureInfo.InvariantCulture, + out parsedInt + ); return parsedInt; } double parsedDouble; - Double.TryParse(number, System.Globalization.NumberStyles.Any, - System.Globalization.CultureInfo.InvariantCulture, out parsedDouble); + Double.TryParse( + number, + System.Globalization.NumberStyles.Any, + System.Globalization.CultureInfo.InvariantCulture, + out parsedDouble + ); return parsedDouble; } @@ -449,9 +462,7 @@ TOKEN NextToken /// indentations. /// Number of spaces for each level of indentation. /// A JSON encoded string, or null if object 'json' is not serializable - public static string Serialize(object obj, - bool humanReadable = false, - int indentSpaces = 2) + public static string Serialize(object obj, bool humanReadable = false, int indentSpaces = 2) { return Serializer.MakeSerialization(obj, humanReadable, indentSpaces); } @@ -496,7 +507,7 @@ void SerializeValue(object value) } else if (value is bool) { - builder.Append((bool) value ? "true" : "false"); + builder.Append((bool)value ? "true" : "false"); } else if ((asList = value as IList) != null) { @@ -508,7 +519,7 @@ void SerializeValue(object value) } else if (value is char) { - SerializeString(new string((char) value, 1)); + SerializeString(new string((char)value, 1)); } else { @@ -533,17 +544,20 @@ void SerializeObject(IDictionary obj) { if (first) { - if (humanReadable) AppendNewLineFunc(); + if (humanReadable) + AppendNewLineFunc(); } else { builder.Append(','); - if (humanReadable) AppendNewLineFunc(); + if (humanReadable) + AppendNewLineFunc(); } SerializeString(e.ToString()); builder.Append(':'); - if (humanReadable) builder.Append(' '); + if (humanReadable) + builder.Append(' '); SerializeValue(obj[e]); @@ -551,7 +565,8 @@ void SerializeObject(IDictionary obj) } --indentLevel; - if (humanReadable && obj.Count > 0) AppendNewLineFunc(); + if (humanReadable && obj.Count > 0) + AppendNewLineFunc(); builder.Append('}'); } @@ -568,12 +583,14 @@ void SerializeArray(IList anArray) object obj = anArray[i]; if (first) { - if (humanReadable) AppendNewLineFunc(); + if (humanReadable) + AppendNewLineFunc(); } else { builder.Append(','); - if (humanReadable) AppendNewLineFunc(); + if (humanReadable) + AppendNewLineFunc(); } SerializeValue(obj); @@ -582,7 +599,8 @@ void SerializeArray(IList anArray) } --indentLevel; - if (humanReadable && anArray.Count > 0) AppendNewLineFunc(); + if (humanReadable && anArray.Count > 0) + AppendNewLineFunc(); builder.Append(']'); } @@ -644,24 +662,33 @@ void SerializeOther(object value) // Previously floats and doubles lost precision too. if (value is float) { - builder.Append(((float) value).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + builder.Append( + ((float)value).ToString( + "R", + System.Globalization.CultureInfo.InvariantCulture + ) + ); } - else if (value is int - || value is uint - || value is long - || value is sbyte - || value is byte - || value is short - || value is ushort - || value is ulong) + else if ( + value is int + || value is uint + || value is long + || value is sbyte + || value is byte + || value is short + || value is ushort + || value is ulong + ) { builder.Append(value); } - else if (value is double - || value is decimal) + else if (value is double || value is decimal) { - builder.Append(Convert.ToDouble(value) - .ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + builder.Append( + Convert + .ToDouble(value) + .ToString("R", System.Globalization.CultureInfo.InvariantCulture) + ); } else { @@ -670,4 +697,4 @@ void SerializeOther(object value) } } } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/Editor/Utilities/ReflectionHelpers.cs b/OneSignalExample/Assets/OneSignal/Editor/Utilities/ReflectionHelpers.cs index a5a151e8d..6cdda7428 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/Utilities/ReflectionHelpers.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/Utilities/ReflectionHelpers.cs @@ -2,20 +2,25 @@ using System.Collections.Generic; using System.Linq; -namespace OneSignalSDK.Installer { - public static class ReflectionHelpers { - public static IEnumerable FindAllAssignableTypes(string assemblyFilter) { +namespace OneSignalSDK.Installer +{ + public static class ReflectionHelpers + { + public static IEnumerable FindAllAssignableTypes(string assemblyFilter) + { var assignableType = typeof(T); - + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); - var filteredAssemblies = assemblies.Where(assembly - => assembly.FullName.Contains(assemblyFilter)); - + var filteredAssemblies = assemblies.Where(assembly => + assembly.FullName.Contains(assemblyFilter) + ); + var allTypes = filteredAssemblies.SelectMany(assembly => assembly.GetTypes()); - var assignableTypes = allTypes.Where(type - => type != assignableType && assignableType.IsAssignableFrom(type)); + var assignableTypes = allTypes.Where(type => + type != assignableType && assignableType.IsAssignableFrom(type) + ); return assignableTypes; } } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignal/link.xml b/OneSignalExample/Assets/OneSignal/link.xml index 68831e9e8..63b9781b1 100644 --- a/OneSignalExample/Assets/OneSignal/link.xml +++ b/OneSignalExample/Assets/OneSignal/link.xml @@ -1,5 +1,5 @@ - - - - \ No newline at end of file + + + + diff --git a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalFileInventoryGenerator.cs b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalFileInventoryGenerator.cs index 422151793..507a0b2fb 100644 --- a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalFileInventoryGenerator.cs +++ b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalFileInventoryGenerator.cs @@ -29,16 +29,19 @@ using UnityEditor; using UnityEngine; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Creates the resource to be distributed with the SDK *.unitypackage /// - public static class OneSignalFileInventoryGenerator { + public static class OneSignalFileInventoryGenerator + { /// /// Run from the internal OneSignal menu or cmdline to create a inventory resource to distribute /// [MenuItem("OneSignal/Generate File Inventory", false, 100)] - public static void GenerateInventory() { + public static void GenerateInventory() + { var inventory = ScriptableObject.CreateInstance(); inventory.DistributedPaths = OneSignalFileInventory.GetCurrentPaths(); @@ -46,4 +49,4 @@ public static void GenerateInventory() { AssetDatabase.CreateAsset(inventory, OneSignalFileInventory.AssetPath); } } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalPackagePublisher.cs b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalPackagePublisher.cs index 4fcbef3d6..6c9a8d768 100644 --- a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalPackagePublisher.cs +++ b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalPackagePublisher.cs @@ -29,21 +29,25 @@ using System.Linq; using UnityEditor; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Creates a unitypackage file for publishing /// - public static class OneSignalPackagePublisher { - public static void UpdateProjectVersion() { + public static class OneSignalPackagePublisher + { + public static void UpdateProjectVersion() + { var packageVersion = File.ReadAllText(VersionFilePath); PlayerSettings.bundleVersion = packageVersion; } [MenuItem("OneSignal/ExportUnityPackage")] - public static void ExportUnityPackage() { + public static void ExportUnityPackage() + { AssetDatabase.Refresh(); var packageVersion = File.ReadAllText(VersionFilePath); - var packageName = $"OneSignal-v{packageVersion}.unitypackage"; + var packageName = $"OneSignal-v{packageVersion}.unitypackage"; AssetDatabase.ExportPackage( _filePaths(), @@ -55,14 +59,17 @@ public static void ExportUnityPackage() { private static readonly string PackagePath = Path.Combine("Assets", "OneSignal"); private static readonly string VersionFilePath = Path.Combine(PackagePath, "VERSION"); - private static readonly string[] Exclusions = { + private static readonly string[] Exclusions = + { Path.Combine(PackagePath, "Attribution"), - ".DS_Store" + ".DS_Store", }; - private static string[] _filePaths() { + private static string[] _filePaths() + { var files = Directory.GetFileSystemEntries(PackagePath); - var pathsToInclude = files.Where(file => { + var pathsToInclude = files.Where(file => + { if (file.EndsWith(".meta")) file = file.Substring(0, file.Length - 5); @@ -72,4 +79,4 @@ private static string[] _filePaths() { return pathsToInclude.ToArray(); } } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalSetupReset.cs b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalSetupReset.cs index 1581a80d0..704efedd0 100644 --- a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalSetupReset.cs +++ b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalSetupReset.cs @@ -28,21 +28,26 @@ using System.IO; using UnityEditor; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// For debugging all of the OneSignalSetupSteps /// - public static class OneSignalSetupReset { + public static class OneSignalSetupReset + { /// /// Resets all setup steps /// [MenuItem("OneSignal/Reset All Setup Steps", false, 100)] - public static void ResetAllSteps() { + public static void ResetAllSteps() + { /* * ExportAndroidResourcesStep * deletes the OneSignalConfig.androidlib directory */ - AssetDatabase.DeleteAsset(Path.Combine("Assets", "Plugins", "Android", "OneSignalConfig.androidlib")); + AssetDatabase.DeleteAsset( + Path.Combine("Assets", "Plugins", "Android", "OneSignalConfig.androidlib") + ); /* * InstallEdm4UStep @@ -74,9 +79,9 @@ public static void ResetAllSteps() { manifest.RemoveScopeRegistry("https://registry.npmjs.org"); manifest.ApplyChanges(); - #if UNITY_2020_1_OR_NEWER +#if UNITY_2020_1_OR_NEWER UnityEditor.PackageManager.Client.Resolve(); - #endif +#endif } } -} \ No newline at end of file +} diff --git a/OneSignalExample/Assets/Plugins/Android/AndroidManifest.xml b/OneSignalExample/Assets/Plugins/Android/AndroidManifest.xml index f1526c519..e65eb925f 100644 --- a/OneSignalExample/Assets/Plugins/Android/AndroidManifest.xml +++ b/OneSignalExample/Assets/Plugins/Android/AndroidManifest.xml @@ -1,22 +1,22 @@ - - - - - - - - - - - - - - - + xmlns:android="http://schemas.android.com/apk/res/android" + package="com.unity3d.player" + xmlns:tools="http://schemas.android.com/tools" +> + + + + + + + + + + + + diff --git a/OneSignalExample/Assets/Plugins/Android/OneSignalConfig.androidlib/AndroidManifest.xml b/OneSignalExample/Assets/Plugins/Android/OneSignalConfig.androidlib/AndroidManifest.xml index 9d45d46f0..d1652ab82 100644 --- a/OneSignalExample/Assets/Plugins/Android/OneSignalConfig.androidlib/AndroidManifest.xml +++ b/OneSignalExample/Assets/Plugins/Android/OneSignalConfig.androidlib/AndroidManifest.xml @@ -2,9 +2,9 @@ WARNING: Do NOT Modify! Changes will be overwritten by the OneSignal plugin. Make your changes to Assets/Plugins/Android/AndroidManifest.xml instead. --> - - - \ No newline at end of file + diff --git a/OneSignalExample/ProjectSettings/AndroidResolverDependencies.xml b/OneSignalExample/ProjectSettings/AndroidResolverDependencies.xml index cc7777feb..a8f902665 100644 --- a/OneSignalExample/ProjectSettings/AndroidResolverDependencies.xml +++ b/OneSignalExample/ProjectSettings/AndroidResolverDependencies.xml @@ -20,4 +20,4 @@ - \ No newline at end of file + diff --git a/OneSignalExample/ProjectSettings/GvhProjectSettings.xml b/OneSignalExample/ProjectSettings/GvhProjectSettings.xml index 5e2f00954..b3045b0d4 100644 --- a/OneSignalExample/ProjectSettings/GvhProjectSettings.xml +++ b/OneSignalExample/ProjectSettings/GvhProjectSettings.xml @@ -1,6 +1,9 @@ - + @@ -18,4 +21,4 @@ - \ No newline at end of file + diff --git a/com.onesignal.unity.android/Editor/Migration/MigrateAndroidResources.cs b/com.onesignal.unity.android/Editor/Migration/MigrateAndroidResources.cs index 09982acd3..8c835ba3f 100644 --- a/com.onesignal.unity.android/Editor/Migration/MigrateAndroidResources.cs +++ b/com.onesignal.unity.android/Editor/Migration/MigrateAndroidResources.cs @@ -1,11 +1,13 @@ using System.IO; using UnityEditor; -namespace OneSignalSDK { - +namespace OneSignalSDK +{ [InitializeOnLoad] - sealed class MigrateAndroidResources { - static MigrateAndroidResources() { + sealed class MigrateAndroidResources + { + static MigrateAndroidResources() + { UpdateBuildDotGradleContains(); } @@ -15,7 +17,8 @@ static MigrateAndroidResources() { /// Includes compatibility with Unity 6, as it's Gradle version has new /// requirements. /// - private static void UpdateBuildDotGradleContains() { + private static void UpdateBuildDotGradleContains() + { if (!Directory.Exists(ExportAndroidResourcesStep._pluginExportPath)) return; @@ -33,7 +36,8 @@ private static void UpdateBuildDotGradleContains() { // We want to copy only when needed, otherwise it can reset file // properties, such as permissions and timestamps - if (exportedContains != packageContains) { + if (exportedContains != packageContains) + { File.Copy(packageFilename, exportedFilename, true); } } diff --git a/com.onesignal.unity.android/Editor/OneSignalAndroidDependencies.xml b/com.onesignal.unity.android/Editor/OneSignalAndroidDependencies.xml index c2fb7529b..ef098636b 100644 --- a/com.onesignal.unity.android/Editor/OneSignalAndroidDependencies.xml +++ b/com.onesignal.unity.android/Editor/OneSignalAndroidDependencies.xml @@ -5,4 +5,4 @@ - \ No newline at end of file + diff --git a/com.onesignal.unity.android/Editor/OneSignalConfig.androidlib/AndroidManifest.xml b/com.onesignal.unity.android/Editor/OneSignalConfig.androidlib/AndroidManifest.xml index 9d45d46f0..d1652ab82 100644 --- a/com.onesignal.unity.android/Editor/OneSignalConfig.androidlib/AndroidManifest.xml +++ b/com.onesignal.unity.android/Editor/OneSignalConfig.androidlib/AndroidManifest.xml @@ -2,9 +2,9 @@ WARNING: Do NOT Modify! Changes will be overwritten by the OneSignal plugin. Make your changes to Assets/Plugins/Android/AndroidManifest.xml instead. --> - - - \ No newline at end of file + diff --git a/com.onesignal.unity.android/Editor/SetupSteps/ExportAndroidResourcesStep.cs b/com.onesignal.unity.android/Editor/SetupSteps/ExportAndroidResourcesStep.cs index 1bf628803..3f3e23c9c 100644 --- a/com.onesignal.unity.android/Editor/SetupSteps/ExportAndroidResourcesStep.cs +++ b/com.onesignal.unity.android/Editor/SetupSteps/ExportAndroidResourcesStep.cs @@ -30,30 +30,37 @@ using System.Linq; using UnityEditor; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Copies the OneSignalConfig.androidlib to Assets/Plugins/Android/* /// - public sealed class ExportAndroidResourcesStep : OneSignalSetupStep { - public override string Summary - => "Copy Android plugin to Assets"; + public sealed class ExportAndroidResourcesStep : OneSignalSetupStep + { + public override string Summary => "Copy Android plugin to Assets"; - public override string Details - => $"Will create the {_pluginExportPath} directory filled with notification icons to be customized for your app"; + public override string Details => + $"Will create the {_pluginExportPath} directory filled with notification icons to be customized for your app"; - public override bool IsRequired - => true; + public override bool IsRequired => true; - protected override bool _getIsStepCompleted() { + protected override bool _getIsStepCompleted() + { if (!Directory.Exists(_pluginExportPath) || Directory.Exists(_pluginV3ExportPath)) return false; - var packagePaths = Directory.GetFiles(_pluginPackagePath, "*", SearchOption.AllDirectories) - .Select(path => path.Remove(0, path.LastIndexOf(_pluginName, StringComparison.InvariantCulture))); + var packagePaths = Directory + .GetFiles(_pluginPackagePath, "*", SearchOption.AllDirectories) + .Select(path => + path.Remove(0, path.LastIndexOf(_pluginName, StringComparison.InvariantCulture)) + ); packagePaths = packagePaths.Where(file => !file.EndsWith(".meta")); - var exportPaths = Directory.GetFiles(_pluginExportPath, "*", SearchOption.AllDirectories) - .Select(path => path.Remove(0, path.LastIndexOf(_pluginName, StringComparison.InvariantCulture))); + var exportPaths = Directory + .GetFiles(_pluginExportPath, "*", SearchOption.AllDirectories) + .Select(path => + path.Remove(0, path.LastIndexOf(_pluginName, StringComparison.InvariantCulture)) + ); var fileDiff = packagePaths.Except(exportPaths); @@ -62,20 +69,24 @@ protected override bool _getIsStepCompleted() { var pluginManifest = File.ReadAllText(_manifestPackagePath); var projectManifest = File.ReadAllText(_manifestExportPath); - + return pluginManifest == projectManifest; } - protected override void _runStep() { + protected override void _runStep() + { MigratePluginToAndroidlib(); var files = Directory.GetFiles(_pluginPackagePath, "*", SearchOption.AllDirectories); var filteredFiles = files.Where(file => !file.EndsWith(".meta")); - foreach (var file in filteredFiles) { - var trimmedPath = file.Remove(0, _pluginPackagePath.Length + 1); + foreach (var file in filteredFiles) + { + var trimmedPath = file.Remove(0, _pluginPackagePath.Length + 1); var fileExportPath = Path.Combine(_pluginExportPath, trimmedPath); - var containingPath = fileExportPath.Remove(fileExportPath.LastIndexOf(Path.DirectorySeparatorChar)); + var containingPath = fileExportPath.Remove( + fileExportPath.LastIndexOf(Path.DirectorySeparatorChar) + ); /* * Export the file. @@ -85,7 +96,7 @@ protected override void _runStep() { if (!Directory.Exists(containingPath)) Directory.CreateDirectory(containingPath); - + if (!fileExportPath.Contains(".png")) // always refresh non-pngs File.Copy(file, fileExportPath, true); else if (!File.Exists(fileExportPath)) // don't copy over existing png files @@ -95,18 +106,22 @@ protected override void _runStep() { AssetDatabase.Refresh(); } - private void MigratePluginToAndroidlib() { - if (Directory.Exists(_pluginV3ExportPath)) { - if (!Directory.Exists(_pluginExportPath)) { + private void MigratePluginToAndroidlib() + { + if (Directory.Exists(_pluginV3ExportPath)) + { + if (!Directory.Exists(_pluginExportPath)) + { try { AssetDatabase.StartAssetEditing(); // Remove project.properties - if (File.Exists(_projectPropertiesV3ExportPath)) { + if (File.Exists(_projectPropertiesV3ExportPath)) + { AssetDatabase.DeleteAsset(_projectPropertiesV3ExportPath); } - + // Rename OneSignalConfig.plugin to OneSignalConfig.androidlib AssetDatabase.MoveAsset(_pluginV3ExportPath, _pluginExportPath); } @@ -116,35 +131,67 @@ private void MigratePluginToAndroidlib() { } // Move the icons and .wav file to /src/main - if (Directory.Exists(_resV3ExportPath)) { + if (Directory.Exists(_resV3ExportPath)) + { Directory.CreateDirectory(Path.GetDirectoryName(_resExportPath)); FileUtil.MoveFileOrDirectory(_resV3ExportPath, _resExportPath); } - } else { + } + else + { AssetDatabase.DeleteAsset(_pluginV3ExportPath); } } } private const string _pluginName = "OneSignalConfig.androidlib"; - private static readonly string _packagePath = Path.Combine("Packages", "com.onesignal.unity.android", "Editor"); - private static readonly string _androidPluginsPath = Path.Combine("Assets", "Plugins", "Android"); - - internal static readonly string _pluginPackagePath = Path.Combine(_packagePath, _pluginName); - internal static readonly string _pluginExportPath = Path.Combine(_androidPluginsPath, _pluginName); - - private static readonly string _manifestPackagePath = Path.Combine(_pluginPackagePath, "AndroidManifest.xml"); - private static readonly string _manifestExportPath = Path.Combine(_pluginExportPath, "AndroidManifest.xml"); + private static readonly string _packagePath = Path.Combine( + "Packages", + "com.onesignal.unity.android", + "Editor" + ); + private static readonly string _androidPluginsPath = Path.Combine( + "Assets", + "Plugins", + "Android" + ); + + internal static readonly string _pluginPackagePath = Path.Combine( + _packagePath, + _pluginName + ); + internal static readonly string _pluginExportPath = Path.Combine( + _androidPluginsPath, + _pluginName + ); + + private static readonly string _manifestPackagePath = Path.Combine( + _pluginPackagePath, + "AndroidManifest.xml" + ); + private static readonly string _manifestExportPath = Path.Combine( + _pluginExportPath, + "AndroidManifest.xml" + ); private const string _resPath = "src/main/res"; private static readonly string _resExportPath = Path.Combine(_pluginExportPath, _resPath); // Old OneSignalConfig name used from 3.x.x to 5.0.2 private const string _pluginNameV3 = "OneSignalConfig.plugin"; - private static readonly string _pluginV3ExportPath = Path.Combine(_androidPluginsPath, _pluginNameV3); - private static readonly string _projectPropertiesV3ExportPath = Path.Combine(_pluginV3ExportPath, "project.properties"); + private static readonly string _pluginV3ExportPath = Path.Combine( + _androidPluginsPath, + _pluginNameV3 + ); + private static readonly string _projectPropertiesV3ExportPath = Path.Combine( + _pluginV3ExportPath, + "project.properties" + ); private const string _resV3Path = "res"; - private static readonly string _resV3ExportPath = Path.Combine(_pluginExportPath, _resV3Path); + private static readonly string _resV3ExportPath = Path.Combine( + _pluginExportPath, + _resV3Path + ); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AndroidDebugManager.cs b/com.onesignal.unity.android/Runtime/AndroidDebugManager.cs index b3a0b0197..4ae7cb3d7 100644 --- a/com.onesignal.unity.android/Runtime/AndroidDebugManager.cs +++ b/com.onesignal.unity.android/Runtime/AndroidDebugManager.cs @@ -25,41 +25,53 @@ * THE SOFTWARE. */ -using UnityEngine; using OneSignalSDK.Debug; using OneSignalSDK.Debug.Models; +using UnityEngine; -namespace OneSignalSDK.Android.Debug { - internal sealed class AndroidDebugManager : IDebugManager { +namespace OneSignalSDK.Android.Debug +{ + internal sealed class AndroidDebugManager : IDebugManager + { private readonly AndroidJavaObject _debug; private LogLevel _logLevel = LogLevel.Warn; private LogLevel _alertLevel = LogLevel.None; - public AndroidDebugManager(AndroidJavaClass sdkClass) { + public AndroidDebugManager(AndroidJavaClass sdkClass) + { _debug = sdkClass.CallStatic("getDebug"); } - public LogLevel LogLevel { + public LogLevel LogLevel + { get => _logLevel; - set { + set + { _logLevel = value; _debug.Call("setLogLevel", ToLogLevel(value)); } } - public LogLevel AlertLevel { + public LogLevel AlertLevel + { get => _alertLevel; - set { + set + { _alertLevel = value; _debug.Call("setAlertLevel", ToLogLevel(value)); } } - private AndroidJavaObject ToLogLevel(LogLevel value) { + private AndroidJavaObject ToLogLevel(LogLevel value) + { var logLevelClass = new AndroidJavaClass("com.onesignal.debug.LogLevel"); - var logLevelValue = logLevelClass.CallStatic("valueOf", logLevelClass, value.ToString().ToUpper()); + var logLevelValue = logLevelClass.CallStatic( + "valueOf", + logLevelClass, + value.ToString().ToUpper() + ); return logLevelValue; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AndroidDisplayableNotification.cs b/com.onesignal.unity.android/Runtime/AndroidDisplayableNotification.cs index 4b6dffc50..1108e7cc8 100644 --- a/com.onesignal.unity.android/Runtime/AndroidDisplayableNotification.cs +++ b/com.onesignal.unity.android/Runtime/AndroidDisplayableNotification.cs @@ -26,15 +26,16 @@ */ using System; -using UnityEngine; using OneSignalSDK.Notifications.Internal; using OneSignalSDK.Notifications.Models; +using UnityEngine; -namespace OneSignalSDK.Android.Notifications.Models { - public sealed class AndroidDisplayableNotification : Notification, IDisplayableNotification { +namespace OneSignalSDK.Android.Notifications.Models +{ + public sealed class AndroidDisplayableNotification : Notification, IDisplayableNotification + { public AndroidJavaObject NotifJO { get; set; } - public void Display() - => NotifJO?.Call("display"); + public void Display() => NotifJO?.Call("display"); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AndroidInAppMessagesManager.cs b/com.onesignal.unity.android/Runtime/AndroidInAppMessagesManager.cs index c40102a20..741f760ac 100644 --- a/com.onesignal.unity.android/Runtime/AndroidInAppMessagesManager.cs +++ b/com.onesignal.unity.android/Runtime/AndroidInAppMessagesManager.cs @@ -25,20 +25,22 @@ * THE SOFTWARE. */ - -using UnityEngine; using System; using System.Collections.Generic; +using OneSignalSDK.Android.Utilities; using OneSignalSDK.InAppMessages; -using OneSignalSDK.InAppMessages.Models; using OneSignalSDK.InAppMessages.Internal; -using OneSignalSDK.Android.Utilities; +using OneSignalSDK.InAppMessages.Models; +using UnityEngine; -namespace OneSignalSDK.Android.InAppMessages { - internal sealed class AndroidInAppMessagesManager : IInAppMessagesManager { +namespace OneSignalSDK.Android.InAppMessages +{ + internal sealed class AndroidInAppMessagesManager : IInAppMessagesManager + { private readonly AndroidJavaObject _inAppMessages; - public AndroidInAppMessagesManager(AndroidJavaClass sdkClass) { + public AndroidInAppMessagesManager(AndroidJavaClass sdkClass) + { _inAppMessages = sdkClass.CallStatic("getInAppMessages"); } @@ -48,44 +50,50 @@ public AndroidInAppMessagesManager(AndroidJavaClass sdkClass) { public event EventHandler DidDismiss; public event EventHandler Clicked; - public bool Paused { + public bool Paused + { get => _inAppMessages.Call("getPaused"); set => _inAppMessages.Call("setPaused", value); } - public void AddTrigger(string key, string value) - => _inAppMessages.Call("addTrigger", key, value); + public void AddTrigger(string key, string value) => + _inAppMessages.Call("addTrigger", key, value); - public void AddTriggers(Dictionary triggers) - => _inAppMessages.Call("addTriggers", triggers.ToMap()); + public void AddTriggers(Dictionary triggers) => + _inAppMessages.Call("addTriggers", triggers.ToMap()); - public void RemoveTrigger(string key) - => _inAppMessages.Call("removeTrigger", key); + public void RemoveTrigger(string key) => _inAppMessages.Call("removeTrigger", key); - public void RemoveTriggers(params string[] keys) - => _inAppMessages.Call("removeTriggers", keys.ToArrayList()); + public void RemoveTriggers(params string[] keys) => + _inAppMessages.Call("removeTriggers", keys.ToArrayList()); - public void ClearTriggers() - => _inAppMessages.Call("clearTriggers"); + public void ClearTriggers() => _inAppMessages.Call("clearTriggers"); - public void Initialize() { + public void Initialize() + { _inAppMessages.Call("addClickListener", new IInAppMessageClickListener(this)); _inAppMessages.Call("addLifecycleListener", new IInAppMessageLifecycleHandler(this)); } - private sealed class IInAppMessageLifecycleHandler : OneSignalAndroidJavaProxy { + private sealed class IInAppMessageLifecycleHandler : OneSignalAndroidJavaProxy + { private AndroidInAppMessagesManager _parent; - public IInAppMessageLifecycleHandler(AndroidInAppMessagesManager inAppMessagesManager) : base("inAppMessages.IInAppMessageLifecycleListener") { + public IInAppMessageLifecycleHandler(AndroidInAppMessagesManager inAppMessagesManager) + : base("inAppMessages.IInAppMessageLifecycleListener") + { _parent = inAppMessagesManager; } /// IInAppMessageWillDisplayEvent - public void onWillDisplay(AndroidJavaObject willDisplayEvent) { + public void onWillDisplay(AndroidJavaObject willDisplayEvent) + { var messageJO = willDisplayEvent.Call("getMessage"); var message = messageJO.ToSerializable(); - InAppMessageWillDisplayEventArgs args = new InAppMessageWillDisplayEventArgs(message); + InAppMessageWillDisplayEventArgs args = new InAppMessageWillDisplayEventArgs( + message + ); EventHandler handler = _parent.WillDisplay; if (handler != null) @@ -95,7 +103,8 @@ public void onWillDisplay(AndroidJavaObject willDisplayEvent) { } /// IInAppMessageDidDisplayEvent - public void onDidDisplay(AndroidJavaObject didDisplayEvent) { + public void onDidDisplay(AndroidJavaObject didDisplayEvent) + { var messageJO = didDisplayEvent.Call("getMessage"); var message = messageJO.ToSerializable(); @@ -109,11 +118,14 @@ public void onDidDisplay(AndroidJavaObject didDisplayEvent) { } /// IInAppMessageWillDismissEvent - public void onWillDismiss(AndroidJavaObject willDismissEvent) { + public void onWillDismiss(AndroidJavaObject willDismissEvent) + { var messageJO = willDismissEvent.Call("getMessage"); var message = messageJO.ToSerializable(); - InAppMessageWillDismissEventArgs args = new InAppMessageWillDismissEventArgs(message); + InAppMessageWillDismissEventArgs args = new InAppMessageWillDismissEventArgs( + message + ); EventHandler handler = _parent.WillDismiss; if (handler != null) @@ -123,7 +135,8 @@ public void onWillDismiss(AndroidJavaObject willDismissEvent) { } /// IInAppMessageDidDismissEvent - public void onDidDismiss(AndroidJavaObject didDismissEvent) { + public void onDidDismiss(AndroidJavaObject didDismissEvent) + { var messageJO = didDismissEvent.Call("getMessage"); var message = messageJO.ToSerializable(); @@ -137,27 +150,31 @@ public void onDidDismiss(AndroidJavaObject didDismissEvent) { } } - private sealed class IInAppMessageClickListener : OneSignalAndroidJavaProxy { + private sealed class IInAppMessageClickListener : OneSignalAndroidJavaProxy + { private AndroidInAppMessagesManager _parent; - public IInAppMessageClickListener(AndroidInAppMessagesManager inAppMessagesManager) : base("inAppMessages.IInAppMessageClickListener") { + public IInAppMessageClickListener(AndroidInAppMessagesManager inAppMessagesManager) + : base("inAppMessages.IInAppMessageClickListener") + { _parent = inAppMessagesManager; } /// IInAppMessageClickEvent - public void onClick(AndroidJavaObject clickEvent) { + public void onClick(AndroidJavaObject clickEvent) + { var messageJO = clickEvent.Call("getMessage"); var message = messageJO.ToSerializable(); var resultJO = clickEvent.Call("getResult"); - + // Not having a 1:1 serializable class with matching primative types will result in ToSerialization being empty var actionId = resultJO.Call("getActionId"); - + var urlTypeJO = resultJO.Call("getUrlTarget"); var urlType = urlTypeJO.Call("toString"); var urlTarget = StringToInAppMessageActionUrlType(urlType); - + var url = resultJO.Call("getUrl"); var closingMessage = resultJO.Call("getClosingMessage"); @@ -172,7 +189,10 @@ public void onClick(AndroidJavaObject clickEvent) { } } - public static InAppMessageActionUrlType StringToInAppMessageActionUrlType(string urlType) { + public static InAppMessageActionUrlType StringToInAppMessageActionUrlType( + string urlType + ) + { switch (urlType) { case "webview": @@ -187,4 +207,4 @@ public static InAppMessageActionUrlType StringToInAppMessageActionUrlType(string } } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AndroidLiveActivitiesManager.cs b/com.onesignal.unity.android/Runtime/AndroidLiveActivitiesManager.cs index c22b317e4..806e6ab72 100644 --- a/com.onesignal.unity.android/Runtime/AndroidLiveActivitiesManager.cs +++ b/com.onesignal.unity.android/Runtime/AndroidLiveActivitiesManager.cs @@ -24,24 +24,28 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -using UnityEngine; using System.Collections.Generic; using System.Threading.Tasks; -using OneSignalSDK.LiveActivities; using OneSignalSDK.Debug.Utilities; +using OneSignalSDK.LiveActivities; +using UnityEngine; -namespace OneSignalSDK.Android.LiveActivities { - internal sealed class AndroidLiveActivitiesManager : ILiveActivitiesManager { - public Task EnterAsync(string activityId, string token) { +namespace OneSignalSDK.Android.LiveActivities +{ + internal sealed class AndroidLiveActivitiesManager : ILiveActivitiesManager + { + public Task EnterAsync(string activityId, string token) + { SDKDebug.Warn("This feature is only available for iOS."); return Task.FromResult(false); } - public Task ExitAsync(string activityId) { + public Task ExitAsync(string activityId) + { SDKDebug.Warn("This feature is only available for iOS."); return Task.FromResult(false); } - + public void RemovePushToStartToken(string activityType) { SDKDebug.Warn("This feature is only available for iOS."); @@ -57,9 +61,13 @@ public void SetupDefault(LiveActivitySetupOptions options = null) SDKDebug.Warn("This feature is only available for iOS."); } - public void StartDefault(string activityId, IDictionary attributes, IDictionary content) + public void StartDefault( + string activityId, + IDictionary attributes, + IDictionary content + ) { SDKDebug.Warn("This feature is only available for iOS."); } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AndroidLocationManager.cs b/com.onesignal.unity.android/Runtime/AndroidLocationManager.cs index c781f13fb..22cd337ee 100644 --- a/com.onesignal.unity.android/Runtime/AndroidLocationManager.cs +++ b/com.onesignal.unity.android/Runtime/AndroidLocationManager.cs @@ -25,27 +25,32 @@ * THE SOFTWARE. */ -using UnityEngine; using System.Threading.Tasks; -using OneSignalSDK.Location; using OneSignalSDK.Android.Utilities; +using OneSignalSDK.Location; +using UnityEngine; -namespace OneSignalSDK.Android.Location { - internal sealed class AndroidLocationManager : ILocationManager { +namespace OneSignalSDK.Android.Location +{ + internal sealed class AndroidLocationManager : ILocationManager + { private readonly AndroidJavaObject _location; - - public AndroidLocationManager(AndroidJavaClass sdkClass) { + + public AndroidLocationManager(AndroidJavaClass sdkClass) + { _location = sdkClass.CallStatic("getLocation"); } - public bool IsShared { + public bool IsShared + { get => _location.Call("isShared"); set => _location.Call("setShared", value); } - public void RequestPermission() { + public void RequestPermission() + { var continuation = new BoolContinuation(); _location.Call("requestPermission", continuation.Proxy); } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AndroidNotificationsManager.cs b/com.onesignal.unity.android/Runtime/AndroidNotificationsManager.cs index 106a20561..4c4808b59 100644 --- a/com.onesignal.unity.android/Runtime/AndroidNotificationsManager.cs +++ b/com.onesignal.unity.android/Runtime/AndroidNotificationsManager.cs @@ -25,21 +25,24 @@ * THE SOFTWARE. */ -using UnityEngine; using System; -using System.Threading.Tasks; using System.Collections.Generic; +using System.Threading.Tasks; +using OneSignalSDK.Android.Notifications.Models; +using OneSignalSDK.Android.Utilities; using OneSignalSDK.Notifications; -using OneSignalSDK.Notifications.Models; using OneSignalSDK.Notifications.Internal; -using OneSignalSDK.Android.Utilities; -using OneSignalSDK.Android.Notifications.Models; +using OneSignalSDK.Notifications.Models; +using UnityEngine; -namespace OneSignalSDK.Android.Notifications { - internal sealed class AndroidNotificationsManager : INotificationsManager { +namespace OneSignalSDK.Android.Notifications +{ + internal sealed class AndroidNotificationsManager : INotificationsManager + { private readonly AndroidJavaObject _notifications; - public AndroidNotificationsManager(AndroidJavaClass sdkClass) { + public AndroidNotificationsManager(AndroidJavaClass sdkClass) + { _notifications = sdkClass.CallStatic("getNotifications"); } @@ -47,46 +50,68 @@ public AndroidNotificationsManager(AndroidJavaClass sdkClass) { public event EventHandler Clicked; public event EventHandler PermissionChanged; - public bool Permission { + public bool Permission + { get => _notifications.Call("getPermission"); } - public bool CanRequestPermission { + public bool CanRequestPermission + { get => _notifications.Call("getCanRequestPermission"); } - public NotificationPermission PermissionNative { - get => _notifications.Call("getPermission") ? NotificationPermission.Authorized : NotificationPermission.Denied; + public NotificationPermission PermissionNative + { + get => + _notifications.Call("getPermission") + ? NotificationPermission.Authorized + : NotificationPermission.Denied; } - public async Task RequestPermissionAsync(bool fallbackToSettings) { + public async Task RequestPermissionAsync(bool fallbackToSettings) + { var continuation = new BoolContinuation(); - _notifications.Call("requestPermission", fallbackToSettings, continuation.Proxy); + _notifications.Call( + "requestPermission", + fallbackToSettings, + continuation.Proxy + ); return await continuation; } - public void ClearAllNotifications() { + public void ClearAllNotifications() + { _notifications.Call("clearAllNotifications"); } - public void Initialize() { + public void Initialize() + { _notifications.Call("addPermissionObserver", new InternalPermissionObserver(this)); - _notifications.Call("addForegroundLifecycleListener", new InternalNotificationLifecycleListener(this)); + _notifications.Call( + "addForegroundLifecycleListener", + new InternalNotificationLifecycleListener(this) + ); _notifications.Call("addClickListener", new InternalNotificationClickListener(this)); } - private sealed class InternalPermissionObserver : OneSignalAwaitableAndroidJavaProxy { + private sealed class InternalPermissionObserver : OneSignalAwaitableAndroidJavaProxy + { private AndroidNotificationsManager _parent; - - public InternalPermissionObserver(AndroidNotificationsManager notificationsManager) : base("notifications.IPermissionObserver") { + + public InternalPermissionObserver(AndroidNotificationsManager notificationsManager) + : base("notifications.IPermissionObserver") + { _parent = notificationsManager; } /// boolean - public void onNotificationPermissionChange(bool permission) { - NotificationPermissionChangedEventArgs args = new NotificationPermissionChangedEventArgs(permission); + public void onNotificationPermissionChange(bool permission) + { + NotificationPermissionChangedEventArgs args = + new NotificationPermissionChangedEventArgs(permission); - EventHandler handler = _parent.PermissionChanged; + EventHandler handler = + _parent.PermissionChanged; if (handler != null) { UnityMainThreadDispatch.Post(state => handler(_parent, args)); @@ -94,21 +119,29 @@ public void onNotificationPermissionChange(bool permission) { } } - private sealed class InternalNotificationLifecycleListener : OneSignalAndroidJavaProxy { + private sealed class InternalNotificationLifecycleListener : OneSignalAndroidJavaProxy + { private AndroidNotificationsManager _parent; - public InternalNotificationLifecycleListener(AndroidNotificationsManager notificationsManager) : base("notifications.INotificationLifecycleListener") { + public InternalNotificationLifecycleListener( + AndroidNotificationsManager notificationsManager + ) + : base("notifications.INotificationLifecycleListener") + { _parent = notificationsManager; } /// INotificationWillDisplayEvent - public void onWillDisplay(AndroidJavaObject willDisplayEvent) { + public void onWillDisplay(AndroidJavaObject willDisplayEvent) + { var notifJO = willDisplayEvent.Call("getNotification"); var notification = _getNotification(notifJO); - InternalNotificationWillDisplayEventArgs args = new InternalNotificationWillDisplayEventArgs(willDisplayEvent, notification); + InternalNotificationWillDisplayEventArgs args = + new InternalNotificationWillDisplayEventArgs(willDisplayEvent, notification); - EventHandler handler = _parent.ForegroundWillDisplay; + EventHandler handler = + _parent.ForegroundWillDisplay; if (handler != null) { // We use Send instead of Post because we need to *not* return to our caller until the @@ -119,32 +152,47 @@ public void onWillDisplay(AndroidJavaObject willDisplayEvent) { } } - public class InternalNotificationWillDisplayEventArgs : NotificationWillDisplayEventArgs { + public class InternalNotificationWillDisplayEventArgs : NotificationWillDisplayEventArgs + { private AndroidJavaObject _willDisplayEvent; - public InternalNotificationWillDisplayEventArgs(AndroidJavaObject willDisplayEvent, IDisplayableNotification notification) : base(notification) { + public InternalNotificationWillDisplayEventArgs( + AndroidJavaObject willDisplayEvent, + IDisplayableNotification notification + ) + : base(notification) + { _willDisplayEvent = willDisplayEvent; } public override void PreventDefault() => _willDisplayEvent.Call("preventDefault"); } - private sealed class InternalNotificationClickListener : OneSignalAndroidJavaProxy { + private sealed class InternalNotificationClickListener : OneSignalAndroidJavaProxy + { private AndroidNotificationsManager _parent; - public InternalNotificationClickListener(AndroidNotificationsManager notificationsManager) : base("notifications.INotificationClickListener") { + public InternalNotificationClickListener( + AndroidNotificationsManager notificationsManager + ) + : base("notifications.INotificationClickListener") + { _parent = notificationsManager; } /// INotificationClickEvent - public void onClick(AndroidJavaObject clickEvent) { + public void onClick(AndroidJavaObject clickEvent) + { var notifJO = clickEvent.Call("getNotification"); var notification = _getNotification(notifJO); var resultJO = clickEvent.Call("getResult"); var result = resultJO.ToSerializable(); - NotificationClickEventArgs args = new NotificationClickEventArgs(notification, result); + NotificationClickEventArgs args = new NotificationClickEventArgs( + notification, + result + ); EventHandler handler = _parent.Clicked; if (handler != null) @@ -154,23 +202,31 @@ public void onClick(AndroidJavaObject clickEvent) { } } - private static AndroidDisplayableNotification _getNotification(AndroidJavaObject notifJO) { + private static AndroidDisplayableNotification _getNotification(AndroidJavaObject notifJO) + { var notification = notifJO.ToSerializable(); - + var dataJson = notifJO.Call("getAdditionalData"); - if (dataJson != null) { + if (dataJson != null) + { var dataJsonStr = dataJson.Call("toString"); - notification.additionalData = Json.Deserialize(dataJsonStr) as Dictionary; + notification.additionalData = + Json.Deserialize(dataJsonStr) as Dictionary; } - var groupedNotificationsJson = notifJO.Call("getGroupedNotifications"); - if (groupedNotificationsJson != null) { + var groupedNotificationsJson = notifJO.Call( + "getGroupedNotifications" + ); + if (groupedNotificationsJson != null) + { var groupedNotificationsStr = groupedNotificationsJson.Call("toString"); - notification.groupedNotifications = Json.Deserialize(groupedNotificationsStr) as List; + notification.groupedNotifications = + Json.Deserialize(groupedNotificationsStr) as List; } var rawPayloadJson = notifJO.Call("getRawPayload"); - if (rawPayloadJson != null) { + if (rawPayloadJson != null) + { var rawPayloadJsonStr = rawPayloadJson.Call("toString"); notification.rawPayload = rawPayloadJsonStr; } @@ -181,4 +237,4 @@ private static AndroidDisplayableNotification _getNotification(AndroidJavaObject return notification; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AndroidPushSubscription.cs b/com.onesignal.unity.android/Runtime/AndroidPushSubscription.cs index a843f4f49..ad4bd9ce9 100644 --- a/com.onesignal.unity.android/Runtime/AndroidPushSubscription.cs +++ b/com.onesignal.unity.android/Runtime/AndroidPushSubscription.cs @@ -26,62 +26,75 @@ */ using System; -using UnityEngine; -using OneSignalSDK.User.Models; -using OneSignalSDK.User.Internal; using OneSignalSDK.Android.Utilities; +using OneSignalSDK.User.Internal; +using OneSignalSDK.User.Models; +using UnityEngine; -namespace OneSignalSDK.Android.User.Models { - internal sealed class AndroidPushSubscription : IPushSubscription { +namespace OneSignalSDK.Android.User.Models +{ + internal sealed class AndroidPushSubscription : IPushSubscription + { public event EventHandler Changed; private readonly AndroidJavaObject _user; - - public AndroidPushSubscription(AndroidJavaObject user) { + + public AndroidPushSubscription(AndroidJavaObject user) + { _user = user; } - private AndroidJavaObject _pushSubscription => _user.Call("getPushSubscription"); + private AndroidJavaObject _pushSubscription => + _user.Call("getPushSubscription"); - public string Id { + public string Id + { get => _pushSubscription.Call("getId"); } - public string Token { + public string Token + { get => _pushSubscription.Call("getToken"); } - public bool OptedIn { + public bool OptedIn + { get => _pushSubscription.Call("getOptedIn"); } - public void OptIn() - => _pushSubscription.Call("optIn"); + public void OptIn() => _pushSubscription.Call("optIn"); - public void OptOut() - => _pushSubscription.Call("optOut"); + public void OptOut() => _pushSubscription.Call("optOut"); - public void Initialize() { + public void Initialize() + { _pushSubscription.Call("addObserver", new InternalSubscriptionChangedHandler(this)); } - private sealed class InternalSubscriptionChangedHandler : OneSignalAndroidJavaProxy { + private sealed class InternalSubscriptionChangedHandler : OneSignalAndroidJavaProxy + { private AndroidPushSubscription _parent; - public InternalSubscriptionChangedHandler(AndroidPushSubscription pushSubscription) : base("user.subscriptions.IPushSubscriptionObserver") { + public InternalSubscriptionChangedHandler(AndroidPushSubscription pushSubscription) + : base("user.subscriptions.IPushSubscriptionObserver") + { _parent = pushSubscription; } /// PushSubscriptionChangedState - public void onPushSubscriptionChange(AndroidJavaObject state) { + public void onPushSubscriptionChange(AndroidJavaObject state) + { var previousJO = state.Call("getPrevious"); var previous = previousJO.ToSerializable(); var currentJO = state.Call("getCurrent"); var current = currentJO.ToSerializable(); - PushSubscriptionChangedState pushSubscriptionChangedState = new PushSubscriptionChangedState(previous, current); - PushSubscriptionChangedEventArgs args = new PushSubscriptionChangedEventArgs(pushSubscriptionChangedState); + PushSubscriptionChangedState pushSubscriptionChangedState = + new PushSubscriptionChangedState(previous, current); + PushSubscriptionChangedEventArgs args = new PushSubscriptionChangedEventArgs( + pushSubscriptionChangedState + ); EventHandler handler = _parent.Changed; if (handler != null) @@ -91,4 +104,4 @@ public void onPushSubscriptionChange(AndroidJavaObject state) { } } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AndroidSessionManager.cs b/com.onesignal.unity.android/Runtime/AndroidSessionManager.cs index 78a46660b..cb729bd55 100644 --- a/com.onesignal.unity.android/Runtime/AndroidSessionManager.cs +++ b/com.onesignal.unity.android/Runtime/AndroidSessionManager.cs @@ -25,24 +25,25 @@ * THE SOFTWARE. */ -using UnityEngine; using OneSignalSDK.Session; +using UnityEngine; -namespace OneSignalSDK.Android.Session { - internal sealed class AndroidSessionManager : ISessionManager { +namespace OneSignalSDK.Android.Session +{ + internal sealed class AndroidSessionManager : ISessionManager + { private readonly AndroidJavaObject _session; - - public AndroidSessionManager(AndroidJavaClass sdkClass) { + + public AndroidSessionManager(AndroidJavaClass sdkClass) + { _session = sdkClass.CallStatic("getSession"); } - public void AddOutcome(string name) - => _session.Call("addOutcome", name); + public void AddOutcome(string name) => _session.Call("addOutcome", name); - public void AddUniqueOutcome(string name) - => _session.Call("addUniqueOutcome", name); + public void AddUniqueOutcome(string name) => _session.Call("addUniqueOutcome", name); - public void AddOutcomeWithValue(string name, float value) - => _session.Call("addOutcomeWithValue", name, value); + public void AddOutcomeWithValue(string name, float value) => + _session.Call("addOutcomeWithValue", name, value); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AndroidUserManager.cs b/com.onesignal.unity.android/Runtime/AndroidUserManager.cs index efcb97f22..88d8c077e 100644 --- a/com.onesignal.unity.android/Runtime/AndroidUserManager.cs +++ b/com.onesignal.unity.android/Runtime/AndroidUserManager.cs @@ -25,104 +25,109 @@ * THE SOFTWARE. */ - -using UnityEngine; using System; using System.Collections.Generic; +using OneSignalSDK.Android.User.Models; +using OneSignalSDK.Android.Utilities; using OneSignalSDK.User; using OneSignalSDK.User.Internal; using OneSignalSDK.User.Models; -using OneSignalSDK.Android.User.Models; -using OneSignalSDK.Android.Utilities; +using UnityEngine; -namespace OneSignalSDK.Android.User { - internal sealed class AndroidUserManager : IUserManager { +namespace OneSignalSDK.Android.User +{ + internal sealed class AndroidUserManager : IUserManager + { private readonly AndroidJavaObject _user; private AndroidPushSubscription _pushSubscription; public event EventHandler Changed; - - public AndroidUserManager(AndroidJavaClass sdkClass) { + + public AndroidUserManager(AndroidJavaClass sdkClass) + { _user = sdkClass.CallStatic("getUser"); _pushSubscription = new AndroidPushSubscription(_user); } - public string OneSignalId { - get { + public string OneSignalId + { + get + { string id = _user.Call("getOnesignalId"); - return string.IsNullOrEmpty(id)? null : id; + return string.IsNullOrEmpty(id) ? null : id; } } - public string ExternalId { - get { + public string ExternalId + { + get + { string id = _user.Call("getExternalId"); - return string.IsNullOrEmpty(id)? null : id; + return string.IsNullOrEmpty(id) ? null : id; } } - public IPushSubscription PushSubscription { + public IPushSubscription PushSubscription + { get => _pushSubscription; } - public string Language { + public string Language + { set => _user.Call("setLanguage", value); } - public Dictionary GetTags() { + public Dictionary GetTags() + { AndroidJavaObject obj = _user.Call("getTags"); return obj.MapToDictionary(); } - public void AddTag(string key, string value) - => _user.Call("addTag", key, value); + public void AddTag(string key, string value) => _user.Call("addTag", key, value); + + public void AddTags(Dictionary tags) => _user.Call("addTags", tags.ToMap()); - public void AddTags(Dictionary tags) - => _user.Call("addTags", tags.ToMap()); + public void RemoveTag(string key) => _user.Call("removeTag", key); - public void RemoveTag(string key) - => _user.Call("removeTag", key); + public void RemoveTags(params string[] keys) => + _user.Call("removeTags", keys.ToArrayList()); - public void RemoveTags(params string[] keys) - => _user.Call("removeTags", keys.ToArrayList()); + public void AddAlias(string label, string id) => _user.Call("addAlias", label, id); - public void AddAlias(string label, string id) - => _user.Call("addAlias", label, id); + public void AddAliases(Dictionary aliases) => + _user.Call("addAliases", aliases.ToMap()); - public void AddAliases(Dictionary aliases) - => _user.Call("addAliases", aliases.ToMap()); + public void RemoveAlias(string label) => _user.Call("removeAlias", label); - public void RemoveAlias(string label) - => _user.Call("removeAlias", label); - - public void RemoveAliases(params string[] labels) - => _user.Call("removeAliases", labels.ToArrayList()); + public void RemoveAliases(params string[] labels) => + _user.Call("removeAliases", labels.ToArrayList()); - public void AddEmail(string email) - => _user.Call("addEmail", email); + public void AddEmail(string email) => _user.Call("addEmail", email); - public void RemoveEmail(string email) - => _user.Call("removeEmail", email); + public void RemoveEmail(string email) => _user.Call("removeEmail", email); - public void AddSms(string sms) - => _user.Call("addSms", sms); + public void AddSms(string sms) => _user.Call("addSms", sms); - public void RemoveSms(string sms) - => _user.Call("removeSms", sms); + public void RemoveSms(string sms) => _user.Call("removeSms", sms); - public void Initialize() { + public void Initialize() + { _user.Call("addObserver", new InternalUserChangedHandler(this)); _pushSubscription.Initialize(); } - private sealed class InternalUserChangedHandler : OneSignalAndroidJavaProxy { + private sealed class InternalUserChangedHandler : OneSignalAndroidJavaProxy + { private AndroidUserManager _parent; - public InternalUserChangedHandler(AndroidUserManager userManager) : base("user.state.IUserStateObserver") { + public InternalUserChangedHandler(AndroidUserManager userManager) + : base("user.state.IUserStateObserver") + { _parent = userManager; } /// UserChangedState - public void onUserStateChange(AndroidJavaObject state) { + public void onUserStateChange(AndroidJavaObject state) + { var currentJO = state.Call("getCurrent"); var current = currentJO.ToSerializable(); @@ -137,4 +142,4 @@ public void onUserStateChange(AndroidJavaObject state) { } } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/AssemblyInfo.cs b/com.onesignal.unity.android/Runtime/AssemblyInfo.cs index f6fe0ca41..90a876792 100644 --- a/com.onesignal.unity.android/Runtime/AssemblyInfo.cs +++ b/com.onesignal.unity.android/Runtime/AssemblyInfo.cs @@ -27,4 +27,4 @@ using UnityEngine.Scripting; -[assembly: AlwaysLinkAssembly] \ No newline at end of file +[assembly: AlwaysLinkAssembly] diff --git a/com.onesignal.unity.android/Runtime/OneSignalAndroid.cs b/com.onesignal.unity.android/Runtime/OneSignalAndroid.cs index db6f0102f..925569cca 100644 --- a/com.onesignal.unity.android/Runtime/OneSignalAndroid.cs +++ b/com.onesignal.unity.android/Runtime/OneSignalAndroid.cs @@ -27,32 +27,36 @@ using System.Collections.Generic; using System.Linq; -using UnityEngine; -using OneSignalSDK.Notifications; -using OneSignalSDK.InAppMessages; +using OneSignalSDK.Android.Debug; +using OneSignalSDK.Android.InAppMessages; +using OneSignalSDK.Android.LiveActivities; +using OneSignalSDK.Android.Location; +using OneSignalSDK.Android.Notifications; +using OneSignalSDK.Android.Session; +using OneSignalSDK.Android.User; using OneSignalSDK.Debug; using OneSignalSDK.Debug.Utilities; +using OneSignalSDK.InAppMessages; +using OneSignalSDK.LiveActivities; using OneSignalSDK.Location; +using OneSignalSDK.Notifications; using OneSignalSDK.Session; using OneSignalSDK.User; -using OneSignalSDK.LiveActivities; -using OneSignalSDK.Android.Notifications; -using OneSignalSDK.Android.InAppMessages; -using OneSignalSDK.Android.Debug; -using OneSignalSDK.Android.Location; -using OneSignalSDK.Android.Session; -using OneSignalSDK.Android.User; -using OneSignalSDK.Android.LiveActivities; +using UnityEngine; -namespace OneSignalSDK.Android { - public sealed partial class OneSignalAndroid : OneSignalPlatform { +namespace OneSignalSDK.Android +{ + public sealed partial class OneSignalAndroid : OneSignalPlatform + { private const string SDKPackage = "com.onesignal"; private const string SDKClassName = "OneSignal"; private const string QualifiedSDKClass = SDKPackage + "." + SDKClassName; private readonly AndroidJavaClass _sdkClass = new AndroidJavaClass(QualifiedSDKClass); - private readonly AndroidJavaClass _sdkWrapperClass = new AndroidJavaClass(SDKPackage + ".common.OneSignalWrapper"); + private readonly AndroidJavaClass _sdkWrapperClass = new AndroidJavaClass( + SDKPackage + ".common.OneSignalWrapper" + ); private static OneSignalAndroid _instance; @@ -67,8 +71,10 @@ public sealed partial class OneSignalAndroid : OneSignalPlatform { /// /// Used to provide a reference for the global callbacks /// - public OneSignalAndroid() { - if (_instance != null) { + public OneSignalAndroid() + { + if (_instance != null) + { SDKDebug.Error("Additional instance of OneSignalAndroid created."); return; } @@ -77,87 +83,105 @@ public OneSignalAndroid() { _debug = new AndroidDebugManager(_sdkClass); } - public override IUserManager User { + public override IUserManager User + { get => _user; } - public override ISessionManager Session { + public override ISessionManager Session + { get => _session; } - public override INotificationsManager Notifications { + public override INotificationsManager Notifications + { get => _notifications; } - public override ILocationManager Location { + public override ILocationManager Location + { get => _location; } - public override IInAppMessagesManager InAppMessages { + public override IInAppMessagesManager InAppMessages + { get => _inAppMessages; } - public override IDebugManager Debug { + public override IDebugManager Debug + { get => _debug; } - public override ILiveActivitiesManager LiveActivities { + public override ILiveActivitiesManager LiveActivities + { get => _liveActivities; } - public override bool ConsentGiven { + public override bool ConsentGiven + { set => _sdkClass.CallStatic("setConsentGiven", value); } - public override bool ConsentRequired { + public override bool ConsentRequired + { set => _sdkClass.CallStatic("setConsentRequired", value); } - public override void Initialize(string appId) { + public override void Initialize(string appId) + { var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); - var activity = unityPlayer.GetStatic("currentActivity"); + var activity = unityPlayer.GetStatic("currentActivity"); _sdkWrapperClass.CallStatic("setSdkType", "unity"); _sdkWrapperClass.CallStatic("setSdkVersion", VersionHeader); _sdkClass.CallStatic("initWithContext", activity, appId); - if (_inAppMessages == null) { + if (_inAppMessages == null) + { _inAppMessages = new AndroidInAppMessagesManager(_sdkClass); _inAppMessages.Initialize(); } - if (_notifications == null) { + if (_notifications == null) + { _notifications = new AndroidNotificationsManager(_sdkClass); _notifications.Initialize(); } - if (_user == null) { + if (_user == null) + { _user = new AndroidUserManager(_sdkClass); _user.Initialize(); } - if (_location == null) { + if (_location == null) + { _location = new AndroidLocationManager(_sdkClass); } - if (_session == null) { + if (_session == null) + { _session = new AndroidSessionManager(_sdkClass); } - if (_liveActivities == null) { + if (_liveActivities == null) + { _liveActivities = new AndroidLiveActivitiesManager(); } _completedInit(appId); } - public override void Login(string externalId, string jwtBearerToken = null) { + public override void Login(string externalId, string jwtBearerToken = null) + { _sdkClass.CallStatic("login", externalId, jwtBearerToken); } - public override void Logout() { + public override void Logout() + { _sdkClass.CallStatic("logout"); } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaObjectExtensions.cs b/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaObjectExtensions.cs index c80a29f36..4fca3fe78 100644 --- a/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaObjectExtensions.cs +++ b/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaObjectExtensions.cs @@ -29,16 +29,19 @@ using UnityEngine; // ReSharper disable InconsistentNaming -namespace OneSignalSDK.Android.Utilities { +namespace OneSignalSDK.Android.Utilities +{ /// /// Conversion methods for common Java types wrapped by /// - internal static class AndroidJavaObjectExtensions { + internal static class AndroidJavaObjectExtensions + { /// /// Converts from a Java class which implements a toJSONObject method which returns a JSONObject representation /// of that object to a Serializable class in Unity /// - public static TModel ToSerializable(this AndroidJavaObject source) { + public static TModel ToSerializable(this AndroidJavaObject source) + { if (source == default) return default; @@ -48,94 +51,127 @@ public static TModel ToSerializable(this AndroidJavaObject source) { return serialized; } - + /* * JSONObject */ - + /// /// Converts from a Java org.json.JSONObject to a /// - public static Dictionary JSONObjectToDictionary(this AndroidJavaObject source) - => source != null ? Json.Deserialize(source.Call("toString")) as Dictionary : null; + public static Dictionary JSONObjectToDictionary( + this AndroidJavaObject source + ) => + source != null + ? Json.Deserialize(source.Call("toString")) as Dictionary + : null; /// /// Converts from a to a Java org.json.JSONObject /// - public static AndroidJavaObject ToJSONObject(this Dictionary source) - => new AndroidJavaObject("org.json.JSONObject", Json.Serialize(source)); - + public static AndroidJavaObject ToJSONObject( + this Dictionary source + ) => new AndroidJavaObject("org.json.JSONObject", Json.Serialize(source)); + /* * Map */ - + /// /// Converts from a Java java.util.Map to a /// - public static Dictionary MapToDictionary(this AndroidJavaObject source) { + public static Dictionary MapToDictionary(this AndroidJavaObject source) + { if (source == null) return null; - + var entries = source.Call("entrySet"); var iter = entries.Call("iterator"); var ret = new Dictionary(); - while (iter.Call("hasNext")) { + while (iter.Call("hasNext")) + { var entry = iter.Call("next"); var key = entry.Call("getKey"); var valueJO = entry.Call("getValue"); - + ret[key] = valueJO.Call("toString"); } - + return ret; } /// /// Converts from a to a Java java.util.Map /// - public static AndroidJavaObject ToMap(this Dictionary source) { + public static AndroidJavaObject ToMap(this Dictionary source) + { var map = new AndroidJavaObject("java.util.HashMap"); - var put = AndroidJNIHelper.GetMethodID(map.GetRawClass(), "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); + var put = AndroidJNIHelper.GetMethodID( + map.GetRawClass(), + "put", + "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;" + ); var entryArgs = new object[2]; - foreach (var kv in source) { + foreach (var kv in source) + { using (var key = new AndroidJavaObject("java.lang.String", kv.Key)) - using (var value = new AndroidJavaObject("java.lang.String", kv.Value)) { + using (var value = new AndroidJavaObject("java.lang.String", kv.Value)) + { entryArgs[0] = key; entryArgs[1] = value; - AndroidJNI.CallObjectMethod(map.GetRawObject(), put, AndroidJNIHelper.CreateJNIArgArray(entryArgs)); + AndroidJNI.CallObjectMethod( + map.GetRawObject(), + put, + AndroidJNIHelper.CreateJNIArgArray(entryArgs) + ); } } return map; } - public static AndroidJavaObject ToMap(this Dictionary source) { + public static AndroidJavaObject ToMap(this Dictionary source) + { var map = new AndroidJavaObject("java.util.HashMap"); - var put = AndroidJNIHelper.GetMethodID(map.GetRawClass(), "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); + var put = AndroidJNIHelper.GetMethodID( + map.GetRawClass(), + "put", + "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;" + ); var entryArgs = new object[2]; - foreach (var kv in source) { + foreach (var kv in source) + { var key = new AndroidJavaObject("java.lang.String", kv.Key); - var value = new AndroidJavaClass("java.lang.String").CallStatic("valueOf", kv.Value); + var value = new AndroidJavaClass("java.lang.String").CallStatic( + "valueOf", + kv.Value + ); entryArgs[0] = key; entryArgs[1] = value; - AndroidJNI.CallObjectMethod(map.GetRawObject(), put, AndroidJNIHelper.CreateJNIArgArray(entryArgs)); + AndroidJNI.CallObjectMethod( + map.GetRawObject(), + put, + AndroidJNIHelper.CreateJNIArgArray(entryArgs) + ); } return map; } - public static AndroidJavaObject ToArrayList(this string[] keys) { + public static AndroidJavaObject ToArrayList(this string[] keys) + { AndroidJavaObject arrayList = new AndroidJavaObject("java.util.ArrayList"); - foreach(string key in keys) { + foreach (string key in keys) + { arrayList.Call("add", key); } return arrayList; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaProxy.cs b/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaProxy.cs index 08c639fbc..6fdb094f0 100644 --- a/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaProxy.cs +++ b/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaProxy.cs @@ -1,29 +1,35 @@ -using UnityEngine; using System; -using Laters; using System.Runtime.CompilerServices; using System.Threading.Tasks; +using Laters; +using UnityEngine; -namespace OneSignalSDK.Android.Utilities { - public abstract class OneSignalAndroidJavaProxy : AndroidJavaProxy { +namespace OneSignalSDK.Android.Utilities +{ + public abstract class OneSignalAndroidJavaProxy : AndroidJavaProxy + { private const string SDKPackage = "com.onesignal"; protected OneSignalAndroidJavaProxy(string listenerClassName) : base(SDKPackage + "." + listenerClassName) { } } - - public abstract class OneSignalAwaitableAndroidJavaProxy : AwaitableAndroidJavaProxy { + + public abstract class OneSignalAwaitableAndroidJavaProxy + : AwaitableAndroidJavaProxy + { private const string SDKPackage = "com.onesignal"; protected OneSignalAwaitableAndroidJavaProxy(string listenerClassName) : base(SDKPackage + "." + listenerClassName) { } } - public sealed class Continuation { + public sealed class Continuation + { public AndroidJavaObject Proxy { get; } private AndroidConsumer _consumer; - public Continuation() { + public Continuation() + { var continuation = new AndroidJavaClass("com.onesignal.Continue"); _consumer = new AndroidConsumer(); Proxy = continuation.CallStatic("with", _consumer); @@ -32,30 +38,41 @@ public Continuation() { public TaskAwaiter GetAwaiter() => _consumer.GetAwaiter(); } - public sealed class AndroidConsumer : AwaitableAndroidJavaProxy { - public AndroidConsumer() : base("java.util.function.Consumer") { } + public sealed class AndroidConsumer : AwaitableAndroidJavaProxy + { + public AndroidConsumer() + : base("java.util.function.Consumer") { } - public void accept(AndroidJavaObject obj) { + public void accept(AndroidJavaObject obj) + { var result = obj.Call("isSuccess"); - if (result) { + if (result) + { _complete(null); - } else { + } + else + { var throwable = obj.Call("getThrowable"); - if (throwable != null) { + if (throwable != null) + { _fail(throwable.Call("getMessage")); - } else { + } + else + { _fail("error with async method"); } } } } - public sealed class BoolContinuation { + public sealed class BoolContinuation + { public AndroidJavaObject Proxy { get; } private AndroidBoolConsumer _consumer; - public BoolContinuation() { + public BoolContinuation() + { var continuation = new AndroidJavaClass("com.onesignal.Continue"); _consumer = new AndroidBoolConsumer(); Proxy = continuation.CallStatic("with", _consumer); @@ -64,17 +81,23 @@ public BoolContinuation() { public TaskAwaiter GetAwaiter() => _consumer.GetAwaiter(); } - public sealed class AndroidBoolConsumer : AwaitableAndroidJavaProxy { - public AndroidBoolConsumer() : base("java.util.function.Consumer") { } + public sealed class AndroidBoolConsumer : AwaitableAndroidJavaProxy + { + public AndroidBoolConsumer() + : base("java.util.function.Consumer") { } - public void accept(AndroidJavaObject obj) { + public void accept(AndroidJavaObject obj) + { var result = obj.Call("isSuccess"); - if (result) { + if (result) + { var data = obj.Call("getData"); var value = data.Call("booleanValue"); _complete(value); - } else { + } + else + { var throwable = obj.Call("getThrowable"); if (throwable != null) _fail(throwable.Call("getMessage")); diff --git a/com.onesignal.unity.android/Runtime/Utilities/AwaitableAndroidJavaProxy.cs b/com.onesignal.unity.android/Runtime/Utilities/AwaitableAndroidJavaProxy.cs index 9a41cbffc..4a5654094 100644 --- a/com.onesignal.unity.android/Runtime/Utilities/AwaitableAndroidJavaProxy.cs +++ b/com.onesignal.unity.android/Runtime/Utilities/AwaitableAndroidJavaProxy.cs @@ -3,14 +3,17 @@ using System.Threading.Tasks; using UnityEngine; -namespace Laters { - public abstract class AwaitableAndroidJavaProxy : AndroidJavaProxy { - public TaskAwaiter GetAwaiter() { +namespace Laters +{ + public abstract class AwaitableAndroidJavaProxy : AndroidJavaProxy + { + public TaskAwaiter GetAwaiter() + { if (_completionSource != null) return _completionSource.Task.GetAwaiter(); - + _completionSource = new TaskCompletionSource(); - + if (_isComplete) _setResult(); else @@ -18,13 +21,17 @@ public TaskAwaiter GetAwaiter() { return _completionSource.Task.GetAwaiter(); } - + protected bool _isComplete = false; - - protected AwaitableAndroidJavaProxy(string javaInterface) : base(javaInterface) {} - protected AwaitableAndroidJavaProxy(AndroidJavaClass javaInterface) : base(javaInterface) {} - protected void _complete(TResult result) { + protected AwaitableAndroidJavaProxy(string javaInterface) + : base(javaInterface) { } + + protected AwaitableAndroidJavaProxy(AndroidJavaClass javaInterface) + : base(javaInterface) { } + + protected void _complete(TResult result) + { if (_isComplete) return; @@ -37,27 +44,33 @@ protected void _complete(TResult result) { toComplete?.Invoke(_result); } - protected void _fail(string error, bool except = false) { - if (except) { + protected void _fail(string error, bool except = false) + { + if (except) + { var exception = new Exception(error); Debug.LogException(exception); _completionSource.TrySetException(exception); } - else { + else + { Debug.LogError(error); _completionSource.TrySetCanceled(); } } - private void _setResult() { - try { + private void _setResult() + { + try + { _completionSource.TrySetResult(_result); } - catch (ObjectDisposedException e) { + catch (ObjectDisposedException e) + { Debug.Log(e.Message); } } - + private TaskCompletionSource _completionSource; private event Action _onComplete; private TResult _result; @@ -66,17 +79,22 @@ private void _setResult() { /// /// Helper which will autocomplete the awaited task when a callback is invoked /// - public abstract class AwaitableVoidAndroidJavaProxy : AwaitableAndroidJavaProxy { - protected AwaitableVoidAndroidJavaProxy(string javaInterface) : base(javaInterface) {} - protected AwaitableVoidAndroidJavaProxy(AndroidJavaClass javaInterface) : base(javaInterface) {} + public abstract class AwaitableVoidAndroidJavaProxy : AwaitableAndroidJavaProxy + { + protected AwaitableVoidAndroidJavaProxy(string javaInterface) + : base(javaInterface) { } + + protected AwaitableVoidAndroidJavaProxy(AndroidJavaClass javaInterface) + : base(javaInterface) { } - public override AndroidJavaObject Invoke(string methodName, object[] args) { + public override AndroidJavaObject Invoke(string methodName, object[] args) + { var invokeResult = base.Invoke(methodName, args); - + if (_isComplete == false) _complete(null); - + return invokeResult; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Platform/DebugManager.cs b/com.onesignal.unity.core/Editor/Platform/DebugManager.cs index 041d77a0b..c366c49f9 100644 --- a/com.onesignal.unity.core/Editor/Platform/DebugManager.cs +++ b/com.onesignal.unity.core/Editor/Platform/DebugManager.cs @@ -27,9 +27,11 @@ using OneSignalSDK.Debug.Models; -namespace OneSignalSDK.Debug { - internal sealed class DebugManager : IDebugManager { +namespace OneSignalSDK.Debug +{ + internal sealed class DebugManager : IDebugManager + { public LogLevel LogLevel { get; set; } public LogLevel AlertLevel { get; set; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Platform/InAppMessagesManager.cs b/com.onesignal.unity.core/Editor/Platform/InAppMessagesManager.cs index ea5165322..d28a8908a 100644 --- a/com.onesignal.unity.core/Editor/Platform/InAppMessagesManager.cs +++ b/com.onesignal.unity.core/Editor/Platform/InAppMessagesManager.cs @@ -29,8 +29,10 @@ using System.Collections.Generic; #pragma warning disable 0067 // the event 'x' is never used -namespace OneSignalSDK.InAppMessages { - internal sealed class InAppMessagesManager : IInAppMessagesManager { +namespace OneSignalSDK.InAppMessages +{ + internal sealed class InAppMessagesManager : IInAppMessagesManager + { public event EventHandler WillDisplay; public event EventHandler DidDisplay; public event EventHandler WillDismiss; @@ -39,24 +41,14 @@ internal sealed class InAppMessagesManager : IInAppMessagesManager { public bool Paused { get; set; } - public void AddTrigger(string key, string value) { + public void AddTrigger(string key, string value) { } - } + public void AddTriggers(Dictionary triggers) { } - public void AddTriggers(Dictionary triggers) { + public void RemoveTrigger(string key) { } - } + public void RemoveTriggers(params string[] keys) { } - public void RemoveTrigger(string key) { - - } - - public void RemoveTriggers(params string[] keys) { - - } - - public void ClearTriggers() { - - } + public void ClearTriggers() { } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Platform/LiveActivitiesManager.cs b/com.onesignal.unity.core/Editor/Platform/LiveActivitiesManager.cs index a1034dc86..f51b896cb 100644 --- a/com.onesignal.unity.core/Editor/Platform/LiveActivitiesManager.cs +++ b/com.onesignal.unity.core/Editor/Platform/LiveActivitiesManager.cs @@ -28,34 +28,30 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace OneSignalSDK.LiveActivities { - internal sealed class LiveActivitiesManager : ILiveActivitiesManager { - public Task EnterAsync(string activityId, string token) { - return Task.FromResult(false); - } - - public Task ExitAsync(string activityId) { - return Task.FromResult(false); - } - - public void RemovePushToStartToken(string activityType) +namespace OneSignalSDK.LiveActivities +{ + internal sealed class LiveActivitiesManager : ILiveActivitiesManager + { + public Task EnterAsync(string activityId, string token) { - + return Task.FromResult(false); } - public void SetPushToStartToken(string activityType, string token) + public Task ExitAsync(string activityId) { - + return Task.FromResult(false); } - public void SetupDefault(LiveActivitySetupOptions options = null) - { + public void RemovePushToStartToken(string activityType) { } - } + public void SetPushToStartToken(string activityType, string token) { } - public void StartDefault(string activityId, IDictionary attributes, IDictionary content) - { + public void SetupDefault(LiveActivitySetupOptions options = null) { } - } + public void StartDefault( + string activityId, + IDictionary attributes, + IDictionary content + ) { } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Platform/LocationManager.cs b/com.onesignal.unity.core/Editor/Platform/LocationManager.cs index 04cbc1c87..0349da84a 100644 --- a/com.onesignal.unity.core/Editor/Platform/LocationManager.cs +++ b/com.onesignal.unity.core/Editor/Platform/LocationManager.cs @@ -27,12 +27,12 @@ using System.Threading.Tasks; -namespace OneSignalSDK.Location { - internal sealed class LocationManager : ILocationManager { +namespace OneSignalSDK.Location +{ + internal sealed class LocationManager : ILocationManager + { public bool IsShared { get; set; } - public void RequestPermission() { - - } + public void RequestPermission() { } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Platform/NotificationsManager.cs b/com.onesignal.unity.core/Editor/Platform/NotificationsManager.cs index 515aecd29..9f1c0073f 100644 --- a/com.onesignal.unity.core/Editor/Platform/NotificationsManager.cs +++ b/com.onesignal.unity.core/Editor/Platform/NotificationsManager.cs @@ -30,8 +30,10 @@ using OneSignalSDK.Notifications.Models; #pragma warning disable 0067 // the event 'x' is never used -namespace OneSignalSDK.Notifications { - internal sealed class NotificationsManager : INotificationsManager { +namespace OneSignalSDK.Notifications +{ + internal sealed class NotificationsManager : INotificationsManager + { public event EventHandler ForegroundWillDisplay; public event EventHandler Clicked; public event EventHandler PermissionChanged; @@ -42,12 +44,11 @@ internal sealed class NotificationsManager : INotificationsManager { public NotificationPermission PermissionNative { get; } - public Task RequestPermissionAsync(bool fallbackToSettings){ + public Task RequestPermissionAsync(bool fallbackToSettings) + { return Task.FromResult(false); } - public void ClearAllNotifications() { - - } + public void ClearAllNotifications() { } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Platform/OneSignalNative.cs b/com.onesignal.unity.core/Editor/Platform/OneSignalNative.cs index 18b2bb70c..84cd07c61 100755 --- a/com.onesignal.unity.core/Editor/Platform/OneSignalNative.cs +++ b/com.onesignal.unity.core/Editor/Platform/OneSignalNative.cs @@ -27,20 +27,22 @@ using System.Collections.Generic; using System.Threading.Tasks; -using OneSignalSDK.Notifications; -using OneSignalSDK.InAppMessages; using OneSignalSDK.Debug; using OneSignalSDK.Debug.Utilities; +using OneSignalSDK.InAppMessages; +using OneSignalSDK.LiveActivities; using OneSignalSDK.Location; +using OneSignalSDK.Notifications; using OneSignalSDK.Session; using OneSignalSDK.User; -using OneSignalSDK.LiveActivities; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Implementationless variation of the OneSignal SDK so that it "runs" in the Editor /// - internal sealed class OneSignalNative : OneSignalPlatform { + internal sealed class OneSignalNative : OneSignalPlatform + { private UserManager _user = new UserManager(); private SessionManager _session = new SessionManager(); private NotificationsManager _notifications = new NotificationsManager(); @@ -51,59 +53,68 @@ internal sealed class OneSignalNative : OneSignalPlatform { private bool _consentGiven; private bool _consentRequired; - public override IUserManager User { + public override IUserManager User + { get => _user; } - - public override ISessionManager Session { + + public override ISessionManager Session + { get => _session; } - - public override INotificationsManager Notifications { + + public override INotificationsManager Notifications + { get => _notifications; } - - public override ILocationManager Location { + + public override ILocationManager Location + { get => _location; } - public override IInAppMessagesManager InAppMessages { + public override IInAppMessagesManager InAppMessages + { get => _inAppMessages; } - public override IDebugManager Debug { + public override IDebugManager Debug + { get => _debug; } - public override ILiveActivitiesManager LiveActivities { + public override ILiveActivitiesManager LiveActivities + { get => _liveActivities; } - public override bool ConsentGiven { + public override bool ConsentGiven + { set => _consentGiven = value; } - public override bool ConsentRequired { + public override bool ConsentRequired + { set => _consentRequired = value; } - public override void Initialize(string appId) { - if (string.IsNullOrEmpty(appId)) { + public override void Initialize(string appId) + { + if (string.IsNullOrEmpty(appId)) + { SDKDebug.Error("appId is null or empty"); return; } _init(appId); - SDKDebug.Warn("Native SDK is a placeholder. Please run on supported platform (iOS or Android)."); - } - - public override void Login(string externalId, string jwtBearerToken = null) { - + SDKDebug.Warn( + "Native SDK is a placeholder. Please run on supported platform (iOS or Android)." + ); } - public override void Logout() { + public override void Login(string externalId, string jwtBearerToken = null) { } - } + public override void Logout() { } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Platform/PushSubscription.cs b/com.onesignal.unity.core/Editor/Platform/PushSubscription.cs index afb1fb706..42e47847f 100644 --- a/com.onesignal.unity.core/Editor/Platform/PushSubscription.cs +++ b/com.onesignal.unity.core/Editor/Platform/PushSubscription.cs @@ -27,22 +27,20 @@ using System; #pragma warning disable 0067 // the event 'x' is never used -namespace OneSignalSDK.User.Models { - internal sealed class PushSubscription : IPushSubscription { +namespace OneSignalSDK.User.Models +{ + internal sealed class PushSubscription : IPushSubscription + { public event EventHandler Changed; public string Id { get; } public string Token { get; } - public bool OptedIn { get; } + public bool OptedIn { get; } - public void OptIn() { + public void OptIn() { } - } - - public void OptOut() { - - } + public void OptOut() { } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Platform/SessionManager.cs b/com.onesignal.unity.core/Editor/Platform/SessionManager.cs index 61f21b719..390322da2 100644 --- a/com.onesignal.unity.core/Editor/Platform/SessionManager.cs +++ b/com.onesignal.unity.core/Editor/Platform/SessionManager.cs @@ -25,18 +25,14 @@ * THE SOFTWARE. */ -namespace OneSignalSDK.Session { - internal sealed class SessionManager : ISessionManager { - public void AddOutcome(string name) { +namespace OneSignalSDK.Session +{ + internal sealed class SessionManager : ISessionManager + { + public void AddOutcome(string name) { } - } + public void AddUniqueOutcome(string name) { } - public void AddUniqueOutcome(string name) { - - } - - public void AddOutcomeWithValue(string name, float value) { - - } + public void AddOutcomeWithValue(string name, float value) { } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Platform/UserManager.cs b/com.onesignal.unity.core/Editor/Platform/UserManager.cs index f5c446d0a..27fb9cee9 100644 --- a/com.onesignal.unity.core/Editor/Platform/UserManager.cs +++ b/com.onesignal.unity.core/Editor/Platform/UserManager.cs @@ -29,13 +29,17 @@ using System.Collections.Generic; using OneSignalSDK.User.Models; -namespace OneSignalSDK.User { - internal sealed class UserManager : IUserManager { - public string OneSignalId { +namespace OneSignalSDK.User +{ + internal sealed class UserManager : IUserManager + { + public string OneSignalId + { get => null; } - public string ExternalId { + public string ExternalId + { get => null; } @@ -43,66 +47,43 @@ public string ExternalId { private PushSubscription _subscription = new PushSubscription(); - public IPushSubscription PushSubscription { + public IPushSubscription PushSubscription + { get => _subscription; } - public string Language { - set { - - } + public string Language + { + set { } } - public Dictionary GetTags() { + public Dictionary GetTags() + { return new Dictionary(); } - public void AddTag(string key, string value){ + public void AddTag(string key, string value) { } - } + public void AddTags(Dictionary tags) { } - public void AddTags(Dictionary tags) { + public void RemoveTag(string key) { } - } + public void RemoveTags(params string[] keys) { } - public void RemoveTag(string key) { + public void AddAlias(string label, string id) { } - } + public void AddAliases(Dictionary aliases) { } - public void RemoveTags(params string[] keys) { + public void RemoveAlias(string label) { } - } + public void RemoveAliases(params string[] labels) { } - public void AddAlias(string label, string id) { + public void AddEmail(string email) { } - } + public void RemoveEmail(string email) { } - public void AddAliases(Dictionary aliases) { + public void AddSms(string sms) { } - } - - public void RemoveAlias(string label) { - - } - - public void RemoveAliases(params string[] labels) { - - } - - public void AddEmail(string email) { - - } - - public void RemoveEmail(string email) { - - } - - public void AddSms(string sms) { - - } - - public void RemoveSms(string sms) { - - } + public void RemoveSms(string sms) { } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Setup/OneSignalSetupStep.cs b/com.onesignal.unity.core/Editor/Setup/OneSignalSetupStep.cs index 85f427c36..6e3f01032 100644 --- a/com.onesignal.unity.core/Editor/Setup/OneSignalSetupStep.cs +++ b/com.onesignal.unity.core/Editor/Setup/OneSignalSetupStep.cs @@ -25,11 +25,13 @@ * THE SOFTWARE. */ -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Abstract class which must be inherited from in order to create a new setup step /// - public abstract class OneSignalSetupStep { + public abstract class OneSignalSetupStep + { /// /// Short description of what this step will do /// @@ -51,12 +53,14 @@ public abstract class OneSignalSetupStep { /// /// The result is cached and only reset on run or specific other conditions /// - public bool IsStepCompleted { - get { + public bool IsStepCompleted + { + get + { if (!_shouldCheckForCompletion) return _isComplete; - _isComplete = _getIsStepCompleted(); + _isComplete = _getIsStepCompleted(); _shouldCheckForCompletion = false; return _isComplete; @@ -66,7 +70,8 @@ public bool IsStepCompleted { /// /// Runs all code necessary in order to fulfill the step /// - public void RunStep() { + public void RunStep() + { if (IsStepCompleted) return; @@ -80,4 +85,4 @@ public void RunStep() { private bool _isComplete = false; protected bool _shouldCheckForCompletion = true; } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Setup/OneSignalSetupWindow.cs b/com.onesignal.unity.core/Editor/Setup/OneSignalSetupWindow.cs index e7d87cd05..cb9750d9f 100644 --- a/com.onesignal.unity.core/Editor/Setup/OneSignalSetupWindow.cs +++ b/com.onesignal.unity.core/Editor/Setup/OneSignalSetupWindow.cs @@ -30,18 +30,23 @@ using UnityEditor; using UnityEngine; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Pop up window which displays any additional required or optional setup steps by the SDK /// - public sealed class OneSignalSetupWindow : EditorWindow { - [MenuItem("Window/OneSignal SDK Setup")] public static void ShowWindow() { + public sealed class OneSignalSetupWindow : EditorWindow + { + [MenuItem("Window/OneSignal SDK Setup")] + public static void ShowWindow() + { var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); window.minSize = _minSize; window.Show(); } - public static void CloseWindow() { + public static void CloseWindow() + { var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); window.Close(); } @@ -49,7 +54,8 @@ public static void CloseWindow() { private static readonly Vector2 _minSize = new Vector2(300, 400); private const string _title = "OneSignal SDK Setup"; - private const string _description = "Additional steps required to get the OneSignal Unity SDK up and running"; + private const string _description = + "Additional steps required to get the OneSignal Unity SDK up and running"; private IReadOnlyList _setupSteps; private readonly Queue _stepsToRun = new Queue(); @@ -65,21 +71,28 @@ public static void CloseWindow() { private Vector2 _scrollPosition; - private void OnEnable() { - var stepTypes = ReflectionHelpers.FindAllAssignableTypes("OneSignal"); - var steps = new List(); + private void OnEnable() + { + var stepTypes = ReflectionHelpers.FindAllAssignableTypes( + "OneSignal" + ); + var steps = new List(); - foreach (var stepType in stepTypes) { + foreach (var stepType in stepTypes) + { if (Activator.CreateInstance(stepType) is OneSignalSetupStep step) steps.Add(step); else - UnityEngine.Debug.LogWarning($"could not create setup step from type {stepType.Name}"); + UnityEngine.Debug.LogWarning( + $"could not create setup step from type {stepType.Name}" + ); } _setupSteps = steps; } - private void OnGUI() { + private void OnGUI() + { _setupGUI(); GUILayout.Label(_description); @@ -88,13 +101,15 @@ private void OnGUI() { if (_setupSteps == null) return; - var willDisableControls = _stepsToRun.Count > 0 + var willDisableControls = + _stepsToRun.Count > 0 || EditorApplication.isUpdating || EditorApplication.isCompiling; EditorGUI.BeginDisabledGroup(willDisableControls); - if (GUILayout.Button("Run All Steps")) { + if (GUILayout.Button("Run All Steps")) + { foreach (var step in _setupSteps) _stepsToRun.Enqueue(step); } @@ -107,11 +122,12 @@ private void OnGUI() { EditorGUILayout.BeginHorizontal(); _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); - foreach (var step in _setupSteps) { + foreach (var step in _setupSteps) + { EditorGUILayout.BeginHorizontal(); var sumContent = new GUIContent(step.Summary); - var sumRect = GUILayoutUtility.GetRect(sumContent, _summaryStyle); + var sumRect = GUILayoutUtility.GetRect(sumContent, _summaryStyle); var checkRect = new Rect(sumRect.x, sumRect.y, sumRect.height, sumRect.height); GUI.DrawTexture(checkRect, step.IsStepCompleted ? _checkTexture : _boxTexture); @@ -142,10 +158,12 @@ private void OnGUI() { EditorGUILayout.EndHorizontal(); } - private void OnInspectorUpdate() { + private void OnInspectorUpdate() + { var runnerCount = _stepsToRun.Count + 1.0f; - while (_stepsToRun.Count > 0) { + while (_stepsToRun.Count > 0) + { var step = _stepsToRun.Dequeue(); EditorUtility.DisplayProgressBar( @@ -160,24 +178,25 @@ private void OnInspectorUpdate() { EditorUtility.ClearProgressBar(); } - private void _setupGUI() { + private void _setupGUI() + { if (_guiSetupComplete) return; _summaryStyle = EditorStyles.boldLabel; - _detailsStyle = new GUIStyle(GUI.skin.textField); + _detailsStyle = new GUIStyle(GUI.skin.textField); _detailsStyle.wordWrap = true; - _runStyle = new GUIStyle(GUI.skin.button); + _runStyle = new GUIStyle(GUI.skin.button); _runStyle.fixedWidth = _minSize.x * .3f; - _requiredStyle = new GUIStyle(EditorStyles.miniBoldLabel); + _requiredStyle = new GUIStyle(EditorStyles.miniBoldLabel); _requiredStyle.normal.textColor = Color.red; - _optionalStyle = new GUIStyle(EditorStyles.miniBoldLabel); + _optionalStyle = new GUIStyle(EditorStyles.miniBoldLabel); _optionalStyle.normal.textColor = Color.yellow; - _optionalStyle.fontStyle = FontStyle.Italic; + _optionalStyle.fontStyle = FontStyle.Italic; var checkContent = EditorGUIUtility.IconContent("TestPassed"); _checkTexture = checkContent.image; @@ -188,4 +207,4 @@ private void _setupGUI() { _guiSetupComplete = true; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/SetupSteps/InstallEdm4uStep.cs b/com.onesignal.unity.core/Editor/SetupSteps/InstallEdm4uStep.cs index 0c3f6f05f..5222695c6 100644 --- a/com.onesignal.unity.core/Editor/SetupSteps/InstallEdm4uStep.cs +++ b/com.onesignal.unity.core/Editor/SetupSteps/InstallEdm4uStep.cs @@ -25,32 +25,34 @@ * THE SOFTWARE. */ -using System.Linq; -using UnityEditor.Compilation; using System; using System.IO; -using System.Text.RegularExpressions; +using System.Linq; using System.Reflection; +using System.Text.RegularExpressions; using OneSignalSDK.Debug.Utilities; +using UnityEditor.Compilation; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Checks for EDM4U assemblies and installs the package from its github releases /// - public sealed class InstallEdm4uStep : OneSignalSetupStep { - public override string Summary - => $"Install EDM4U {_edm4UVersion}"; + public sealed class InstallEdm4uStep : OneSignalSetupStep + { + public override string Summary => $"Install EDM4U {_edm4UVersion}"; - public override string Details - => $"Downloads and imports version {_edm4UVersion} from Google's repo. This library resolves dependencies " + - $"among included libraries on Android."; + public override string Details => + $"Downloads and imports version {_edm4UVersion} from Google's repo. This library resolves dependencies " + + $"among included libraries on Android."; - public override bool IsRequired - => true; + public override bool IsRequired => true; - private Version _getAssetsEDM4UVersion() { - var isInstalled = CompilationPipeline.GetPrecompiledAssemblyNames() - .Any(assemblyName => assemblyName.StartsWith("Google.VersionHandler")); + private Version _getAssetsEDM4UVersion() + { + var isInstalled = CompilationPipeline + .GetPrecompiledAssemblyNames() + .Any(assemblyName => assemblyName.StartsWith("Google.VersionHandler")); if (!isInstalled) return null; @@ -63,13 +65,19 @@ private Version _getAssetsEDM4UVersion() { FileInfo[] files; - try { - files = directoryInfo.GetFiles("external-dependency-manager_version-*_manifest.txt"); - } catch (Exception) { + try + { + files = directoryInfo.GetFiles( + "external-dependency-manager_version-*_manifest.txt" + ); + } + catch (Exception) + { return null; } - if (files.Length != 1) { + if (files.Length != 1) + { return null; } @@ -81,8 +89,11 @@ private Version _getAssetsEDM4UVersion() { return version; } - private Version _getPackagesEDM4UVersion() { - var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.GetName().Name.StartsWith("Google.PackageManagerResolver")); + private Version _getPackagesEDM4UVersion() + { + var assembly = AppDomain + .CurrentDomain.GetAssemblies() + .FirstOrDefault(x => x.GetName().Name.StartsWith("Google.PackageManagerResolver")); if (assembly == null) return null; @@ -98,12 +109,14 @@ private Version _getPackagesEDM4UVersion() { return version; } - protected override bool _getIsStepCompleted() { + protected override bool _getIsStepCompleted() + { var version = _getAssetsEDM4UVersion(); if (version == null) version = _getPackagesEDM4UVersion(); - if (version == null) { + if (version == null) + { SDKDebug.Warn("EDM4U version number could not be determined."); return false; } @@ -113,17 +126,23 @@ protected override bool _getIsStepCompleted() { return version >= expectedVersion; } - protected override void _runStep() { + protected override void _runStep() + { const string msg = "Downloading Google External Dependency Manager"; - UnityPackageInstaller.DownloadAndInstall(_edm4UPackageDownloadUrl, msg, result => { - if (result) - _shouldCheckForCompletion = true; - }); + UnityPackageInstaller.DownloadAndInstall( + _edm4UPackageDownloadUrl, + msg, + result => + { + if (result) + _shouldCheckForCompletion = true; + } + ); } private const string _edm4UVersion = "1.2.177"; - private static readonly string _edm4UPackageDownloadUrl - = $"https://github.com/googlesamples/unity-jar-resolver/blob/v{_edm4UVersion}/external-dependency-manager-{_edm4UVersion}.unitypackage?raw=true"; + private static readonly string _edm4UPackageDownloadUrl = + $"https://github.com/googlesamples/unity-jar-resolver/blob/v{_edm4UVersion}/external-dependency-manager-{_edm4UVersion}.unitypackage?raw=true"; } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/SetupSteps/LinkXMLStep.cs b/com.onesignal.unity.core/Editor/SetupSteps/LinkXMLStep.cs index e31567330..da85392ca 100644 --- a/com.onesignal.unity.core/Editor/SetupSteps/LinkXMLStep.cs +++ b/com.onesignal.unity.core/Editor/SetupSteps/LinkXMLStep.cs @@ -27,35 +27,40 @@ using System.IO; -namespace OneSignalSDK { -/// -/// Makes sure that the link.xml file for the OneSignal SDK exists -/// -public class LinkXMLStep : OneSignalSetupStep { - public override string Summary - => "Generate link.xml"; - - public override string Details - => $"Generates the link.xml file at {_destinationPath} which is needed to prevent OneSignal classes from being " + - $"removed by Unity's code stripping."; - - public override bool IsRequired - => true; - - protected override bool _getIsStepCompleted() - => File.Exists(_destinationPath); - - protected override void _runStep() { - if (!Directory.Exists(_destinationDir)) - Directory.CreateDirectory(_destinationDir); - - if (!File.Exists(_destinationPath)) - File.Copy(_sourcePath, _destinationPath); - } - - private static readonly string _destinationDir = Path.Combine("Assets", "OneSignal"); - - private static readonly string _sourcePath = Path.Combine("Packages", "com.onesignal.unity.core", "Editor", "link.xml"); - private static readonly string _destinationPath = Path.Combine(_destinationDir, "link.xml"); +namespace OneSignalSDK +{ + /// + /// Makes sure that the link.xml file for the OneSignal SDK exists + /// + public class LinkXMLStep : OneSignalSetupStep + { + public override string Summary => "Generate link.xml"; + + public override string Details => + $"Generates the link.xml file at {_destinationPath} which is needed to prevent OneSignal classes from being " + + $"removed by Unity's code stripping."; + + public override bool IsRequired => true; + + protected override bool _getIsStepCompleted() => File.Exists(_destinationPath); + + protected override void _runStep() + { + if (!Directory.Exists(_destinationDir)) + Directory.CreateDirectory(_destinationDir); + + if (!File.Exists(_destinationPath)) + File.Copy(_sourcePath, _destinationPath); + } + + private static readonly string _destinationDir = Path.Combine("Assets", "OneSignal"); + + private static readonly string _sourcePath = Path.Combine( + "Packages", + "com.onesignal.unity.core", + "Editor", + "link.xml" + ); + private static readonly string _destinationPath = Path.Combine(_destinationDir, "link.xml"); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/SetupSteps/SyncCodeBundleStep.cs b/com.onesignal.unity.core/Editor/SetupSteps/SyncCodeBundleStep.cs index 3f693f692..80d9aea3f 100644 --- a/com.onesignal.unity.core/Editor/SetupSteps/SyncCodeBundleStep.cs +++ b/com.onesignal.unity.core/Editor/SetupSteps/SyncCodeBundleStep.cs @@ -1,6 +1,6 @@ /* * Modified MIT License -* +* * Copyright 2023 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy @@ -9,13 +9,13 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: -* +* * 1. The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. -* +* * 2. All copies of substantial portions of the Software may only be used in connection * with services provided by OneSignal. -* +* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -29,23 +29,25 @@ using System.IO; using UnityEngine; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Checks if this code bundle is of a mismatched version than the currently imported packages and updates /// - public sealed class SyncCodeBundleStep : OneSignalSetupStep { - public override string Summary - => "Sync example code bundle"; + public sealed class SyncCodeBundleStep : OneSignalSetupStep + { + public override string Summary => "Sync example code bundle"; - public override string Details - => "Checks if the project scope code bundle (example code) is of a mismatched version than the currently " + - "imported packages"; + public override string Details => + "Checks if the project scope code bundle (example code) is of a mismatched version than the currently " + + "imported packages"; - public override bool IsRequired - => false; + public override bool IsRequired => false; - protected override bool _getIsStepCompleted() { - if (!File.Exists(_packageJsonPath)) { + protected override bool _getIsStepCompleted() + { + if (!File.Exists(_packageJsonPath)) + { UnityEngine.Debug.LogError($"Could not find {_packageJsonPath}"); return true; } @@ -55,7 +57,8 @@ protected override bool _getIsStepCompleted() { var packageJson = File.ReadAllText(_packageJsonPath); - if (Json.Deserialize(packageJson) is Dictionary packageInfo) { + if (Json.Deserialize(packageJson) is Dictionary packageInfo) + { _sdkVersion = packageInfo["version"] as string; return _bundleVersion == _sdkVersion; @@ -66,23 +69,39 @@ protected override bool _getIsStepCompleted() { return true; } - protected override void _runStep() { + protected override void _runStep() + { var msg = $"Downloading OneSignal Unity SDK {_sdkVersion}"; - UnityPackageInstaller.DownloadAndInstall(_onesignalUnityPackageDownloadUrl, msg, result => { - if (!result) - _shouldCheckForCompletion = true; - }); + UnityPackageInstaller.DownloadAndInstall( + _onesignalUnityPackageDownloadUrl, + msg, + result => + { + if (!result) + _shouldCheckForCompletion = true; + } + ); } - private static readonly string _versionPath = Path.Combine("Assets", "OneSignal", "VERSION"); + private static readonly string _versionPath = Path.Combine( + "Assets", + "OneSignal", + "VERSION" + ); private static string _bundleVersion => File.ReadAllText(_versionPath); - private static string _onesignalUnityPackageDownloadUrl - => $"https://github.com/OneSignal/OneSignal-Unity-SDK/releases/download/{_sdkVersion}/OneSignal-v{_sdkVersion}.unitypackage"; + private static string _onesignalUnityPackageDownloadUrl => + $"https://github.com/OneSignal/OneSignal-Unity-SDK/releases/download/{_sdkVersion}/OneSignal-v{_sdkVersion}.unitypackage"; - private static readonly string _packagePath = Path.Combine("Packages", "com.onesignal.unity.core"); - private static readonly string _packageJsonPath = Path.Combine(_packagePath, "package.json"); + private static readonly string _packagePath = Path.Combine( + "Packages", + "com.onesignal.unity.core" + ); + private static readonly string _packageJsonPath = Path.Combine( + _packagePath, + "package.json" + ); private static string _sdkVersion; } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Utilities/EditorWebRequest.cs b/com.onesignal.unity.core/Editor/Utilities/EditorWebRequest.cs index 5274abbb5..de91b7449 100644 --- a/com.onesignal.unity.core/Editor/Utilities/EditorWebRequest.cs +++ b/com.onesignal.unity.core/Editor/Utilities/EditorWebRequest.cs @@ -29,11 +29,13 @@ using UnityEditor; using UnityEngine.Networking; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// The EditorWebRequest is a wrapper around the `UnityWebRequest` that can work in Edit mode. /// - public class EditorWebRequest { + public class EditorWebRequest + { Action m_OnComplete = null; bool m_ShowProgress = false; @@ -46,7 +48,8 @@ public class EditorWebRequest { /// No custom flags or headers are set. /// /// The URI of the resource to retrieve via HTTP GET. - public static EditorWebRequest Get(string url) { + public static EditorWebRequest Get(string url) + { var unityRequest = UnityWebRequest.Get(url); return new EditorWebRequest(unityRequest); @@ -56,7 +59,8 @@ public static EditorWebRequest Get(string url) { /// Create new `EditorWebRequest` instance based on `UnityWebRequest`. /// /// - public EditorWebRequest(UnityWebRequest request) { + public EditorWebRequest(UnityWebRequest request) + { UnityRequest = request; } @@ -64,8 +68,9 @@ public EditorWebRequest(UnityWebRequest request) { /// Request will display editor progress dialog with the given title. /// /// Editor progress dialog title. - public void AddEditorProgressDialog(string title) { - m_ShowProgress = true; + public void AddEditorProgressDialog(string title) + { + m_ShowProgress = true; m_ProgressDialogTitle = title; } @@ -73,8 +78,9 @@ public void AddEditorProgressDialog(string title) { /// Begin communicating with the remote server. /// /// Communication callback. - public void Send(Action callback) { - m_OnComplete = callback; + public void Send(Action callback) + { + m_OnComplete = callback; EditorApplication.update += OnEditorUpdate; UnityRequest.SendWebRequest(); } @@ -89,14 +95,23 @@ public void Send(Action callback) { /// public string DataAsText => UnityRequest.downloadHandler.text; - void OnEditorUpdate() { - if (m_ShowProgress) { - var progress = $"Download Progress: {Convert.ToInt32(UnityRequest.downloadProgress * 100f)}%"; - EditorUtility.DisplayProgressBar(m_ProgressDialogTitle, progress, UnityRequest.downloadProgress); + void OnEditorUpdate() + { + if (m_ShowProgress) + { + var progress = + $"Download Progress: {Convert.ToInt32(UnityRequest.downloadProgress * 100f)}%"; + EditorUtility.DisplayProgressBar( + m_ProgressDialogTitle, + progress, + UnityRequest.downloadProgress + ); } - if (UnityRequest.isDone) { - if (m_ShowProgress) { + if (UnityRequest.isDone) + { + if (m_ShowProgress) + { EditorUtility.ClearProgressBar(); } @@ -105,4 +120,4 @@ void OnEditorUpdate() { } } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/Utilities/UnityPackageInstaller.cs b/com.onesignal.unity.core/Editor/Utilities/UnityPackageInstaller.cs index f01794829..e715bcd61 100644 --- a/com.onesignal.unity.core/Editor/Utilities/UnityPackageInstaller.cs +++ b/com.onesignal.unity.core/Editor/Utilities/UnityPackageInstaller.cs @@ -1,6 +1,6 @@ /* * Modified MIT License -* +* * Copyright 2023 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy @@ -9,13 +9,13 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: -* +* * 1. The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. -* +* * 2. All copies of substantial portions of the Software may only be used in connection * with services provided by OneSignal. -* +* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,25 +30,42 @@ using UnityEditor; using UnityEngine; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Helper to download and install packages /// - public static class UnityPackageInstaller { + public static class UnityPackageInstaller + { /// /// Downloads and install a unitypackage from the specified url /// - public static void DownloadAndInstall(string url, string progressMessage, Action onComplete) { + public static void DownloadAndInstall( + string url, + string progressMessage, + Action onComplete + ) + { var request = EditorWebRequest.Get(url); request.AddEditorProgressDialog(progressMessage); - request.Send(unityRequest => { - if (unityRequest.error != null) { - EditorUtility.DisplayDialog("Package Download failed.", unityRequest.error, "Ok"); + request.Send(unityRequest => + { + if (unityRequest.error != null) + { + EditorUtility.DisplayDialog( + "Package Download failed.", + unityRequest.error, + "Ok" + ); onComplete(false); } - var projectPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6); - var tmpPackageFile = projectPath + FileUtil.GetUniqueTempPathInProject() + ".unityPackage"; + var projectPath = Application.dataPath.Substring( + 0, + Application.dataPath.Length - 6 + ); + var tmpPackageFile = + projectPath + FileUtil.GetUniqueTempPathInProject() + ".unityPackage"; File.WriteAllBytes(tmpPackageFile, unityRequest.downloadHandler.data); AssetDatabase.ImportPackage(tmpPackageFile, false); @@ -57,4 +74,4 @@ public static void DownloadAndInstall(string url, string progressMessage, Action }); } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Editor/link.xml b/com.onesignal.unity.core/Editor/link.xml index 68831e9e8..63b9781b1 100644 --- a/com.onesignal.unity.core/Editor/link.xml +++ b/com.onesignal.unity.core/Editor/link.xml @@ -1,5 +1,5 @@ - - - - \ No newline at end of file + + + + diff --git a/com.onesignal.unity.core/Runtime/Behaviors/OneSignalBehaviour.cs b/com.onesignal.unity.core/Runtime/Behaviors/OneSignalBehaviour.cs index 767c68c33..1f34da056 100644 --- a/com.onesignal.unity.core/Runtime/Behaviors/OneSignalBehaviour.cs +++ b/com.onesignal.unity.core/Runtime/Behaviors/OneSignalBehaviour.cs @@ -25,15 +25,17 @@ * THE SOFTWARE. */ -using UnityEngine; using OneSignalSDK; using OneSignalSDK.Debug.Models; +using UnityEngine; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Behaviour attached to the OneSignalController.prefab which can be dragged into your scene fora codeless init /// - public class OneSignalBehaviour : MonoBehaviour { + public class OneSignalBehaviour : MonoBehaviour + { /// /// The unique identifier for your application from the OneSignal dashboard /// https://documentation.onesignal.com/docs/keys-and-ids#app-id @@ -44,7 +46,7 @@ public class OneSignalBehaviour : MonoBehaviour { /// The minimum level of logs which will be logged to the console /// public LogLevel LogLevel = LogLevel.Warn; - + /// /// The minimum level of log events which will be converted into foreground alerts /// @@ -62,13 +64,14 @@ public class OneSignalBehaviour : MonoBehaviour { /// This method must be called before on iOS. public bool IsShared = false; - private void Start() { - OneSignal.Debug.LogLevel = LogLevel; - OneSignal.Debug.AlertLevel = AlertLevel; - OneSignal.ConsentRequired = ConsentRequired; - OneSignal.Location.IsShared = IsShared; + private void Start() + { + OneSignal.Debug.LogLevel = LogLevel; + OneSignal.Debug.AlertLevel = AlertLevel; + OneSignal.ConsentRequired = ConsentRequired; + OneSignal.Location.IsShared = IsShared; OneSignal.Initialize(AppId); } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Debug/IDebugManager.cs b/com.onesignal.unity.core/Runtime/Debug/IDebugManager.cs index f5a44d533..8f331bcd7 100644 --- a/com.onesignal.unity.core/Runtime/Debug/IDebugManager.cs +++ b/com.onesignal.unity.core/Runtime/Debug/IDebugManager.cs @@ -27,15 +27,17 @@ using OneSignalSDK.Debug.Models; -namespace OneSignalSDK.Debug { +namespace OneSignalSDK.Debug +{ /// /// Access to debug the SDK in the event additional information is required to diagnose any /// SDK-related issues. - /// + /// /// WARNING: This should not be used in a production setting. - /// + /// /// - public interface IDebugManager { + public interface IDebugManager + { /// /// The minimum level of logs which will be logged to the console /// @@ -46,4 +48,4 @@ public interface IDebugManager { /// LogLevel AlertLevel { get; set; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Debug/Models/LogLevel.cs b/com.onesignal.unity.core/Runtime/Debug/Models/LogLevel.cs index 02ce637cc..3b5ea8777 100644 --- a/com.onesignal.unity.core/Runtime/Debug/Models/LogLevel.cs +++ b/com.onesignal.unity.core/Runtime/Debug/Models/LogLevel.cs @@ -25,17 +25,19 @@ * THE SOFTWARE. */ -namespace OneSignalSDK.Debug.Models { +namespace OneSignalSDK.Debug.Models +{ /// /// Direct mapping of native SDK log levels - /// - public enum LogLevel { - None = 0, - Fatal, - Error, - Warn, - Info, - Debug, - Verbose + /// + public enum LogLevel + { + None = 0, + Fatal, + Error, + Warn, + Info, + Debug, + Verbose, } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Debug/Utilities/SDKDebug.cs b/com.onesignal.unity.core/Runtime/Debug/Utilities/SDKDebug.cs index 01749a95f..d64b7f7a2 100644 --- a/com.onesignal.unity.core/Runtime/Debug/Utilities/SDKDebug.cs +++ b/com.onesignal.unity.core/Runtime/Debug/Utilities/SDKDebug.cs @@ -28,36 +28,41 @@ using System; using OneSignalSDK.Debug.Models; -namespace OneSignalSDK.Debug.Utilities { +namespace OneSignalSDK.Debug.Utilities +{ /// /// Helper for printing Unity logs formatted to specify they are from this SDK /// - internal static class SDKDebug { + internal static class SDKDebug + { public static event Action LogIntercept; public static event Action WarnIntercept; public static event Action ErrorIntercept; - - public static void Info(string message) { + + public static void Info(string message) + { if (LogIntercept != null) LogIntercept(message); else if (OneSignal.Debug.LogLevel >= LogLevel.Info) UnityEngine.Debug.Log(_formatMessage(message)); } - public static void Warn(string message) { + public static void Warn(string message) + { if (WarnIntercept != null) WarnIntercept(message); else if (OneSignal.Debug.LogLevel >= LogLevel.Warn) - UnityEngine.Debug.LogWarning(_formatMessage(message)); + UnityEngine.Debug.LogWarning(_formatMessage(message)); } - public static void Error(string message) { + public static void Error(string message) + { if (ErrorIntercept != null) ErrorIntercept(message); - else if (OneSignal.Debug.LogLevel >= LogLevel.Error) + else if (OneSignal.Debug.LogLevel >= LogLevel.Error) UnityEngine.Debug.LogError(_formatMessage(message)); } private static string _formatMessage(string message) => "[OneSignal] " + message; } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/InAppMessages/IInAppMessagesManager.cs b/com.onesignal.unity.core/Runtime/InAppMessages/IInAppMessagesManager.cs index 50fef63ab..d0d69af73 100644 --- a/com.onesignal.unity.core/Runtime/InAppMessages/IInAppMessagesManager.cs +++ b/com.onesignal.unity.core/Runtime/InAppMessages/IInAppMessagesManager.cs @@ -29,7 +29,8 @@ using System.Collections.Generic; using OneSignalSDK.InAppMessages.Models; -namespace OneSignalSDK.InAppMessages { +namespace OneSignalSDK.InAppMessages +{ /// /// When any client side will display event in an In-App Message's occurs there will be a corresponding event with /// this arguement. @@ -38,7 +39,8 @@ public class InAppMessageWillDisplayEventArgs : EventArgs { public IInAppMessage Message { get; } - public InAppMessageWillDisplayEventArgs(IInAppMessage message) { + public InAppMessageWillDisplayEventArgs(IInAppMessage message) + { Message = message; } } @@ -51,7 +53,8 @@ public class InAppMessageDidDisplayEventArgs : EventArgs { public IInAppMessage Message { get; } - public InAppMessageDidDisplayEventArgs(IInAppMessage message) { + public InAppMessageDidDisplayEventArgs(IInAppMessage message) + { Message = message; } } @@ -64,7 +67,8 @@ public class InAppMessageWillDismissEventArgs : EventArgs { public IInAppMessage Message { get; } - public InAppMessageWillDismissEventArgs(IInAppMessage message) { + public InAppMessageWillDismissEventArgs(IInAppMessage message) + { Message = message; } } @@ -77,7 +81,8 @@ public class InAppMessageDidDismissEventArgs : EventArgs { public IInAppMessage Message { get; } - public InAppMessageDidDismissEventArgs(IInAppMessage message) { + public InAppMessageDidDismissEventArgs(IInAppMessage message) + { Message = message; } } @@ -90,7 +95,8 @@ public class InAppMessageClickEventArgs : EventArgs public IInAppMessage Message { get; } public IInAppMessageClickResult Result { get; } - public InAppMessageClickEventArgs(IInAppMessage message, IInAppMessageClickResult result) { + public InAppMessageClickEventArgs(IInAppMessage message, IInAppMessageClickResult result) + { Message = message; Result = result; } @@ -102,7 +108,8 @@ public InAppMessageClickEventArgs(IInAppMessage message, IInAppMessageClickResul /// if the current user qualifies for any IAMs sent down by the OneSignal backend. To /// blanket disable IAMs, set [paused] to `true` on startup. /// - public interface IInAppMessagesManager { + public interface IInAppMessagesManager + { /// /// When an In-App Message is ready to be displayed to the screen /// @@ -165,4 +172,4 @@ public interface IInAppMessagesManager { /// void ClearTriggers(); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessage.cs b/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessage.cs index 376e0705b..508a886c9 100644 --- a/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessage.cs +++ b/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessage.cs @@ -28,21 +28,25 @@ using System; using OneSignalSDK.InAppMessages.Models; -namespace OneSignalSDK.InAppMessages.Internal { - [Serializable] public sealed class InAppMessage : IInAppMessage { +namespace OneSignalSDK.InAppMessages.Internal +{ + [Serializable] + public sealed class InAppMessage : IInAppMessage + { /// /// Unique id of this in-app message /// public string MessageId => messageId; - public InAppMessage() {} + public InAppMessage() { } - public InAppMessage(string messageId) { + public InAppMessage(string messageId) + { this.messageId = messageId; } #region Native Field Handling - public string messageId; + public string messageId; #endregion } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessageAction.cs b/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessageAction.cs index 829367f36..29364dd0a 100755 --- a/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessageAction.cs +++ b/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessageAction.cs @@ -26,14 +26,17 @@ */ using System; -using UnityEngine; using OneSignalSDK.InAppMessages.Models; +using UnityEngine; -namespace OneSignalSDK.InAppMessages.Internal { +namespace OneSignalSDK.InAppMessages.Internal +{ /// /// Action associated with clicking a button in an In-App Message /// - [Serializable] public sealed class InAppMessageAction : IInAppMessageAction { + [Serializable] + public sealed class InAppMessageAction : IInAppMessageAction + { /// /// An optional click name defined for the action element /// @@ -55,10 +58,10 @@ namespace OneSignalSDK.InAppMessages.Internal { public bool ClosesMessage => closes_message; #region Native Field Handling - public string click_name; - public string click_url; - public bool first_click; - public bool closes_message; + public string click_name; + public string click_url; + public bool first_click; + public bool closes_message; #endregion } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessageClickResult.cs b/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessageClickResult.cs index 655563d36..b35e2cd92 100644 --- a/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessageClickResult.cs +++ b/com.onesignal.unity.core/Runtime/InAppMessages/Internal/InAppMessageClickResult.cs @@ -28,8 +28,11 @@ using System; using OneSignalSDK.InAppMessages.Models; -namespace OneSignalSDK.InAppMessages.Internal { - [Serializable] public sealed class InAppMessageClickResult : IInAppMessageClickResult { +namespace OneSignalSDK.InAppMessages.Internal +{ + [Serializable] + public sealed class InAppMessageClickResult : IInAppMessageClickResult + { private InAppMessageActionUrlType _urlTarget; /// @@ -40,7 +43,8 @@ namespace OneSignalSDK.InAppMessages.Internal { /// /// Where the URL will be opened /// - public InAppMessageActionUrlType UrlTarget { + public InAppMessageActionUrlType UrlTarget + { get => _urlTarget; } @@ -54,9 +58,15 @@ public InAppMessageActionUrlType UrlTarget { /// public bool ClosingMessage => closingMessage; - public InAppMessageClickResult() {} + public InAppMessageClickResult() { } - public InAppMessageClickResult(string actionId, InAppMessageActionUrlType urlTarget, string url, bool closingMessage) { + public InAppMessageClickResult( + string actionId, + InAppMessageActionUrlType urlTarget, + string url, + bool closingMessage + ) + { this.actionId = actionId; _urlTarget = urlTarget; this.url = url; @@ -65,10 +75,10 @@ public InAppMessageClickResult(string actionId, InAppMessageActionUrlType urlTar } #region Native Field Handling - public string actionId; - public string urlType; - public string url; - public bool closingMessage; + public string actionId; + public string urlType; + public string url; + public bool closingMessage; #endregion } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessage.cs b/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessage.cs index 0b01aa69a..79ebc83df 100644 --- a/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessage.cs +++ b/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessage.cs @@ -27,11 +27,13 @@ using System; -namespace OneSignalSDK.InAppMessages.Models { - public interface IInAppMessage { +namespace OneSignalSDK.InAppMessages.Models +{ + public interface IInAppMessage + { /// /// Unique id of this in-app message /// string MessageId { get; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessageAction.cs b/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessageAction.cs index e2b3c27f6..a78073c50 100755 --- a/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessageAction.cs +++ b/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessageAction.cs @@ -28,11 +28,13 @@ using System; using UnityEngine; -namespace OneSignalSDK.InAppMessages.Models { +namespace OneSignalSDK.InAppMessages.Models +{ /// /// Action associated with clicking a button in an In-App Message /// - public interface IInAppMessageAction { + public interface IInAppMessageAction + { /// /// An optional click name defined for the action element /// @@ -53,4 +55,4 @@ public interface IInAppMessageAction { /// bool ClosesMessage { get; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessageClickResult.cs b/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessageClickResult.cs index 9d1974d43..0efb76528 100644 --- a/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessageClickResult.cs +++ b/com.onesignal.unity.core/Runtime/InAppMessages/Models/IInAppMessageClickResult.cs @@ -27,8 +27,10 @@ using System; -namespace OneSignalSDK.InAppMessages.Models { - public interface IInAppMessageClickResult { +namespace OneSignalSDK.InAppMessages.Models +{ + public interface IInAppMessageClickResult + { /// /// Action the user took on the in-app message /// @@ -49,4 +51,4 @@ public interface IInAppMessageClickResult { /// bool ClosingMessage { get; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/InAppMessages/Models/InAppMessageActionUrlType.cs b/com.onesignal.unity.core/Runtime/InAppMessages/Models/InAppMessageActionUrlType.cs index ea8eb69e5..65c984f6c 100644 --- a/com.onesignal.unity.core/Runtime/InAppMessages/Models/InAppMessageActionUrlType.cs +++ b/com.onesignal.unity.core/Runtime/InAppMessages/Models/InAppMessageActionUrlType.cs @@ -25,11 +25,14 @@ * THE SOFTWARE. */ -namespace OneSignalSDK.InAppMessages.Models { - public class InAppMessageActionUrlType { +namespace OneSignalSDK.InAppMessages.Models +{ + public class InAppMessageActionUrlType + { private string _type; - private InAppMessageActionUrlType(string type) { + private InAppMessageActionUrlType(string type) + { _type = type; } @@ -38,8 +41,12 @@ public override string ToString() return _type; } - public static InAppMessageActionUrlType InAppWebview = new InAppMessageActionUrlType("Webview"); + public static InAppMessageActionUrlType InAppWebview = new InAppMessageActionUrlType( + "Webview" + ); public static InAppMessageActionUrlType Browser = new InAppMessageActionUrlType("Browser"); - public static InAppMessageActionUrlType RepalceContent = new InAppMessageActionUrlType("Replacement"); + public static InAppMessageActionUrlType RepalceContent = new InAppMessageActionUrlType( + "Replacement" + ); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/LiveActivities/ILiveActivitiesManager.cs b/com.onesignal.unity.core/Runtime/LiveActivities/ILiveActivitiesManager.cs index 61a8f02ef..99191bc7e 100644 --- a/com.onesignal.unity.core/Runtime/LiveActivities/ILiveActivitiesManager.cs +++ b/com.onesignal.unity.core/Runtime/LiveActivities/ILiveActivitiesManager.cs @@ -28,8 +28,10 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace OneSignalSDK.LiveActivities { - public interface ILiveActivitiesManager { +namespace OneSignalSDK.LiveActivities +{ + public interface ILiveActivitiesManager + { /// /// Associates a customer defined activityId with a live activity temporary push token on OneSignal's server /// @@ -54,7 +56,7 @@ public interface ILiveActivitiesManager { /// `DefaultLiveActivityAttributes`. This is most useful for users that (1) only have one Live /// Activity widget and (2) are using a cross-platform framework and do not want to create the /// cross-platform <-> iOS native bindings to manage ActivityKit. - /// + /// /// Only applies to iOS. /// /// An optional structure to provide for more granular setup options. @@ -64,20 +66,24 @@ public interface ILiveActivitiesManager { /// Start a new LiveActivity that is modelled by the default`DefaultLiveActivityAttributes` /// structure. The `DefaultLiveActivityAttributes` is initialized with the dynamic `attributes` /// and `content` passed in. - /// + /// /// Only applies to iOS. /// /// The activity identifier the live activity on this device will be started /// and eligible to receive updates for. /// A dynamic type containing the static attributes passed into `DefaultLiveActivityAttributes`. /// A dynamic type containing the content attributes passed into `DefaultLiveActivityAttributes`. - void StartDefault(string activityId, IDictionary attributes, IDictionary content); + void StartDefault( + string activityId, + IDictionary attributes, + IDictionary content + ); /// /// Indicate this device is capable of receiving pushToStart live activities for the `activityType`. /// The `activityType` **must** be the name of the struct conforming to `ActivityAttributes` that will be used /// to start the live activity. - /// + /// /// Only applies to iOS. /// /// The name of the specific `ActivityAttributes` structure tied to the live activity. @@ -88,10 +94,10 @@ public interface ILiveActivitiesManager { /// Indicate this device is no longer capable of receiving pushToStart live activities for the `activityType`. /// The `activityType` **must** be the name of the struct conforming to `ActivityAttributes` that will be used /// to start the live activity. - /// + /// /// Only applies to iOS. /// /// The name of the specific `ActivityAttributes` structure tied to the live activity. void RemovePushToStartToken(string activityType); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/LiveActivities/LiveActivitiesSetupOptions.cs b/com.onesignal.unity.core/Runtime/LiveActivities/LiveActivitiesSetupOptions.cs index ae2a5fb31..51aa70515 100644 --- a/com.onesignal.unity.core/Runtime/LiveActivities/LiveActivitiesSetupOptions.cs +++ b/com.onesignal.unity.core/Runtime/LiveActivities/LiveActivitiesSetupOptions.cs @@ -27,7 +27,8 @@ using System.Threading.Tasks; -namespace OneSignalSDK.LiveActivities { +namespace OneSignalSDK.LiveActivities +{ /// /// The setup options for . /// @@ -44,4 +45,4 @@ public class LiveActivitySetupOptions /// public bool EnablePushToUpdate { get; set; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Location/ILocationManager.cs b/com.onesignal.unity.core/Runtime/Location/ILocationManager.cs index 238cc48fa..d6de00b95 100644 --- a/com.onesignal.unity.core/Runtime/Location/ILocationManager.cs +++ b/com.onesignal.unity.core/Runtime/Location/ILocationManager.cs @@ -27,11 +27,13 @@ using System.Threading.Tasks; -namespace OneSignalSDK.Location { +namespace OneSignalSDK.Location +{ /// /// The entry point to the location SDK for OneSignal. /// - public interface ILocationManager { + public interface ILocationManager + { /// /// Disable or enable location collection by OneSignal (defaults to enabled if your app has location permission). /// @@ -43,4 +45,4 @@ public interface ILocationManager { /// void RequestPermission(); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Notifications/INotificationsManager.cs b/com.onesignal.unity.core/Runtime/Notifications/INotificationsManager.cs index 506cb1af5..2bdcb262e 100644 --- a/com.onesignal.unity.core/Runtime/Notifications/INotificationsManager.cs +++ b/com.onesignal.unity.core/Runtime/Notifications/INotificationsManager.cs @@ -29,7 +29,8 @@ using System.Threading.Tasks; using OneSignalSDK.Notifications.Models; -namespace OneSignalSDK.Notifications { +namespace OneSignalSDK.Notifications +{ /// /// When a push notification has been received and is about to be displayed /// @@ -37,16 +38,15 @@ public class NotificationWillDisplayEventArgs : EventArgs { public IDisplayableNotification Notification { get; } - public NotificationWillDisplayEventArgs(IDisplayableNotification notification) { + public NotificationWillDisplayEventArgs(IDisplayableNotification notification) + { Notification = notification; } /// /// Prevents OneSignal from displaying the notification automatically. /// - public virtual void PreventDefault() { - - } + public virtual void PreventDefault() { } } /// @@ -57,20 +57,25 @@ public class NotificationClickEventArgs : EventArgs public INotification Notification { get; } public INotificationClickResult Result { get; } - public NotificationClickEventArgs(INotification notification, INotificationClickResult result) { + public NotificationClickEventArgs( + INotification notification, + INotificationClickResult result + ) + { Notification = notification; Result = result; } } /// - /// When the user enables or disables notifications for your app from the system settings outside of your app. + /// When the user enables or disables notifications for your app from the system settings outside of your app. /// public class NotificationPermissionChangedEventArgs : EventArgs { public bool Permission { get; } - public NotificationPermissionChangedEventArgs(bool permission) { + public NotificationPermissionChangedEventArgs(bool permission) + { Permission = permission; } } @@ -78,7 +83,8 @@ public NotificationPermissionChangedEventArgs(bool permission) { /// /// The entry point to the notification SDK for OneSignal. /// - public interface INotificationsManager { + public interface INotificationsManager + { /// /// When a push notification has been received while app is in the foreground /// @@ -127,4 +133,4 @@ public interface INotificationsManager { /// void ClearAllNotifications(); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Notifications/Internal/Notification.cs b/com.onesignal.unity.core/Runtime/Notifications/Internal/Notification.cs index 880dd69e3..b7a5007e4 100755 --- a/com.onesignal.unity.core/Runtime/Notifications/Internal/Notification.cs +++ b/com.onesignal.unity.core/Runtime/Notifications/Internal/Notification.cs @@ -26,20 +26,23 @@ */ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using OneSignalSDK.Notifications.Models; -namespace OneSignalSDK.Notifications.Internal { - [Serializable] public sealed class ActionButton : IActionButton { +namespace OneSignalSDK.Notifications.Internal +{ + [Serializable] + public sealed class ActionButton : IActionButton + { public string Id => id; public string Text => text; public string Icon => icon; #region Native Field Handling - public string id; - public string text; - public string icon; + public string id; + public string text; + public string icon; #endregion } @@ -47,43 +50,47 @@ namespace OneSignalSDK.Notifications.Internal { /// If a background image was set, this object will be available /// /// Android only - [Serializable] public sealed class BackgroundImageLayout : IBackgroundImageLayout { + [Serializable] + public sealed class BackgroundImageLayout : IBackgroundImageLayout + { public string Image => image; public string TitleTextColor => titleTextColor; public string BodyTextColor => bodyTextColor; #region Native Field Handling - public string image; - public string titleTextColor; - public string bodyTextColor; + public string image; + public string titleTextColor; + public string bodyTextColor; #endregion } - + /// /// See full documentation at /// https://documentation.onesignal.com/docs/mobile-push-notifications-guide#notification-payload-and-methods /// - [Serializable] public class NotificationBase : INotificationBase { + [Serializable] + public class NotificationBase : INotificationBase + { /// /// OneSignal notification UUID /// public string NotificationId => notificationId; - + /// /// Name of Template from Templates /// public string TemplateName => templateName; - + /// /// Unique Template Identifier from Templates /// public string TemplateId => templateId; - + /// /// Title text of the notification /// public string Title => title; - + /// /// Body text of the notification /// @@ -93,7 +100,7 @@ namespace OneSignalSDK.Notifications.Internal { /// URL opened when opening the notification /// public string LaunchURL => launchURL; - + /// /// Sound resource played when the notification is shown /// https://documentation.onesignal.com/docs/customize-notification-sounds @@ -104,7 +111,7 @@ namespace OneSignalSDK.Notifications.Internal { /// Collapse id for the notification /// public string CollapseId => collapseId; - + /// /// Gets custom additional data that was sent with the notification. Set on the dashboard under /// Options > Additional Data or with the data field on the REST API. @@ -121,7 +128,7 @@ namespace OneSignalSDK.Notifications.Internal { /// public string RawPayload => rawPayload; - #region Android + #region Android /// /// Unique Android Native API identifier /// @@ -133,55 +140,55 @@ namespace OneSignalSDK.Notifications.Internal { /// /// Android only public string SmallIcon => smallIcon; - + /// /// Large icon resource name set on the notification /// /// Android only public string LargeIcon => largeIcon; - + /// /// Big picture image set on the notification /// /// Android only public string BigPicture => bigPicture; - + /// /// Accent color shown around small notification icon on Android 5+ devices. ARGB format. /// /// Android 5+ only public string SmallIconAccentColor => smallIconAccentColor; - + /// /// LED string. Devices that have a notification LED will blink in this color. ARGB format. /// /// Android only public string LedColor => ledColor; - + /// /// Privacy setting for how the notification should be shown on the lockscreen of Android 5+ devices /// /// Android 5+ only public LockScreenVisibility LockScreenVisibility => lockScreenVisibility; - + /// /// Notifications with this same key will be grouped together as a single summary notification /// /// Android only public string GroupKey => groupKey; - + /// /// Summary text displayed in the summary notification /// /// Android only public string GroupMessage => groupMessage; - + /// /// Google project number the notification was sent under /// /// Android only public string FromProjectNumber => fromProjectNumber; - + /// /// Priority of the notification. Values range from -2 to 2 (see /// https://developer.android.com/reference/androidx/core/app/NotificationCompat for more info) @@ -194,9 +201,9 @@ namespace OneSignalSDK.Notifications.Internal { /// /// Android only public IBackgroundImageLayout BackgroundImageLayout => backgroundImageLayout; - #endregion + #endregion - #region iOS + #region iOS /// /// Message Subtitle, iOS only /// @@ -262,54 +269,57 @@ namespace OneSignalSDK.Notifications.Internal { /// /// iOS 10+ only public IDictionary Attachments => attachments; - #endregion + #endregion #region Native Field Handling - public string notificationId; - public string templateName; - public string templateId; - public string title; - public string body; - public string launchURL; - public string sound; - public string collapseId; - public IDictionary additionalData; - public List actionButtons; - public string rawPayload; - public int androidNotificationId; - public string smallIcon; - public string largeIcon; - public string bigPicture; - public string smallIconAccentColor; - public string ledColor; - public LockScreenVisibility lockScreenVisibility; - public string groupKey; - public string groupMessage; - public string fromProjectNumber; - public int priority; - public BackgroundImageLayout backgroundImageLayout; - public string subtitle; - public bool contentAvailable; - public bool mutableContent; - public string category; - public int badge; - public int badgeIncrement; - public string threadId; - public double relevanceScore; - public string interruptionLevel; - public IDictionary attachments; + public string notificationId; + public string templateName; + public string templateId; + public string title; + public string body; + public string launchURL; + public string sound; + public string collapseId; + public IDictionary additionalData; + public List actionButtons; + public string rawPayload; + public int androidNotificationId; + public string smallIcon; + public string largeIcon; + public string bigPicture; + public string smallIconAccentColor; + public string ledColor; + public LockScreenVisibility lockScreenVisibility; + public string groupKey; + public string groupMessage; + public string fromProjectNumber; + public int priority; + public BackgroundImageLayout backgroundImageLayout; + public string subtitle; + public bool contentAvailable; + public bool mutableContent; + public string category; + public int badge; + public int badgeIncrement; + public string threadId; + public double relevanceScore; + public string interruptionLevel; + public IDictionary attachments; #endregion } - [Serializable] public class Notification : NotificationBase, INotification { + [Serializable] + public class Notification : NotificationBase, INotification + { /// /// Gets the notification payloads a summary notification was created from /// /// Android only - public List GroupedNotifications => groupedNotifications.ToList(); + public List GroupedNotifications => + groupedNotifications.ToList(); #region Native Field Handling - public List groupedNotifications; + public List groupedNotifications; #endregion } } diff --git a/com.onesignal.unity.core/Runtime/Notifications/Internal/NotificationClickResult.cs b/com.onesignal.unity.core/Runtime/Notifications/Internal/NotificationClickResult.cs index 49522aeff..eb5c91066 100755 --- a/com.onesignal.unity.core/Runtime/Notifications/Internal/NotificationClickResult.cs +++ b/com.onesignal.unity.core/Runtime/Notifications/Internal/NotificationClickResult.cs @@ -28,28 +28,32 @@ using System; using OneSignalSDK.Notifications.Models; -namespace OneSignalSDK.Notifications.Internal { - [Serializable] public sealed class NotificationClickResult : INotificationClickResult { +namespace OneSignalSDK.Notifications.Internal +{ + [Serializable] + public sealed class NotificationClickResult : INotificationClickResult + { /// /// Custom id of action taken. /// public string ActionId => actionId; - + /// /// The launch url for the notification /// public string Url => url; - public NotificationClickResult() {} + public NotificationClickResult() { } - public NotificationClickResult(string actionId, string url) { + public NotificationClickResult(string actionId, string url) + { this.actionId = actionId; this.url = url; } #region Native Field Handling - public string actionId; - public string url; + public string actionId; + public string url; #endregion } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Notifications/Models/IDisplayableNotification.cs b/com.onesignal.unity.core/Runtime/Notifications/Models/IDisplayableNotification.cs index 065386061..4adc18d0f 100644 --- a/com.onesignal.unity.core/Runtime/Notifications/Models/IDisplayableNotification.cs +++ b/com.onesignal.unity.core/Runtime/Notifications/Models/IDisplayableNotification.cs @@ -27,8 +27,10 @@ using System; -namespace OneSignalSDK.Notifications.Models { - public interface IDisplayableNotification : INotification { +namespace OneSignalSDK.Notifications.Models +{ + public interface IDisplayableNotification : INotification + { /// /// Display the notification on the device. /// diff --git a/com.onesignal.unity.core/Runtime/Notifications/Models/INotification.cs b/com.onesignal.unity.core/Runtime/Notifications/Models/INotification.cs index 9b2d86347..98c9a11dd 100755 --- a/com.onesignal.unity.core/Runtime/Notifications/Models/INotification.cs +++ b/com.onesignal.unity.core/Runtime/Notifications/Models/INotification.cs @@ -28,18 +28,21 @@ using System; using System.Collections.Generic; -namespace OneSignalSDK.Notifications.Models { +namespace OneSignalSDK.Notifications.Models +{ /// /// Privacy setting for how the notification should be shown on the lockscreen of Android 5+ devices /// /// Android 5+ only - public enum LockScreenVisibility { - Secret = -1, // Not shown - Private = 0, // Contents are hidden - Public = 1 // (default) Fully visible + public enum LockScreenVisibility + { + Secret = -1, // Not shown + Private = 0, // Contents are hidden + Public = 1, // (default) Fully visible } - public interface IActionButton { + public interface IActionButton + { string Id { get; } string Text { get; } string Icon { get; } @@ -49,37 +52,39 @@ public interface IActionButton { /// If a background image was set, this object will be available /// /// Android only - public interface IBackgroundImageLayout { + public interface IBackgroundImageLayout + { string Image { get; } string TitleTextColor { get; } string BodyTextColor { get; } } - + /// /// See full documentation at /// https://documentation.onesignal.com/docs/mobile-push-notifications-guide#notification-payload-and-methods /// - public interface INotificationBase { + public interface INotificationBase + { /// /// OneSignal notification UUID /// string NotificationId { get; } - + /// /// Name of Template from Templates /// string TemplateName { get; } - + /// /// Unique Template Identifier from Templates /// string TemplateId { get; } - + /// /// Title text of the notification /// string Title { get; } - + /// /// Body text of the notification /// @@ -89,7 +94,7 @@ public interface INotificationBase { /// URL opened when opening the notification /// string LaunchURL { get; } - + /// /// Sound resource played when the notification is shown /// https://documentation.onesignal.com/docs/customize-notification-sounds @@ -100,7 +105,7 @@ public interface INotificationBase { /// Collapse id for the notification /// string CollapseId { get; } - + /// /// Gets custom additional data that was sent with the notification. Set on the dashboard under /// Options > Additional Data or with the data field on the REST API. @@ -117,7 +122,7 @@ public interface INotificationBase { /// string RawPayload { get; } - #region Android + #region Android /// /// Unique Android Native API identifier /// @@ -129,55 +134,55 @@ public interface INotificationBase { /// /// Android only string SmallIcon { get; } - + /// /// Large icon resource name set on the notification /// /// Android only string LargeIcon { get; } - + /// /// Big picture image set on the notification /// /// Android only string BigPicture { get; } - + /// /// Accent color shown around small notification icon on Android 5+ devices. ARGB format. /// /// Android 5+ only string SmallIconAccentColor { get; } - + /// /// LED string. Devices that have a notification LED will blink in this color. ARGB format. /// /// Android only string LedColor { get; } - + /// /// Privacy setting for how the notification should be shown on the lockscreen of Android 5+ devices /// /// Android 5+ only LockScreenVisibility LockScreenVisibility { get; } - + /// /// Notifications with this same key will be grouped together as a single summary notification /// /// Android only string GroupKey { get; } - + /// /// Summary text displayed in the summary notification /// /// Android only string GroupMessage { get; } - + /// /// Google project number the notification was sent under /// /// Android only string FromProjectNumber { get; } - + /// /// Priority of the notification. Values range from -2 to 2 (see /// https://developer.android.com/reference/androidx/core/app/NotificationCompat for more info) @@ -190,9 +195,9 @@ public interface INotificationBase { /// /// Android only IBackgroundImageLayout BackgroundImageLayout { get; } - #endregion + #endregion - #region iOS + #region iOS /// /// Message Subtitle, iOS only /// @@ -258,10 +263,11 @@ public interface INotificationBase { /// /// iOS 10+ only IDictionary Attachments { get; } - #endregion + #endregion } - public interface INotification : INotificationBase { + public interface INotification : INotificationBase + { /// /// Gets the notification payloads a summary notification was created from /// diff --git a/com.onesignal.unity.core/Runtime/Notifications/Models/INotificationClickResult.cs b/com.onesignal.unity.core/Runtime/Notifications/Models/INotificationClickResult.cs index d6f0ffc8c..0ce4cb4d9 100755 --- a/com.onesignal.unity.core/Runtime/Notifications/Models/INotificationClickResult.cs +++ b/com.onesignal.unity.core/Runtime/Notifications/Models/INotificationClickResult.cs @@ -27,16 +27,18 @@ using System; -namespace OneSignalSDK.Notifications.Models { - public interface INotificationClickResult { +namespace OneSignalSDK.Notifications.Models +{ + public interface INotificationClickResult + { /// /// Custom id of action taken. /// string ActionId { get; } - + /// /// The launch url for the notification. /// string Url { get; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Notifications/Models/NotificationPermission.cs b/com.onesignal.unity.core/Runtime/Notifications/Models/NotificationPermission.cs index 6e11eb42a..7da52e1a5 100644 --- a/com.onesignal.unity.core/Runtime/Notifications/Models/NotificationPermission.cs +++ b/com.onesignal.unity.core/Runtime/Notifications/Models/NotificationPermission.cs @@ -25,12 +25,14 @@ * THE SOFTWARE. */ -namespace OneSignalSDK.Notifications.Models { - public enum NotificationPermission { - NotDetermined = 0, - Denied, - Authorized, - Provisional, - Ephemeral +namespace OneSignalSDK.Notifications.Models +{ + public enum NotificationPermission + { + NotDetermined = 0, + Denied, + Authorized, + Provisional, + Ephemeral, } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/OneSignal.Internal.cs b/com.onesignal.unity.core/Runtime/OneSignal.Internal.cs index 95b3d4460..3b44421dd 100755 --- a/com.onesignal.unity.core/Runtime/OneSignal.Internal.cs +++ b/com.onesignal.unity.core/Runtime/OneSignal.Internal.cs @@ -27,29 +27,39 @@ using System; using System.Linq; -using UnityEngine; using OneSignalSDK.Debug.Utilities; +using UnityEngine; -namespace OneSignalSDK { - public static partial class OneSignal { +namespace OneSignalSDK +{ + public static partial class OneSignal + { private static OneSignalPlatform _default; - private static OneSignalPlatform _getDefaultInstance() { + private static OneSignalPlatform _getDefaultInstance() + { if (_default != null) return _default; // only 1 sdk should be available for any given supported platform - var availableSDKs = ReflectionHelpers.FindAllAssignableTypes("OneSignal"); - if (Activator.CreateInstance(availableSDKs.First()) is OneSignalPlatform sdk) { + var availableSDKs = ReflectionHelpers.FindAllAssignableTypes( + "OneSignal" + ); + if (Activator.CreateInstance(availableSDKs.First()) is OneSignalPlatform sdk) + { _default = sdk; - SDKDebug.Info($"OneSignal set to platform SDK {sdk.GetType()}. Current version is {Version}"); + SDKDebug.Info( + $"OneSignal set to platform SDK {sdk.GetType()}. Current version is {Version}" + ); } - else { - UnityEngine.Debug.LogError("[OneSignal] Could not find an implementation of OneSignal SDK to use!"); + else + { + UnityEngine.Debug.LogError( + "[OneSignal] Could not find an implementation of OneSignal SDK to use!" + ); } return _default; } } } - diff --git a/com.onesignal.unity.core/Runtime/OneSignal.cs b/com.onesignal.unity.core/Runtime/OneSignal.cs index eec1cb09e..60e43c492 100755 --- a/com.onesignal.unity.core/Runtime/OneSignal.cs +++ b/com.onesignal.unity.core/Runtime/OneSignal.cs @@ -26,29 +26,30 @@ */ using System.Collections.Generic; -using UnityEngine; -using OneSignalSDK.Notifications; -using OneSignalSDK.InAppMessages; using OneSignalSDK.Debug; +using OneSignalSDK.InAppMessages; +using OneSignalSDK.LiveActivities; using OneSignalSDK.Location; +using OneSignalSDK.Notifications; using OneSignalSDK.Session; using OneSignalSDK.User; -using OneSignalSDK.LiveActivities; +using UnityEngine; -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// OneSignal SDK for Unity /// - public static partial class OneSignal { + public static partial class OneSignal + { public const string Version = "5.1.15"; /// /// The default static instance of the OneSignal Unity SDK /// - public static OneSignalPlatform Default { - get { - return _getDefaultInstance(); - } + public static OneSignalPlatform Default + { + get { return _getDefaultInstance(); } } /// @@ -56,82 +57,76 @@ public static OneSignalPlatform Default { /// has been called, and initialized with a device-scoped user until (or if) [login] has been /// called. /// - public static IUserManager User { - get { - return OneSignal.Default.User; - } + public static IUserManager User + { + get { return OneSignal.Default.User; } } /// /// The session manager for accessing session-scoped management. Initialized only after [initWithContext] /// has been called. /// - public static ISessionManager Session { - get { - return OneSignal.Default.Session; - } + public static ISessionManager Session + { + get { return OneSignal.Default.Session; } } /// /// The notification manager for accessing device-scoped notification management. Initialized /// only after [initWithContext] has been called. /// - public static INotificationsManager Notifications{ - get { - return OneSignal.Default.Notifications; - } + public static INotificationsManager Notifications + { + get { return OneSignal.Default.Notifications; } } /// /// The notification manager for accessing device-scoped notification management. Initialized /// only after [initWithContext] has been called. /// - public static ILocationManager Location { - get { - return OneSignal.Default.Location; - } + public static ILocationManager Location + { + get { return OneSignal.Default.Location; } } /// /// The In-App Messaging manager for accessing device-scoped IAP management. Initialized /// only after [initWithContext] has been called. /// - public static IInAppMessagesManager InAppMessages { - get { - return OneSignal.Default.InAppMessages; - } + public static IInAppMessagesManager InAppMessages + { + get { return OneSignal.Default.InAppMessages; } } /// /// Access to debug the SDK in the additional information is required to diagnose any /// SDK-related issues. Initialized immediately (can be used prior to [initWithContext]). - /// + /// /// WARNING: This should not be used in a production setting. - /// + /// /// - public static IDebugManager Debug { - get { - return OneSignal.Default.Debug; - } + public static IDebugManager Debug + { + get { return OneSignal.Default.Debug; } } /// /// Access to debug the SDK in the additional information is required to diagnose any /// SDK-related issues. Initialized immediately (can be used prior to [initWithContext]). - /// + /// /// WARNING: This should not be used in a production setting. - /// + /// /// - public static ILiveActivitiesManager LiveActivities { - get { - return OneSignal.Default.LiveActivities; - } + public static ILiveActivitiesManager LiveActivities + { + get { return OneSignal.Default.LiveActivities; } } /// /// Provides privacy consent. OneSignal Unity SDK will not initialize until this is true. /// - public static bool ConsentGiven { + public static bool ConsentGiven + { set => OneSignal.Default.ConsentGiven = value; } @@ -139,7 +134,8 @@ public static bool ConsentGiven { /// Allows you to delay the initialization of the SDK until is set to true. Must /// be set before is called. /// - public static bool ConsentRequired { + public static bool ConsentRequired + { set => OneSignal.Default.ConsentRequired = value; } @@ -147,21 +143,22 @@ public static bool ConsentRequired { /// Starts the OneSignal SDK /// /// Your application id from the OneSignal dashboard - public static void Initialize(string appId) { + public static void Initialize(string appId) + { OneSignal.Default.Initialize(appId); } /// /// Login to OneSignal under the user identified by the [externalId] provided. The act of /// logging a user into the OneSignal SDK will switch the [user] context to that specific user. - /// + /// /// * If the [externalId] exists the user will be retrieved and the context set from that /// user information. If operations have already been performed under a guest user, they /// *will not* be applied to the now logged in user (they will be lost). /// * If the [externalId] does not exist the user will be created and the context set from /// the current local state. If operations have already been performed under a guest user /// those operations *will* be applied to the newly created user. - /// + /// /// *Push Notifications and In-App Messaging* /// Logging in a new user will automatically transfer push notification and in-app messaging /// subscriptions from the current user (if there is one) to the newly logged in user. This is @@ -173,7 +170,8 @@ public static void Initialize(string appId) { /// trust for the login operation. Required when identity verification has been enabled. See /// [Identity Verification | OneSignal](https://documentation.onesignal.com/docs/identity-verification) /// - public static void Login(string externalId, string jwtBearerToken = null) { + public static void Login(string externalId, string jwtBearerToken = null) + { OneSignal.Default.Login(externalId, jwtBearerToken); } @@ -183,7 +181,8 @@ public static void Login(string externalId, string jwtBearerToken = null) { /// be retrieved, except through this device as long as the app remains installed and the app /// data is not cleared. /// - public static void Logout() { + public static void Logout() + { OneSignal.Default.Logout(); } } diff --git a/com.onesignal.unity.core/Runtime/OneSignalPlatform.cs b/com.onesignal.unity.core/Runtime/OneSignalPlatform.cs index db2ab8856..34d1420f8 100644 --- a/com.onesignal.unity.core/Runtime/OneSignalPlatform.cs +++ b/com.onesignal.unity.core/Runtime/OneSignalPlatform.cs @@ -26,30 +26,34 @@ */ using System; -using UnityEngine; using System.Collections.Generic; -using OneSignalSDK.Notifications; -using OneSignalSDK.InAppMessages; using OneSignalSDK.Debug; +using OneSignalSDK.InAppMessages; +using OneSignalSDK.LiveActivities; using OneSignalSDK.Location; +using OneSignalSDK.Notifications; using OneSignalSDK.Session; using OneSignalSDK.User; -using OneSignalSDK.LiveActivities; +using UnityEngine; -namespace OneSignalSDK { - public abstract class OneSignalPlatform { +namespace OneSignalSDK +{ + public abstract class OneSignalPlatform + { public const string VersionHeader = "050115"; internal static event Action OnInitialize; internal static string AppId { get; private set; } - protected static void _completedInit(string appId) { - AppId = appId; + protected static void _completedInit(string appId) + { + AppId = appId; OnInitialize?.Invoke(AppId); } - protected static void _init(string appId) { + protected static void _init(string appId) + { OnInitialize?.Invoke(appId); } @@ -70,7 +74,7 @@ protected static void _init(string appId) { /// The notification manager for accessing device-scoped notification management. Initialized /// only after [initWithContext] has been called. /// - public abstract INotificationsManager Notifications{ get; } + public abstract INotificationsManager Notifications { get; } /// /// The notification manager for accessing device-scoped notification management. Initialized @@ -87,18 +91,18 @@ protected static void _init(string appId) { /// /// Access to debug the SDK in the additional information is required to diagnose any /// SDK-related issues. Initialized immediately (can be used prior to [initWithContext]). - /// + /// /// WARNING: This should not be used in a production setting. - /// + /// /// public abstract IDebugManager Debug { get; } /// /// Access to debug the SDK in the additional information is required to diagnose any /// SDK-related issues. Initialized immediately (can be used prior to [initWithContext]). - /// + /// /// WARNING: This should not be used in a production setting. - /// + /// /// public abstract ILiveActivitiesManager LiveActivities { get; } @@ -122,14 +126,14 @@ protected static void _init(string appId) { /// /// Login to OneSignal under the user identified by the [externalId] provided. The act of /// logging a user into the OneSignal SDK will switch the [user] context to that specific user. - /// + /// /// * If the [externalId] exists the user will be retrieved and the context set from that /// user information. If operations have already been performed under a guest user, they /// *will not* be applied to the now logged in user (they will be lost). /// * If the [externalId] does not exist the user will be created and the context set from /// the current local state. If operations have already been performed under a guest user /// those operations *will* be applied to the newly created user. - /// + /// /// *Push Notifications and In-App Messaging* /// Logging in a new user will automatically transfer push notification and in-app messaging /// subscriptions from the current user (if there is one) to the newly logged in user. This is diff --git a/com.onesignal.unity.core/Runtime/Session/ISessionManager.cs b/com.onesignal.unity.core/Runtime/Session/ISessionManager.cs index 80e481c2e..0fbae915c 100644 --- a/com.onesignal.unity.core/Runtime/Session/ISessionManager.cs +++ b/com.onesignal.unity.core/Runtime/Session/ISessionManager.cs @@ -25,11 +25,13 @@ * THE SOFTWARE. */ -namespace OneSignalSDK.Session { +namespace OneSignalSDK.Session +{ /// /// The OneSignal session manager is responsible for managing the current session state. /// - public interface ISessionManager { + public interface ISessionManager + { /// /// Send a trackable custom event which is tied to push notification campaigns /// @@ -49,4 +51,4 @@ public interface ISessionManager { /// The value tied to the outcome. void AddOutcomeWithValue(string name, float value); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/User/IUserManager.cs b/com.onesignal.unity.core/Runtime/User/IUserManager.cs index 69fe0aa05..23eaaa4d8 100644 --- a/com.onesignal.unity.core/Runtime/User/IUserManager.cs +++ b/com.onesignal.unity.core/Runtime/User/IUserManager.cs @@ -28,10 +28,11 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using UnityEngine; using OneSignalSDK.User.Models; +using UnityEngine; -namespace OneSignalSDK.User { +namespace OneSignalSDK.User +{ /// /// Several states associated with the SDK can be changed in and outside of the application. /// @@ -39,7 +40,8 @@ public class UserStateChangedEventArgs : EventArgs { public UserChangedState State { get; } - public UserStateChangedEventArgs(UserChangedState state) { + public UserStateChangedEventArgs(UserChangedState state) + { State = state; } } @@ -50,7 +52,7 @@ public UserStateChangedEventArgs(UserChangedState state) { /// accessible by the current device. Once the application knows the identity of the user using their /// app, they should call [OneSignal.login] providing that identity to OneSignal, at which /// point all state in here will reflect the state of that known user. - /// + /// /// The current user is persisted across the application lifecycle, even when the application /// is restarted. It is up to the application developer to call [OneSignal.login] when /// the user of the application switches, or logs out, to ensure the identity tracked by OneSignal @@ -60,7 +62,8 @@ public UserStateChangedEventArgs(UserChangedState state) { /// 1. When the identity of the user changes (i.e. a login or a context switch) /// 2. When the identity of the user is lost (i.e. a logout) /// - public interface IUserManager { + public interface IUserManager + { /// /// The UUID generated by OneSignal to represent a user, null if this is currently unavailable. /// @@ -135,7 +138,7 @@ public interface IUserManager { /// Add/set aliases for the current user. If any alias already exists it will be overwritten. /// /// - /// A dictionary of the alias label -> alias id that should be set against the user. Each alias id + /// A dictionary of the alias label -> alias id that should be set against the user. Each alias id /// must be a unique value within the alias label across your entire user base so it can /// uniquely identify this user. /// @@ -177,4 +180,4 @@ public interface IUserManager { /// The sms address that the current user was subscribed for, and should no longer be. void RemoveSms(string sms); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/User/Internal/PushSubscriptionState.cs b/com.onesignal.unity.core/Runtime/User/Internal/PushSubscriptionState.cs index 0d20288c8..67907db24 100644 --- a/com.onesignal.unity.core/Runtime/User/Internal/PushSubscriptionState.cs +++ b/com.onesignal.unity.core/Runtime/User/Internal/PushSubscriptionState.cs @@ -28,36 +28,40 @@ using System; using OneSignalSDK.User.Models; -namespace OneSignalSDK.User.Internal { - [Serializable] public sealed class PushSubscriptionState : IPushSubscriptionState { +namespace OneSignalSDK.User.Internal +{ + [Serializable] + public sealed class PushSubscriptionState : IPushSubscriptionState + { /// /// Unique id of this subscription /// /// See https://documentation.onesignal.com/docs/subscriptions for more information public string Id => id; - + /// /// Whether this subscription is currently active /// public bool OptedIn => optedIn; - + /// /// The unique token provided by the device's operating system used to send push notifications /// public string Token => token; #region Native Field Handling - public string id; - public bool optedIn; - public string token; + public string id; + public bool optedIn; + public string token; #endregion - public PushSubscriptionState() {} + public PushSubscriptionState() { } - public PushSubscriptionState(string id, bool optedIn, string token) { + public PushSubscriptionState(string id, bool optedIn, string token) + { this.id = id; this.optedIn = optedIn; this.token = token; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/User/Internal/UserState.cs b/com.onesignal.unity.core/Runtime/User/Internal/UserState.cs index eab372c57..e2aaa6abd 100644 --- a/com.onesignal.unity.core/Runtime/User/Internal/UserState.cs +++ b/com.onesignal.unity.core/Runtime/User/Internal/UserState.cs @@ -28,19 +28,23 @@ using System; using OneSignalSDK.User; -namespace OneSignalSDK.User.Internal { - [Serializable] public sealed class UserState { +namespace OneSignalSDK.User.Internal +{ + [Serializable] + public sealed class UserState + { public string OneSignalId => onesignalId; public string ExternalId => externalId; #region Native Field Handling - public string onesignalId; - public string externalId; + public string onesignalId; + public string externalId; #endregion - public UserState(string onesignalId, string externalId) { + public UserState(string onesignalId, string externalId) + { this.onesignalId = onesignalId; this.externalId = externalId; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/User/Models/IPushSubscription.cs b/com.onesignal.unity.core/Runtime/User/Models/IPushSubscription.cs index fabdc919f..b6669d22b 100644 --- a/com.onesignal.unity.core/Runtime/User/Models/IPushSubscription.cs +++ b/com.onesignal.unity.core/Runtime/User/Models/IPushSubscription.cs @@ -30,7 +30,8 @@ using System.Threading.Tasks; using UnityEngine; -namespace OneSignalSDK.User.Models { +namespace OneSignalSDK.User.Models +{ /// /// Several states associated with the SDK can be changed in and outside of the application. /// @@ -38,7 +39,8 @@ public class PushSubscriptionChangedEventArgs : EventArgs { public PushSubscriptionChangedState State { get; } - public PushSubscriptionChangedEventArgs(PushSubscriptionChangedState state) { + public PushSubscriptionChangedEventArgs(PushSubscriptionChangedState state) + { State = state; } } @@ -47,7 +49,8 @@ public PushSubscriptionChangedEventArgs(PushSubscriptionChangedState state) { /// A push subscription allows a user to receive notifications through the push /// channel. /// - public interface IPushSubscription { + public interface IPushSubscription + { /// /// When this uers's subscription to push notifications has changed /// @@ -88,4 +91,4 @@ public interface IPushSubscription { /// void OptOut(); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/User/Models/IPushSubscriptionState.cs b/com.onesignal.unity.core/Runtime/User/Models/IPushSubscriptionState.cs index e2918ff02..7e23fa0e8 100644 --- a/com.onesignal.unity.core/Runtime/User/Models/IPushSubscriptionState.cs +++ b/com.onesignal.unity.core/Runtime/User/Models/IPushSubscriptionState.cs @@ -27,22 +27,24 @@ using System; -namespace OneSignalSDK.User.Models { - public interface IPushSubscriptionState { +namespace OneSignalSDK.User.Models +{ + public interface IPushSubscriptionState + { /// /// Unique id of this subscription /// /// See https://documentation.onesignal.com/docs/subscriptions for more information string Id { get; } - + /// /// Whether this subscription is currently active /// bool OptedIn { get; } - + /// /// The unique token provided by the device's operating system used to send push notifications /// string Token { get; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/User/Models/IUserState.cs b/com.onesignal.unity.core/Runtime/User/Models/IUserState.cs index 6bfcab177..2047a6765 100644 --- a/com.onesignal.unity.core/Runtime/User/Models/IUserState.cs +++ b/com.onesignal.unity.core/Runtime/User/Models/IUserState.cs @@ -27,15 +27,17 @@ using System; -namespace OneSignalSDK.User { - public interface IUserState { +namespace OneSignalSDK.User +{ + public interface IUserState + { /// /// The unique identifier for your OneSignal account. This will be an empty string until the /// user has been successfully logged in on the backend and assigned an ID. /// Use [Changed] to be notified when the [OneSignalId] has been successfully assigned. /// string OneSignalId { get; } - + /// /// The external identifier that you use to identify users. Use [Changed] to be notified /// when the [ExternalId] has been successfully assigned. This will be an empty string if no @@ -43,4 +45,4 @@ public interface IUserState { /// string ExternalId { get; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/User/Models/PushSubscriptionChangedState.cs b/com.onesignal.unity.core/Runtime/User/Models/PushSubscriptionChangedState.cs index 01f0ef590..59157cf38 100644 --- a/com.onesignal.unity.core/Runtime/User/Models/PushSubscriptionChangedState.cs +++ b/com.onesignal.unity.core/Runtime/User/Models/PushSubscriptionChangedState.cs @@ -27,15 +27,21 @@ using System; -namespace OneSignalSDK.User.Models { - public sealed class PushSubscriptionChangedState { +namespace OneSignalSDK.User.Models +{ + public sealed class PushSubscriptionChangedState + { public IPushSubscriptionState Previous { get; } public IPushSubscriptionState Current { get; } - public PushSubscriptionChangedState(IPushSubscriptionState previous, IPushSubscriptionState current) { + public PushSubscriptionChangedState( + IPushSubscriptionState previous, + IPushSubscriptionState current + ) + { Previous = previous; Current = current; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/User/Models/UserChangedState.cs b/com.onesignal.unity.core/Runtime/User/Models/UserChangedState.cs index 419fe0336..647a2f7a6 100644 --- a/com.onesignal.unity.core/Runtime/User/Models/UserChangedState.cs +++ b/com.onesignal.unity.core/Runtime/User/Models/UserChangedState.cs @@ -28,12 +28,15 @@ using System; using OneSignalSDK.User.Internal; -namespace OneSignalSDK.User { - public sealed class UserChangedState { +namespace OneSignalSDK.User +{ + public sealed class UserChangedState + { public UserState Current { get; } - public UserChangedState(UserState state) { + public UserChangedState(UserState state) + { Current = state; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Utilities/MiniJSON.cs b/com.onesignal.unity.core/Runtime/Utilities/MiniJSON.cs index 2659f1ab3..df91487a0 100644 --- a/com.onesignal.unity.core/Runtime/Utilities/MiniJSON.cs +++ b/com.onesignal.unity.core/Runtime/Utilities/MiniJSON.cs @@ -33,7 +33,8 @@ using System.IO; using System.Text; -namespace OneSignalSDK { +namespace OneSignalSDK +{ // Forked from https://github.com/Jackyjjc/MiniJSON.cs // version: 6de00beb134bbab9d873033a48b32e4067ed0c25 @@ -117,7 +118,7 @@ enum TOKEN NUMBER, TRUE, FALSE, - NULL + NULL, }; StringReader json; @@ -304,7 +305,7 @@ string ParseString() hex[i] = NextChar; } - s.Append((char) Convert.ToInt32(new string(hex), 16)); + s.Append((char)Convert.ToInt32(new string(hex), 16)); break; default: s.Append(c); @@ -325,17 +326,29 @@ object ParseNumber() { string number = NextWord; - if (number.IndexOf('.') == -1 && number.IndexOf('E') == -1 && number.IndexOf('e') == -1) + if ( + number.IndexOf('.') == -1 + && number.IndexOf('E') == -1 + && number.IndexOf('e') == -1 + ) { long parsedInt; - Int64.TryParse(number, System.Globalization.NumberStyles.Any, - System.Globalization.CultureInfo.InvariantCulture, out parsedInt); + Int64.TryParse( + number, + System.Globalization.NumberStyles.Any, + System.Globalization.CultureInfo.InvariantCulture, + out parsedInt + ); return parsedInt; } double parsedDouble; - Double.TryParse(number, System.Globalization.NumberStyles.Any, - System.Globalization.CultureInfo.InvariantCulture, out parsedDouble); + Double.TryParse( + number, + System.Globalization.NumberStyles.Any, + System.Globalization.CultureInfo.InvariantCulture, + out parsedDouble + ); return parsedDouble; } @@ -449,9 +462,7 @@ TOKEN NextToken /// indentations. /// Number of spaces for each level of indentation. /// A JSON encoded string, or null if object 'json' is not serializable - public static string Serialize(object obj, - bool humanReadable = false, - int indentSpaces = 2) + public static string Serialize(object obj, bool humanReadable = false, int indentSpaces = 2) { return Serializer.MakeSerialization(obj, humanReadable, indentSpaces); } @@ -496,7 +507,7 @@ void SerializeValue(object value) } else if (value is bool) { - builder.Append((bool) value ? "true" : "false"); + builder.Append((bool)value ? "true" : "false"); } else if ((asList = value as IList) != null) { @@ -508,7 +519,7 @@ void SerializeValue(object value) } else if (value is char) { - SerializeString(new string((char) value, 1)); + SerializeString(new string((char)value, 1)); } else { @@ -533,17 +544,20 @@ void SerializeObject(IDictionary obj) { if (first) { - if (humanReadable) AppendNewLineFunc(); + if (humanReadable) + AppendNewLineFunc(); } else { builder.Append(','); - if (humanReadable) AppendNewLineFunc(); + if (humanReadable) + AppendNewLineFunc(); } SerializeString(e.ToString()); builder.Append(':'); - if (humanReadable) builder.Append(' '); + if (humanReadable) + builder.Append(' '); SerializeValue(obj[e]); @@ -551,7 +565,8 @@ void SerializeObject(IDictionary obj) } --indentLevel; - if (humanReadable && obj.Count > 0) AppendNewLineFunc(); + if (humanReadable && obj.Count > 0) + AppendNewLineFunc(); builder.Append('}'); } @@ -568,12 +583,14 @@ void SerializeArray(IList anArray) object obj = anArray[i]; if (first) { - if (humanReadable) AppendNewLineFunc(); + if (humanReadable) + AppendNewLineFunc(); } else { builder.Append(','); - if (humanReadable) AppendNewLineFunc(); + if (humanReadable) + AppendNewLineFunc(); } SerializeValue(obj); @@ -582,7 +599,8 @@ void SerializeArray(IList anArray) } --indentLevel; - if (humanReadable && anArray.Count > 0) AppendNewLineFunc(); + if (humanReadable && anArray.Count > 0) + AppendNewLineFunc(); builder.Append(']'); } @@ -644,24 +662,33 @@ void SerializeOther(object value) // Previously floats and doubles lost precision too. if (value is float) { - builder.Append(((float) value).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + builder.Append( + ((float)value).ToString( + "R", + System.Globalization.CultureInfo.InvariantCulture + ) + ); } - else if (value is int - || value is uint - || value is long - || value is sbyte - || value is byte - || value is short - || value is ushort - || value is ulong) + else if ( + value is int + || value is uint + || value is long + || value is sbyte + || value is byte + || value is short + || value is ushort + || value is ulong + ) { builder.Append(value); } - else if (value is double - || value is decimal) + else if (value is double || value is decimal) { - builder.Append(Convert.ToDouble(value) - .ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + builder.Append( + Convert + .ToDouble(value) + .ToString("R", System.Globalization.CultureInfo.InvariantCulture) + ); } else { @@ -670,4 +697,4 @@ void SerializeOther(object value) } } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Utilities/ReflectionHelpers.cs b/com.onesignal.unity.core/Runtime/Utilities/ReflectionHelpers.cs index be9d1925f..c9abdb60b 100644 --- a/com.onesignal.unity.core/Runtime/Utilities/ReflectionHelpers.cs +++ b/com.onesignal.unity.core/Runtime/Utilities/ReflectionHelpers.cs @@ -2,20 +2,25 @@ using System.Collections.Generic; using System.Linq; -namespace OneSignalSDK { - public static class ReflectionHelpers { - public static IEnumerable FindAllAssignableTypes(string assemblyFilter) { +namespace OneSignalSDK +{ + public static class ReflectionHelpers + { + public static IEnumerable FindAllAssignableTypes(string assemblyFilter) + { var assignableType = typeof(T); - + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); - var filteredAssemblies = assemblies.Where(assembly - => assembly.FullName.Contains(assemblyFilter)); - + var filteredAssemblies = assemblies.Where(assembly => + assembly.FullName.Contains(assemblyFilter) + ); + var allTypes = filteredAssemblies.SelectMany(assembly => assembly.GetTypes()); - var assignableTypes = allTypes.Where(type - => type != assignableType && assignableType.IsAssignableFrom(type)); + var assignableTypes = allTypes.Where(type => + type != assignableType && assignableType.IsAssignableFrom(type) + ); return assignableTypes; } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Runtime/Utilities/UnityMainThreadDispatch.cs b/com.onesignal.unity.core/Runtime/Utilities/UnityMainThreadDispatch.cs index 4ba7b0bbb..2f34885eb 100644 --- a/com.onesignal.unity.core/Runtime/Utilities/UnityMainThreadDispatch.cs +++ b/com.onesignal.unity.core/Runtime/Utilities/UnityMainThreadDispatch.cs @@ -31,11 +31,13 @@ using UnityEditor; #endif -namespace OneSignalSDK { +namespace OneSignalSDK +{ /// /// Helper class for ensuring a callback is invoked on the main Unity thread /// - public static class UnityMainThreadDispatch { + public static class UnityMainThreadDispatch + { /// /// Synchronous; blocks until the callback completes /// @@ -54,4 +56,4 @@ public static class UnityMainThreadDispatch { [RuntimeInitializeOnLoadMethod] private static void _initialize() => _context = _context ?? SynchronizationContext.Current; } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.core/Samples~/OneSignalExampleBehaviour.cs b/com.onesignal.unity.core/Samples~/OneSignalExampleBehaviour.cs index 9df95bfd2..5198ab7f9 100644 --- a/com.onesignal.unity.core/Samples~/OneSignalExampleBehaviour.cs +++ b/com.onesignal.unity.core/Samples~/OneSignalExampleBehaviour.cs @@ -43,7 +43,8 @@ /// /// Example class to show how an application can utilize the public methods of the OneSignal SDK /// -public class OneSignalExampleBehaviour : MonoBehaviour { +public class OneSignalExampleBehaviour : MonoBehaviour +{ /// /// set to an email address you would like to test notifications against /// @@ -71,72 +72,72 @@ public class OneSignalExampleBehaviour : MonoBehaviour { public bool consentRequired; /// - /// + /// /// public bool consentGiven; /// - /// + /// /// public string language; /// - /// + /// /// public string aliasKey; /// - /// + /// /// public string aliasValue; /// - /// + /// /// public string tagKey; /// - /// + /// /// public string tagValue; /// - /// + /// /// public string triggerKey; /// - /// + /// /// public string triggerValue; /// - /// + /// /// public string outcomeKey; /// - /// + /// /// public float outcomeValue; /// - /// + /// /// public string liveActivityId; /// - /// + /// /// public string liveActivityIdToken; /// - /// + /// /// public string liveActivityType; /// - /// + /// /// public string liveActivityTypeToken; @@ -144,7 +145,8 @@ public class OneSignalExampleBehaviour : MonoBehaviour { /// we recommend initializing OneSignal early in your application's lifecycle such as in the Start method of a /// MonoBehaviour in your opening Scene /// - private void Start() { + private void Start() + { // Enable lines below to debug issues with OneSignal OneSignal.Debug.LogLevel = LogLevel.Verbose; OneSignal.Debug.AlertLevel = LogLevel.Fatal; @@ -179,54 +181,70 @@ private void Start() { /* * SDK events */ - - private void _notificationOnClick(object sender, NotificationClickEventArgs e) { + + private void _notificationOnClick(object sender, NotificationClickEventArgs e) + { _log($"Notification was clicked with Notification: {JsonUtility.ToJson(e.Notification)}"); _log($"Notification was clicked with Result: {JsonUtility.ToJson(e.Result)}"); } - private void _notificationOnDisplay(object sender, NotificationWillDisplayEventArgs e) { - var additionalData = e.Notification.AdditionalData != null - ? Json.Serialize(e.Notification.AdditionalData) + private void _notificationOnDisplay(object sender, NotificationWillDisplayEventArgs e) + { + var additionalData = + e.Notification.AdditionalData != null + ? Json.Serialize(e.Notification.AdditionalData) : null; - _log($"Notification was received in foreground: {JsonUtility.ToJson(e.Notification)}\n{additionalData}"); - + _log( + $"Notification was received in foreground: {JsonUtility.ToJson(e.Notification)}\n{additionalData}" + ); + e.Notification.Display(); } - private void _notificationPermissionChanged(object sender, NotificationPermissionChangedEventArgs e) { + private void _notificationPermissionChanged( + object sender, + NotificationPermissionChangedEventArgs e + ) + { _log($"Notification Permission changed to: {e.Permission}"); } - private void _iamWillDisplay(object sender, InAppMessageWillDisplayEventArgs e) { + private void _iamWillDisplay(object sender, InAppMessageWillDisplayEventArgs e) + { _log($"IAM will display: {JsonUtility.ToJson(e.Message)}"); } - private void _iamDidDisplay(object sender, InAppMessageDidDisplayEventArgs e) { + private void _iamDidDisplay(object sender, InAppMessageDidDisplayEventArgs e) + { _log($"IAM did display: {JsonUtility.ToJson(e.Message)}"); } - private void _iamWillDismiss(object sender, InAppMessageWillDismissEventArgs e) { + private void _iamWillDismiss(object sender, InAppMessageWillDismissEventArgs e) + { _log($"IAM will dismiss: {JsonUtility.ToJson(e.Message)}"); } - private void _iamDidDismiss(object sender, InAppMessageDidDismissEventArgs e) { + private void _iamDidDismiss(object sender, InAppMessageDidDismissEventArgs e) + { _log($"IAM did dismiss: {JsonUtility.ToJson(e.Message)}"); } - private void _iamOnClick(object sender, InAppMessageClickEventArgs e) { + private void _iamOnClick(object sender, InAppMessageClickEventArgs e) + { _log($"IAM was clicked with Message: {JsonUtility.ToJson(e.Message)}"); _log($"IAM was clicked with Result: {JsonUtility.ToJson(e.Result)}"); _log($"IAM was clicked with Result UrlTarget: " + e.Result.UrlTarget.ToString()); } - private void _pushSubscriptionChanged(object sender, PushSubscriptionChangedEventArgs e) { + private void _pushSubscriptionChanged(object sender, PushSubscriptionChangedEventArgs e) + { _log($"Push subscription changed from previous: {JsonUtility.ToJson(e.State.Previous)}"); _log($"Push subscription changed to current: {JsonUtility.ToJson(e.State.Current)}"); } - private void _userStateChanged(object sender, UserStateChangedEventArgs e) { + private void _userStateChanged(object sender, UserStateChangedEventArgs e) + { _log($"OneSignalId changed : {e.State.Current.OneSignalId}"); _log($"ExternalId changed : {e.State.Current.ExternalId}"); } @@ -235,25 +253,29 @@ private void _userStateChanged(object sender, UserStateChangedEventArgs e) { * SDK setup */ - public void ToggleConsentRequired() { + public void ToggleConsentRequired() + { consentRequired = !consentRequired; _log($"Toggling ConsentRequired to {consentRequired}"); OneSignal.ConsentRequired = consentRequired; } - public void ToggleConsentGiven() { + public void ToggleConsentGiven() + { consentGiven = !consentGiven; _log($"Toggling ConsentGiven to {consentGiven}"); OneSignal.ConsentGiven = consentGiven; } - public void SetLogLevel() { + public void SetLogLevel() + { var newLevel = _nextEnum(OneSignal.Debug.LogLevel); _log($"Setting LogLevel to {newLevel}"); OneSignal.Debug.LogLevel = newLevel; } - public void SetAlertLevel() { + public void SetAlertLevel() + { var newLevel = _nextEnum(OneSignal.Debug.AlertLevel); _log($"Setting AlertLevel to {newLevel}"); OneSignal.Debug.AlertLevel = newLevel; @@ -263,67 +285,80 @@ public void SetAlertLevel() { * User identification */ - public void LoginOneSignalUser() { + public void LoginOneSignalUser() + { _log($"Logging in user ({externalId})"); OneSignal.Login(externalId); } - - public void LogoutOneSignalUser() { + + public void LogoutOneSignalUser() + { _log($"Logging out user"); OneSignal.Logout(); } - public void PushSubscriptionOptIn() { + public void PushSubscriptionOptIn() + { _log($"Opting in push subscription"); OneSignal.User.PushSubscription.OptIn(); } - public void PushSubscriptionOptOut() { + public void PushSubscriptionOptOut() + { _log($"Opting out push subscription"); OneSignal.User.PushSubscription.OptOut(); } - public void AddEmail() { + public void AddEmail() + { _log($"Adding email ({email})"); OneSignal.User.AddEmail(email); } - - public void RemoveEmail() { + + public void RemoveEmail() + { _log($"Removing email ({email})"); OneSignal.User.RemoveEmail(email); } - public void AddSms() { + public void AddSms() + { _log($"Adding sms ({phoneNumber})"); OneSignal.User.AddSms(phoneNumber); } - - public void RemoveSms() { + + public void RemoveSms() + { _log($"Removing sms ({phoneNumber})"); OneSignal.User.RemoveSms(phoneNumber); } - public void SetLanguage() { + public void SetLanguage() + { _log($"Setting language for the user to ({language})"); OneSignal.User.Language = language; } - public void AddAlias() { + public void AddAlias() + { _log($"Adding alias with label {aliasKey} and id {aliasValue}"); OneSignal.User.AddAlias(aliasKey, aliasValue); } - public void RemoveAlias() { + public void RemoveAlias() + { _log($"Removing alias with label {aliasKey}"); OneSignal.User.RemoveAlias(aliasKey); } - public void GetOneSignalId() { + public void GetOneSignalId() + { string onesignalId = OneSignal.User.OneSignalId ?? "null"; _log($"Get OneSignalId {onesignalId}"); } - public void GetExternalId() { + public void GetExternalId() + { string externalId = OneSignal.User.ExternalId ?? "null"; _log($"Get ExternalId {externalId}"); } @@ -332,8 +367,11 @@ public void GetExternalId() { * Push */ - public async void PromptForPush() { - _log($"Can request push notification permission: {OneSignal.Notifications.CanRequestPermission}"); + public async void PromptForPush() + { + _log( + $"Can request push notification permission: {OneSignal.Notifications.CanRequestPermission}" + ); _log("Opening permission prompt for push notifications and awaiting result..."); @@ -345,21 +383,24 @@ public async void PromptForPush() { _log("Notification permission denied"); } - public void ClearPush() { + public void ClearPush() + { _log("Clearing existing OneSignal push notifications"); - + OneSignal.Notifications.ClearAllNotifications(); - + _log("Notifications cleared"); } - public void GetNotificationsPermission() { + public void GetNotificationsPermission() + { var permission = OneSignal.Notifications.Permission; _log($"Notifications permission is: {permission}"); } - public void GetNotificationsPermissionNative() { + public void GetNotificationsPermissionNative() + { var permissionNative = OneSignal.Notifications.PermissionNative; _log($"Notifications native permission is: {permissionNative.ToString()}"); @@ -369,22 +410,26 @@ public void GetNotificationsPermissionNative() { * In-App Messages */ - public void AddTrigger() { + public void AddTrigger() + { _log($"Adding trigger with key {triggerKey} and value {triggerValue}"); OneSignal.InAppMessages.AddTrigger(triggerKey, triggerValue); } - public void RemoveTrigger() { + public void RemoveTrigger() + { _log($"Removing trigger for key {triggerKey}"); OneSignal.InAppMessages.RemoveTrigger(triggerKey); } - public void ClearTriggers() { + public void ClearTriggers() + { _log("Clearing all trigger keys and values from user"); OneSignal.InAppMessages.ClearTriggers(); } - public void TogglePauseInAppMessages() { + public void TogglePauseInAppMessages() + { _log($"Toggling Pausing InAppMessages to {!OneSignal.InAppMessages.Paused}"); OneSignal.InAppMessages.Paused = !OneSignal.InAppMessages.Paused; } @@ -393,21 +438,24 @@ public void TogglePauseInAppMessages() { * Tags */ - public void AddTag() { + public void AddTag() + { _log($"Adding tag with key {tagKey} and value {tagValue}"); OneSignal.User.AddTag(tagKey, tagValue); } - public void RemoveTag() { + public void RemoveTag() + { _log($"Removing tag for key {tagKey}"); OneSignal.User.RemoveTag(tagKey); - } - public void GetTags() { + public void GetTags() + { Dictionary dict = OneSignal.User.GetTags(); string dictionaryString = "{"; - foreach(KeyValuePair keyValues in dict) { + foreach (KeyValuePair keyValues in dict) + { dictionaryString += keyValues.Key + " : " + keyValues.Value + ", "; } _log($"Get all user tags " + dictionaryString.TrimEnd(',', ' ') + "}"); @@ -417,17 +465,20 @@ public void GetTags() { * Outcomes */ - public void AddOutcome() { + public void AddOutcome() + { _log($"Adding outcome with key {outcomeKey}"); OneSignal.Session.AddOutcome(outcomeKey); } - public void AddUniqueOutcome() { + public void AddUniqueOutcome() + { _log($"Adding unique outcome with key {outcomeKey}"); OneSignal.Session.AddUniqueOutcome(outcomeKey); } - public void AddOutcomeWithValue() { + public void AddOutcomeWithValue() + { _log($"Adding outcome with key {outcomeKey} and value {outcomeValue}"); OneSignal.Session.AddOutcomeWithValue(outcomeKey, outcomeValue); } @@ -436,12 +487,14 @@ public void AddOutcomeWithValue() { * Location */ - public void PromptLocation() { + public void PromptLocation() + { _log("Opening permission prompt for location"); OneSignal.Location.RequestPermission(); } - public void ToggleShareLocation() { + public void ToggleShareLocation() + { _log($"Toggling Location IsShared to {!OneSignal.Location.IsShared}"); OneSignal.Location.IsShared = !OneSignal.Location.IsShared; } @@ -450,26 +503,31 @@ public void ToggleShareLocation() { * iOS */ - public void StartDefaultLiveActivity() { + public void StartDefaultLiveActivity() + { _log($"Start Default Live Activity with id: {liveActivityId}..."); OneSignal.LiveActivities.StartDefault( liveActivityId, - new Dictionary() { - { "title", "Welcome!" } - }, - new Dictionary() { - { "message", new Dictionary() { - { "en", "Hello World!"} - }}, + new Dictionary() { { "title", "Welcome!" } }, + new Dictionary() + { + { + "message", + new Dictionary() { { "en", "Hello World!" } } + }, { "intValue", 3 }, { "doubleValue", 3.14 }, - { "boolValue", true } - }); + { "boolValue", true }, + } + ); } - public async void EnterLiveActivityAsync() { - _log($"Entering Live Activity with id: {liveActivityId} and token: {liveActivityIdToken} and awaiting result..."); + public async void EnterLiveActivityAsync() + { + _log( + $"Entering Live Activity with id: {liveActivityId} and token: {liveActivityIdToken} and awaiting result..." + ); var result = await OneSignal.LiveActivities.EnterAsync(liveActivityId, liveActivityIdToken); @@ -479,7 +537,8 @@ public async void EnterLiveActivityAsync() { _log("Live Activity enter failed"); } - public async void ExitLiveActivityAsync() { + public async void ExitLiveActivityAsync() + { _log($"Exiting Live Activity with id: {liveActivityId} and awaiting result..."); var result = await OneSignal.LiveActivities.ExitAsync(liveActivityId); @@ -490,19 +549,23 @@ public async void ExitLiveActivityAsync() { _log("Live Activity exit failed"); } - public void SetPushToStartToken() { - _log($"Set Push To Start Token for type: {liveActivityType} with token: {liveActivityTypeToken}..."); + public void SetPushToStartToken() + { + _log( + $"Set Push To Start Token for type: {liveActivityType} with token: {liveActivityTypeToken}..." + ); OneSignal.LiveActivities.SetPushToStartToken(liveActivityType, liveActivityTypeToken); } - public void RemovePushToStartToken() { + public void RemovePushToStartToken() + { _log($"Remove Push To Start Token for type: {liveActivityType}..."); OneSignal.LiveActivities.RemovePushToStartToken(liveActivityType); } -#region Rendering + #region Rendering /* * You can safely ignore everything in this region and below */ @@ -513,62 +576,77 @@ public void RemovePushToStartToken() { public void SetAppIdString(string newVal) => appId = newVal; public void SetExternalIdString(string newVal) => externalId = newVal; + public void SetEmailString(string newVal) => email = newVal; + public void SetPhoneNumberString(string newVal) => phoneNumber = newVal; + public void SetLanguageString(string newVal) => language = newVal; public void SetAliasKey(string newVal) => aliasKey = newVal; + public void SetAliasValue(string newVal) => aliasValue = newVal; public void SetTriggerKey(string newVal) => triggerKey = newVal; + public void SetTriggerValue(string newVal) => triggerValue = newVal; public void SetTagKey(string newVal) => tagKey = newVal; + public void SetTagValue(string newVal) => tagValue = newVal; public void SetOutcomeKey(string newVal) => outcomeKey = newVal; + public void SetOutcomeValue(string newVal) => outcomeValue = Convert.ToSingle(newVal); public void SetLiveActivityId(string newVal) => liveActivityId = newVal; + public void SetLiveActivityIdToken(string newVal) => liveActivityIdToken = newVal; public void SetLiveActivityType(string newVal) => liveActivityType = newVal; + public void SetLiveActivityTypeToken(string newVal) => liveActivityTypeToken = newVal; - private void Awake() { - SDKDebug.LogIntercept += _log; - SDKDebug.WarnIntercept += _warn; + private void Awake() + { + SDKDebug.LogIntercept += _log; + SDKDebug.WarnIntercept += _warn; SDKDebug.ErrorIntercept += _error; appIdText.text = appId; } - private void _log(object message) { + private void _log(object message) + { string green = "#3BB674"; UnityEngine.Debug.Log(message); console.text += $"\nI> {message}"; } - private void _warn(object message) { + private void _warn(object message) + { string yellow = "#FFA940"; UnityEngine.Debug.LogWarning(message); console.text += $"\nW> {message}"; } - private void _error(object message) { + private void _error(object message) + { string red = "#E54B4D"; UnityEngine.Debug.LogError(message); console.text += $"\nE> {message}"; } -#endregion + #endregion -#region Helpers - private static T _nextEnum(T src) where T : struct { + #region Helpers + private static T _nextEnum(T src) + where T : struct + { if (!typeof(T).IsEnum) throw new ArgumentException($"Argument {typeof(T).FullName} is not an Enum"); var vals = (T[])Enum.GetValues(src.GetType()); var next = Array.IndexOf(vals, src) + 1; return vals.Length == next ? vals[0] : vals[next]; } -#endregion + #endregion } -#endif \ No newline at end of file +#endif diff --git a/com.onesignal.unity.ios/Editor/BuildPostProcessor.cs b/com.onesignal.unity.ios/Editor/BuildPostProcessor.cs index ff0784208..e03b85bd1 100644 --- a/com.onesignal.unity.ios/Editor/BuildPostProcessor.cs +++ b/com.onesignal.unity.ios/Editor/BuildPostProcessor.cs @@ -61,23 +61,36 @@ using UnityEditor.Build.Reporting; using UnityEditor.iOS.Xcode.Extensions; using Debug = UnityEngine.Debug; - using UnityEditor.Callbacks; -namespace OneSignalSDK.iOS { +namespace OneSignalSDK.iOS +{ /// /// Adds required frameworks to the iOS project, and adds the OneSignalNotificationServiceExtension. Also handles /// making sure both targets (app and extension service) have the correct dependencies /// - public class BuildPostProcessor : IPostprocessBuildWithReport { + public class BuildPostProcessor : IPostprocessBuildWithReport + { private const string ServiceExtensionTargetName = "OneSignalNotificationServiceExtension"; private const string ServiceExtensionFilename = "NotificationService.swift"; private const string DependenciesFilename = "OneSignaliOSDependencies.xml"; private const string PackageName = "com.onesignal.unity.ios"; - private static readonly string EditorFilesPath = Path.Combine("Packages", PackageName, "Editor"); - private static readonly string PluginLibrariesPath = Path.Combine(PackageName, "Runtime", "Plugins", "iOS"); - private static readonly string PluginFilesPath = Path.Combine("Packages", PluginLibrariesPath); + private static readonly string EditorFilesPath = Path.Combine( + "Packages", + PackageName, + "Editor" + ); + private static readonly string PluginLibrariesPath = Path.Combine( + PackageName, + "Runtime", + "Plugins", + "iOS" + ); + private static readonly string PluginFilesPath = Path.Combine( + "Packages", + PluginLibrariesPath + ); private string _outputPath; private string _projectPath; @@ -96,18 +109,19 @@ public class BuildPostProcessor : IPostprocessBuildWithReport { /// /// Entry for the build post processing necessary to get the OneSignal SDK iOS up and running /// - public void OnPostprocessBuild(BuildReport report) { + public void OnPostprocessBuild(BuildReport report) + { if (report.summary.platform != BuildTarget.iOS) return; // Load the project - _outputPath = report.summary.outputPath; + _outputPath = report.summary.outputPath; _projectPath = PBXProject.GetPBXProjectPath(_outputPath); _project.ReadFromString(File.ReadAllText(_projectPath)); - + // Turn on capabilities required by OneSignal AddProjectCapabilities(); - + // Add the service extension AddNotificationServiceExtension(); @@ -120,22 +134,31 @@ public void OnPostprocessBuild(BuildReport report) { /// /// Get existing entitlements file if exists or creates a new file, adds it to the project, and returns the path /// - private string GetEntitlementsPath(string targetGuid, string targetName) { - var relativePath = _project.GetBuildPropertyForAnyConfig(targetGuid, "CODE_SIGN_ENTITLEMENTS"); + private string GetEntitlementsPath(string targetGuid, string targetName) + { + var relativePath = _project.GetBuildPropertyForAnyConfig( + targetGuid, + "CODE_SIGN_ENTITLEMENTS" + ); - if (relativePath != null) { + if (relativePath != null) + { var fullPath = Path.Combine(_outputPath, relativePath); if (File.Exists(fullPath)) return fullPath; } - - var entitlementsPath = Path.Combine(_outputPath, targetName, $"{targetName}.entitlements"); - + + var entitlementsPath = Path.Combine( + _outputPath, + targetName, + $"{targetName}.entitlements" + ); + // make new file var entitlementsPlist = new PlistDocument(); entitlementsPlist.WriteToFile(entitlementsPath); - + // Copy the entitlement file to the xcode project var entitlementFileName = Path.GetFileName(entitlementsPath); var relativeDestination = targetName + "/" + entitlementFileName; @@ -146,28 +169,34 @@ private string GetEntitlementsPath(string targetGuid, string targetName) { return relativeDestination; } - + /// /// Add the required capabilities and entitlements for OneSignal /// - private void AddProjectCapabilities() { + private void AddProjectCapabilities() + { var targetGuid = _project.GetMainTargetGuid(); var targetName = _project.GetMainTargetName(); var entitlementsPath = GetEntitlementsPath(targetGuid, targetName); - var projCapability = new ProjectCapabilityManager(_projectPath, entitlementsPath, targetName); + var projCapability = new ProjectCapabilityManager( + _projectPath, + entitlementsPath, + targetName + ); projCapability.AddBackgroundModes(BackgroundModesOptions.RemoteNotifications); projCapability.AddPushNotifications(false); projCapability.AddAppGroups(new[] { _appGroupName }); - + projCapability.WriteToFile(); } - + /// /// Create and add the notification extension to the project /// - private void AddNotificationServiceExtension() { + private void AddNotificationServiceExtension() + { #if !UNITY_CLOUD_BUILD // refresh plist and podfile on appends ExtensionCreatePlist(_outputPath); @@ -179,9 +208,12 @@ private void AddNotificationServiceExtension() { if (!string.IsNullOrEmpty(extensionGuid)) return; - extensionGuid = _project.AddAppExtension(_project.GetMainTargetGuid(), + extensionGuid = _project.AddAppExtension( + _project.GetMainTargetGuid(), ServiceExtensionTargetName, - PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS) + "." + ServiceExtensionTargetName, + PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS) + + "." + + ServiceExtensionTargetName, ServiceExtensionTargetName + "/" + "Info.plist" // Unix path as it's used by Xcode ); @@ -192,20 +224,31 @@ private void AddNotificationServiceExtension() { _project.SetBuildProperty(extensionGuid, "IPHONEOS_DEPLOYMENT_TARGET", "10.0"); _project.SetBuildProperty(extensionGuid, "SWIFT_VERSION", "5.0"); _project.SetBuildProperty(extensionGuid, "ARCHS", "arm64"); - _project.SetBuildProperty(extensionGuid, "DEVELOPMENT_TEAM", PlayerSettings.iOS.appleDeveloperTeamID); + _project.SetBuildProperty( + extensionGuid, + "DEVELOPMENT_TEAM", + PlayerSettings.iOS.appleDeveloperTeamID + ); _project.SetBuildProperty(extensionGuid, "ENABLE_BITCODE", "NO"); - _project.AddBuildProperty(extensionGuid, "LIBRARY_SEARCH_PATHS", - $"$(PROJECT_DIR)/Libraries/{PluginLibrariesPath.Replace("\\", "/")}"); + _project.AddBuildProperty( + extensionGuid, + "LIBRARY_SEARCH_PATHS", + $"$(PROJECT_DIR)/Libraries/{PluginLibrariesPath.Replace("\\", "/")}" + ); _project.WriteToFile(_projectPath); // add capabilities + entitlements var entitlementsPath = GetEntitlementsPath(extensionGuid, ServiceExtensionTargetName); - var projCapability = new ProjectCapabilityManager(_projectPath, entitlementsPath, ServiceExtensionTargetName); - + var projCapability = new ProjectCapabilityManager( + _projectPath, + entitlementsPath, + ServiceExtensionTargetName + ); + projCapability.AddAppGroups(new[] { _appGroupName }); - + projCapability.WriteToFile(); #endif } @@ -213,80 +256,109 @@ private void AddNotificationServiceExtension() { /// /// Add the swift source file required by the notification extension /// - private void ExtensionAddSourceFiles(string extensionGuid) { - var buildPhaseID = _project.AddSourcesBuildPhase(extensionGuid); - var sourcePath = Path.Combine(PluginFilesPath, ServiceExtensionFilename); - var destPathRelative = Path.Combine(ServiceExtensionTargetName, ServiceExtensionFilename); + private void ExtensionAddSourceFiles(string extensionGuid) + { + var buildPhaseID = _project.AddSourcesBuildPhase(extensionGuid); + var sourcePath = Path.Combine(PluginFilesPath, ServiceExtensionFilename); + var destPathRelative = Path.Combine( + ServiceExtensionTargetName, + ServiceExtensionFilename + ); var destPath = Path.Combine(_outputPath, destPathRelative); if (!File.Exists(destPath)) - FileUtil.CopyFileOrDirectory(sourcePath.Replace("\\", "/"), destPath.Replace("\\", "/")); + FileUtil.CopyFileOrDirectory( + sourcePath.Replace("\\", "/"), + destPath.Replace("\\", "/") + ); var sourceFileGuid = _project.AddFile(destPathRelative, destPathRelative); _project.AddFileToBuildSection(extensionGuid, buildPhaseID, sourceFileGuid); } - + /// /// Create a .plist file for the extension /// /// NOTE: File in Xcode project is replaced everytime, never appends - private bool ExtensionCreatePlist(string path) { + private bool ExtensionCreatePlist(string path) + { var extensionPath = Path.Combine(path, ServiceExtensionTargetName); Directory.CreateDirectory(extensionPath); - var plistPath = Path.Combine(extensionPath, "Info.plist"); + var plistPath = Path.Combine(extensionPath, "Info.plist"); var alreadyExists = File.Exists(plistPath); var notificationServicePlist = new PlistDocument(); notificationServicePlist.ReadFromFile(Path.Combine(PluginFilesPath, "Info.plist")); - notificationServicePlist.root.SetString("CFBundleShortVersionString", PlayerSettings.bundleVersion); - notificationServicePlist.root.SetString("CFBundleVersion", PlayerSettings.iOS.buildNumber); + notificationServicePlist.root.SetString( + "CFBundleShortVersionString", + PlayerSettings.bundleVersion + ); + notificationServicePlist.root.SetString( + "CFBundleVersion", + PlayerSettings.iOS.buildNumber + ); notificationServicePlist.WriteToFile(plistPath); - + return alreadyExists; } - private void ExtensionAddPodsToTarget() { + private void ExtensionAddPodsToTarget() + { var podfilePath = Path.Combine(_outputPath, "Podfile"); - if (!File.Exists(podfilePath)) { - Debug.LogError($"Could not find Podfile. {ServiceExtensionFilename} will have errors."); + if (!File.Exists(podfilePath)) + { + Debug.LogError( + $"Could not find Podfile. {ServiceExtensionFilename} will have errors." + ); return; } var dependenciesFilePath = Path.Combine(EditorFilesPath, DependenciesFilename); - if (!File.Exists(dependenciesFilePath)) { + if (!File.Exists(dependenciesFilePath)) + { Debug.LogError($"Could not find {DependenciesFilename}"); return; } - + var dependenciesFile = File.ReadAllText(dependenciesFilePath); - var dependenciesRegex = new Regex("(?<=)"); + var dependenciesRegex = new Regex( + "(?<=)" + ); - if (!dependenciesRegex.IsMatch(dependenciesFile)) { - Debug.LogError($"Could not read current iOS framework dependency version from {DependenciesFilename}"); + if (!dependenciesRegex.IsMatch(dependenciesFile)) + { + Debug.LogError( + $"Could not read current iOS framework dependency version from {DependenciesFilename}" + ); return; } var podfile = File.ReadAllText(podfilePath); - var podfileRegex = new Regex($@"target '{ServiceExtensionTargetName}' do\n pod 'OneSignalXCFramework', '(.+)'\nend\n"); - + var podfileRegex = new Regex( + $@"target '{ServiceExtensionTargetName}' do\n pod 'OneSignalXCFramework', '(.+)'\nend\n" + ); + var requiredVersion = dependenciesRegex.Match(dependenciesFile).ToString(); - var requiredTarget = $"target '{ServiceExtensionTargetName}' do\n pod 'OneSignalXCFramework', '{requiredVersion}'\nend\n"; + var requiredTarget = + $"target '{ServiceExtensionTargetName}' do\n pod 'OneSignalXCFramework', '{requiredVersion}'\nend\n"; if (!podfileRegex.IsMatch(podfile)) podfile += requiredTarget; - else { + else + { var podfileTarget = podfileRegex.Match(podfile).ToString(); podfile = podfile.Replace(podfileTarget, requiredTarget); } - + File.WriteAllText(podfilePath, podfile); } - private void DisableBitcode() { + private void DisableBitcode() + { // Main var targetGuid = _project.GetMainTargetGuid(); _project.SetBuildProperty(targetGuid, "ENABLE_BITCODE", "NO"); @@ -301,4 +373,4 @@ private void DisableBitcode() { } } } -#endif \ No newline at end of file +#endif diff --git a/com.onesignal.unity.ios/Editor/OneSignaliOSDependencies.xml b/com.onesignal.unity.ios/Editor/OneSignaliOSDependencies.xml index 1ceff9188..ba5b6bff1 100644 --- a/com.onesignal.unity.ios/Editor/OneSignaliOSDependencies.xml +++ b/com.onesignal.unity.ios/Editor/OneSignaliOSDependencies.xml @@ -1,5 +1,5 @@  - - - - \ No newline at end of file + + + + diff --git a/com.onesignal.unity.ios/Editor/PBXProjectExtensions.cs b/com.onesignal.unity.ios/Editor/PBXProjectExtensions.cs index 793742a15..07e78b593 100644 --- a/com.onesignal.unity.ios/Editor/PBXProjectExtensions.cs +++ b/com.onesignal.unity.ios/Editor/PBXProjectExtensions.cs @@ -28,21 +28,22 @@ #if UNITY_IOS using UnityEditor.iOS.Xcode; -namespace OneSignalSDK.iOS { - public static class PBXProjectExtensions { - #if UNITY_2019_3_OR_NEWER - public static string GetMainTargetName(this PBXProject project) - => "Unity-iPhone"; +namespace OneSignalSDK.iOS +{ + public static class PBXProjectExtensions + { +#if UNITY_2019_3_OR_NEWER + public static string GetMainTargetName(this PBXProject project) => "Unity-iPhone"; - public static string GetMainTargetGuid(this PBXProject project) - => project.GetUnityMainTargetGuid(); - #else - public static string GetMainTargetName(this PBXProject project) - => PBXProject.GetUnityTargetName(); - - public static string GetMainTargetGuid(this PBXProject project) - => project.TargetGuidByName(PBXProject.GetUnityTargetName()); - #endif + public static string GetMainTargetGuid(this PBXProject project) => + project.GetUnityMainTargetGuid(); +#else + public static string GetMainTargetName(this PBXProject project) => + PBXProject.GetUnityTargetName(); + + public static string GetMainTargetGuid(this PBXProject project) => + project.TargetGuidByName(PBXProject.GetUnityTargetName()); +#endif } } -#endif \ No newline at end of file +#endif diff --git a/com.onesignal.unity.ios/Runtime/AssemblyInfo.cs b/com.onesignal.unity.ios/Runtime/AssemblyInfo.cs index f6fe0ca41..90a876792 100644 --- a/com.onesignal.unity.ios/Runtime/AssemblyInfo.cs +++ b/com.onesignal.unity.ios/Runtime/AssemblyInfo.cs @@ -27,4 +27,4 @@ using UnityEngine.Scripting; -[assembly: AlwaysLinkAssembly] \ No newline at end of file +[assembly: AlwaysLinkAssembly] diff --git a/com.onesignal.unity.ios/Runtime/OneSignaliOS.cs b/com.onesignal.unity.ios/Runtime/OneSignaliOS.cs index 544863644..6b42dfed2 100644 --- a/com.onesignal.unity.ios/Runtime/OneSignaliOS.cs +++ b/com.onesignal.unity.ios/Runtime/OneSignaliOS.cs @@ -25,35 +25,51 @@ * THE SOFTWARE. */ -using UnityEngine; -using System.Linq; -using System.Threading.Tasks; using System.Collections.Generic; +using System.Linq; using System.Runtime.InteropServices; -using OneSignalSDK.Notifications; -using OneSignalSDK.InAppMessages; +using System.Threading.Tasks; using OneSignalSDK.Debug; using OneSignalSDK.Debug.Utilities; -using OneSignalSDK.Location; -using OneSignalSDK.Session; -using OneSignalSDK.User; -using OneSignalSDK.LiveActivities; -using OneSignalSDK.iOS.Notifications; -using OneSignalSDK.iOS.InAppMessages; +using OneSignalSDK.InAppMessages; using OneSignalSDK.iOS.Debug; +using OneSignalSDK.iOS.InAppMessages; +using OneSignalSDK.iOS.LiveActivities; using OneSignalSDK.iOS.Location; +using OneSignalSDK.iOS.Notifications; using OneSignalSDK.iOS.Session; using OneSignalSDK.iOS.User; -using OneSignalSDK.iOS.LiveActivities; +using OneSignalSDK.LiveActivities; +using OneSignalSDK.Location; +using OneSignalSDK.Notifications; +using OneSignalSDK.Session; +using OneSignalSDK.User; +using UnityEngine; + +namespace OneSignalSDK.iOS +{ + public sealed partial class OneSignaliOS : OneSignalPlatform + { + [DllImport("__Internal")] + private static extern void _oneSignalSetConsentGiven(bool consent); + + [DllImport("__Internal")] + private static extern void _oneSignalSetConsentRequired(bool required); + + [DllImport("__Internal")] + private static extern void _oneSignalInitialize(string appId); -namespace OneSignalSDK.iOS { - public sealed partial class OneSignaliOS : OneSignalPlatform { - [DllImport("__Internal")] private static extern void _oneSignalSetConsentGiven(bool consent); - [DllImport("__Internal")] private static extern void _oneSignalSetConsentRequired(bool required); - [DllImport("__Internal")] private static extern void _oneSignalInitialize(string appId); - [DllImport("__Internal")] private static extern void _oneSignalLogin(string externalId); - [DllImport("__Internal")] private static extern void _oneSignalLoginWithJwtBearerToken(string externalId, string jwtBearerToken); - [DllImport("__Internal")] private static extern void _oneSignalLogout(); + [DllImport("__Internal")] + private static extern void _oneSignalLogin(string externalId); + + [DllImport("__Internal")] + private static extern void _oneSignalLoginWithJwtBearerToken( + string externalId, + string jwtBearerToken + ); + + [DllImport("__Internal")] + private static extern void _oneSignalLogout(); private iOSUserManager _user; private iOSSessionManager _session; @@ -68,8 +84,10 @@ public sealed partial class OneSignaliOS : OneSignalPlatform { /// /// Used to provide a reference for and sets up the global callbacks /// - public OneSignaliOS() { - if (_instance != null) { + public OneSignaliOS() + { + if (_instance != null) + { SDKDebug.Error("Additional instance of OneSignaliOS created."); return; } @@ -78,85 +96,106 @@ public OneSignaliOS() { _debug = new iOSDebugManager(); } - public override IUserManager User { + public override IUserManager User + { get => _user; } - public override ISessionManager Session { + public override ISessionManager Session + { get => _session; } - public override INotificationsManager Notifications { + public override INotificationsManager Notifications + { get => _notifications; } - public override ILocationManager Location { + public override ILocationManager Location + { get => _location; } - public override IInAppMessagesManager InAppMessages { + public override IInAppMessagesManager InAppMessages + { get => _inAppMessages; } - public override IDebugManager Debug { + public override IDebugManager Debug + { get => _debug; } - public override ILiveActivitiesManager LiveActivities { + public override ILiveActivitiesManager LiveActivities + { get => _liveActivities; } - public override bool ConsentGiven { + public override bool ConsentGiven + { set => _oneSignalSetConsentGiven(value); } - public override bool ConsentRequired { + public override bool ConsentRequired + { set => _oneSignalSetConsentRequired(value); } - public override void Initialize(string appId) { + public override void Initialize(string appId) + { _oneSignalInitialize(appId); - if (_inAppMessages == null) { + if (_inAppMessages == null) + { _inAppMessages = new iOSInAppMessagesManager(); _inAppMessages.Initialize(); } - if (_notifications == null) { + if (_notifications == null) + { _notifications = new iOSNotificationsManager(); _notifications.Initialize(); } - if (_user == null) { + if (_user == null) + { _user = new iOSUserManager(); _user.Initialize(); } - if (_location == null) { + if (_location == null) + { _location = new iOSLocationManager(); } - if (_session == null) { + if (_session == null) + { _session = new iOSSessionManager(); } - if (_liveActivities == null) { + if (_liveActivities == null) + { _liveActivities = new iOSLiveActivitiesManager(); } _completedInit(appId); } - public override void Login(string externalId, string jwtBearerToken = null) { - if (jwtBearerToken == null) { + public override void Login(string externalId, string jwtBearerToken = null) + { + if (jwtBearerToken == null) + { _oneSignalLogin(externalId); - } else { + } + else + { _oneSignalLoginWithJwtBearerToken(externalId, jwtBearerToken); } } - public override void Logout() { + public override void Logout() + { _oneSignalLogout(); } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/Utilities/Later.cs b/com.onesignal.unity.ios/Runtime/Utilities/Later.cs index 0d59c4957..6fd8e75c5 100644 --- a/com.onesignal.unity.ios/Runtime/Utilities/Later.cs +++ b/com.onesignal.unity.ios/Runtime/Utilities/Later.cs @@ -2,26 +2,32 @@ using System.Runtime.CompilerServices; using System.Threading.Tasks; -namespace Laters { +namespace Laters +{ /// For referencing generically - public interface ILater {} - + public interface ILater { } + /// Read-only interface for a standard - public interface ILater : ILater { + public interface ILater : ILater + { event Action OnComplete; TaskAwaiter GetAwaiter(); } /// Basic Later for passing a single type to callbacks and awaiters - public class Later : BaseLater { + public class Later : BaseLater + { public void Complete(TResult result) => _complete(result); } /// Separated implementation so the derivations can offer different methods for completion - public abstract class BaseLater : ILater { - public event Action OnComplete { + public abstract class BaseLater : ILater + { + public event Action OnComplete + { remove => _onComplete -= value; - add { + add + { if (_isComplete) _onComplete += value; else if (value != null) @@ -29,7 +35,8 @@ public event Action OnComplete { } } - public TaskAwaiter GetAwaiter() { + public TaskAwaiter GetAwaiter() + { if (_completionSource != null) return _completionSource.Task.GetAwaiter(); @@ -43,7 +50,8 @@ public TaskAwaiter GetAwaiter() { return _completionSource.Task.GetAwaiter(); } - protected void _complete(TResult result) { + protected void _complete(TResult result) + { if (_isComplete) return; @@ -61,4 +69,4 @@ protected void _complete(TResult result) { private bool _isComplete = false; private TResult _result; } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/Utilities/WaitingProxy.cs b/com.onesignal.unity.ios/Runtime/Utilities/WaitingProxy.cs index 34baeed28..3d81b44fb 100644 --- a/com.onesignal.unity.ios/Runtime/Utilities/WaitingProxy.cs +++ b/com.onesignal.unity.ios/Runtime/Utilities/WaitingProxy.cs @@ -25,28 +25,33 @@ * THE SOFTWARE. */ -using Laters; using System.Collections.Generic; +using Laters; -namespace OneSignalSDK.iOS.Utilities { - internal static class WaitingProxy { - private static readonly Dictionary WaitingProxies = new Dictionary(); +namespace OneSignalSDK.iOS.Utilities +{ + internal static class WaitingProxy + { + private static readonly Dictionary WaitingProxies = + new Dictionary(); - public static (Later proxy, int hashCode) _setupProxy() { - var proxy = new Later(); + public static (Later proxy, int hashCode) _setupProxy() + { + var proxy = new Later(); var hashCode = proxy.GetHashCode(); WaitingProxies[hashCode] = proxy; return (proxy, hashCode); } - public static void ResolveCallbackProxy(int hashCode, TResponse response) { + public static void ResolveCallbackProxy(int hashCode, TResponse response) + { if (!WaitingProxies.ContainsKey(hashCode)) return; - + if (WaitingProxies[hashCode] is Later later) later.Complete(response); - + WaitingProxies.Remove(hashCode); } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/iOSDebugManager.cs b/com.onesignal.unity.ios/Runtime/iOSDebugManager.cs index 6a4f65d30..ac88982ed 100644 --- a/com.onesignal.unity.ios/Runtime/iOSDebugManager.cs +++ b/com.onesignal.unity.ios/Runtime/iOSDebugManager.cs @@ -25,33 +25,42 @@ * THE SOFTWARE. */ -using UnityEngine; using System.Runtime.InteropServices; using OneSignalSDK.Debug; using OneSignalSDK.Debug.Models; +using UnityEngine; + +namespace OneSignalSDK.iOS.Debug +{ + internal sealed class iOSDebugManager : IDebugManager + { + [DllImport("__Internal")] + private static extern void _oneSignalDebugSetLogLevel(int logLevel); -namespace OneSignalSDK.iOS.Debug { - internal sealed class iOSDebugManager : IDebugManager { - [DllImport("__Internal")] private static extern void _oneSignalDebugSetLogLevel(int logLevel); - [DllImport("__Internal")] private static extern void _oneSignalDebugSetAlertLevel(int alertlLevel); + [DllImport("__Internal")] + private static extern void _oneSignalDebugSetAlertLevel(int alertlLevel); private LogLevel _logLevel = LogLevel.Warn; private LogLevel _alertLevel = LogLevel.None; - public LogLevel LogLevel { + public LogLevel LogLevel + { get => _logLevel; - set { + set + { _logLevel = value; - _oneSignalDebugSetLogLevel((int) value); + _oneSignalDebugSetLogLevel((int)value); } } - public LogLevel AlertLevel { + public LogLevel AlertLevel + { get => _alertLevel; - set { + set + { _alertLevel = value; - _oneSignalDebugSetAlertLevel((int) value); + _oneSignalDebugSetAlertLevel((int)value); } } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/iOSDisplayableNotification.cs b/com.onesignal.unity.ios/Runtime/iOSDisplayableNotification.cs index ba3febef0..77c9c10a8 100644 --- a/com.onesignal.unity.ios/Runtime/iOSDisplayableNotification.cs +++ b/com.onesignal.unity.ios/Runtime/iOSDisplayableNotification.cs @@ -26,16 +26,18 @@ */ using System; -using UnityEngine; using System.Runtime.InteropServices; using OneSignalSDK.Notifications.Internal; using OneSignalSDK.Notifications.Models; +using UnityEngine; -namespace OneSignalSDK.iOS.Notifications.Models { - public sealed class iOSDisplayableNotification : Notification, IDisplayableNotification { - [DllImport("__Internal")] private static extern void _oneSignalNotificationsDisplay(string notificationId); +namespace OneSignalSDK.iOS.Notifications.Models +{ + public sealed class iOSDisplayableNotification : Notification, IDisplayableNotification + { + [DllImport("__Internal")] + private static extern void _oneSignalNotificationsDisplay(string notificationId); - public void Display() - => _oneSignalNotificationsDisplay(this.NotificationId); + public void Display() => _oneSignalNotificationsDisplay(this.NotificationId); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/iOSInAppMessagesManager.cs b/com.onesignal.unity.ios/Runtime/iOSInAppMessagesManager.cs index e33cf55fc..43f0b446d 100644 --- a/com.onesignal.unity.ios/Runtime/iOSInAppMessagesManager.cs +++ b/com.onesignal.unity.ios/Runtime/iOSInAppMessagesManager.cs @@ -25,30 +25,63 @@ * THE SOFTWARE. */ - -using UnityEngine; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using OneSignalSDK.InAppMessages; -using OneSignalSDK.InAppMessages.Models; using OneSignalSDK.InAppMessages.Internal; +using OneSignalSDK.InAppMessages.Models; +using UnityEngine; + +namespace OneSignalSDK.iOS.InAppMessages +{ + internal sealed class iOSInAppMessagesManager : IInAppMessagesManager + { + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesSetWillDisplayCallback( + StringListenerDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesSetDidDisplayCallback( + StringListenerDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesSetWillDismissCallback( + StringListenerDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesSetDidDismissCallback( + StringListenerDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesSetClickCallback( + ClickListenerDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesSetPaused(bool paused); + + [DllImport("__Internal")] + private static extern bool _oneSignalInAppMessagesGetPaused(); + + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesAddTrigger(string key, string value); + + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesAddTriggers(string triggersJson); + + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesRemoveTrigger(string key); + + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesRemoveTriggers(string triggersJson); -namespace OneSignalSDK.iOS.InAppMessages { - internal sealed class iOSInAppMessagesManager : IInAppMessagesManager { - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesSetWillDisplayCallback(StringListenerDelegate callback); - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesSetDidDisplayCallback(StringListenerDelegate callback); - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesSetWillDismissCallback(StringListenerDelegate callback); - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesSetDidDismissCallback(StringListenerDelegate callback); - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesSetClickCallback(ClickListenerDelegate callback); - - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesSetPaused(bool paused); - [DllImport("__Internal")] private static extern bool _oneSignalInAppMessagesGetPaused(); - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesAddTrigger(string key, string value); - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesAddTriggers(string triggersJson); - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesRemoveTrigger(string key); - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesRemoveTriggers(string triggersJson); - [DllImport("__Internal")] private static extern void _oneSignalInAppMessagesClearTriggers(); + [DllImport("__Internal")] + private static extern void _oneSignalInAppMessagesClearTriggers(); private delegate void StringListenerDelegate(string response); private delegate void ClickListenerDelegate(string message, string result, int urlType); @@ -61,31 +94,32 @@ internal sealed class iOSInAppMessagesManager : IInAppMessagesManager { private static iOSInAppMessagesManager _instance; - public iOSInAppMessagesManager() { + public iOSInAppMessagesManager() + { _instance = this; } - public bool Paused { + public bool Paused + { get => _oneSignalInAppMessagesGetPaused(); set => _oneSignalInAppMessagesSetPaused(value); } - public void AddTrigger(string key, string value) - => _oneSignalInAppMessagesAddTrigger(key, value.ToString()); + public void AddTrigger(string key, string value) => + _oneSignalInAppMessagesAddTrigger(key, value.ToString()); - public void AddTriggers(Dictionary triggers) - => _oneSignalInAppMessagesAddTriggers(Json.Serialize(triggers)); + public void AddTriggers(Dictionary triggers) => + _oneSignalInAppMessagesAddTriggers(Json.Serialize(triggers)); - public void RemoveTrigger(string key) - => _oneSignalInAppMessagesRemoveTrigger(key); + public void RemoveTrigger(string key) => _oneSignalInAppMessagesRemoveTrigger(key); - public void RemoveTriggers(params string[] keys) - => _oneSignalInAppMessagesRemoveTriggers(Json.Serialize(keys)); + public void RemoveTriggers(params string[] keys) => + _oneSignalInAppMessagesRemoveTriggers(Json.Serialize(keys)); - public void ClearTriggers() - => _oneSignalInAppMessagesClearTriggers(); + public void ClearTriggers() => _oneSignalInAppMessagesClearTriggers(); - public void Initialize() { + public void Initialize() + { _oneSignalInAppMessagesSetWillDisplayCallback(_onWillDisplay); _oneSignalInAppMessagesSetDidDisplayCallback(_onDidDisplay); _oneSignalInAppMessagesSetWillDismissCallback(_onWillDismiss); @@ -94,7 +128,8 @@ public void Initialize() { } [AOT.MonoPInvokeCallback(typeof(StringListenerDelegate))] - private static void _onWillDisplay(string response) { + private static void _onWillDisplay(string response) + { var message = new InAppMessage(response); InAppMessageWillDisplayEventArgs args = new InAppMessageWillDisplayEventArgs(message); @@ -106,7 +141,8 @@ private static void _onWillDisplay(string response) { } [AOT.MonoPInvokeCallback(typeof(StringListenerDelegate))] - private static void _onDidDisplay(string response) { + private static void _onDidDisplay(string response) + { var message = new InAppMessage(response); InAppMessageDidDisplayEventArgs args = new InAppMessageDidDisplayEventArgs(message); @@ -118,7 +154,8 @@ private static void _onDidDisplay(string response) { } [AOT.MonoPInvokeCallback(typeof(StringListenerDelegate))] - private static void _onWillDismiss(string response) { + private static void _onWillDismiss(string response) + { var message = new InAppMessage(response); InAppMessageWillDismissEventArgs args = new InAppMessageWillDismissEventArgs(message); @@ -130,7 +167,8 @@ private static void _onWillDismiss(string response) { } [AOT.MonoPInvokeCallback(typeof(StringListenerDelegate))] - private static void _onDidDismiss(string response) { + private static void _onDidDismiss(string response) + { var message = new InAppMessage(response); InAppMessageDidDismissEventArgs args = new InAppMessageDidDismissEventArgs(message); @@ -142,12 +180,18 @@ private static void _onDidDismiss(string response) { } [AOT.MonoPInvokeCallback(typeof(ClickListenerDelegate))] - private static void _onClicked(string message, string result, int urlType) { + private static void _onClicked(string message, string result, int urlType) + { var mes = JsonUtility.FromJson(message); var res = JsonUtility.FromJson(result); var urlTarget = IntToInAppMessageActionUrlType(urlType); - var clickRes = new InAppMessageClickResult(res.ActionId, urlTarget, res.Url, res.ClosingMessage); + var clickRes = new InAppMessageClickResult( + res.ActionId, + urlTarget, + res.Url, + res.ClosingMessage + ); InAppMessageClickEventArgs args = new InAppMessageClickEventArgs(mes, clickRes); @@ -158,7 +202,8 @@ private static void _onClicked(string message, string result, int urlType) { } } - public static InAppMessageActionUrlType IntToInAppMessageActionUrlType(int urlType) { + public static InAppMessageActionUrlType IntToInAppMessageActionUrlType(int urlType) + { switch (urlType) { case 0: @@ -172,4 +217,4 @@ public static InAppMessageActionUrlType IntToInAppMessageActionUrlType(int urlTy } } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/iOSLiveActivitiesManager.cs b/com.onesignal.unity.ios/Runtime/iOSLiveActivitiesManager.cs index 41415f7b8..2d0d47b3d 100644 --- a/com.onesignal.unity.ios/Runtime/iOSLiveActivitiesManager.cs +++ b/com.onesignal.unity.ios/Runtime/iOSLiveActivitiesManager.cs @@ -26,30 +26,57 @@ */ using System.Collections.Generic; -using System.Threading.Tasks; using System.Runtime.InteropServices; -using OneSignalSDK.LiveActivities; +using System.Threading.Tasks; using OneSignalSDK.iOS.Utilities; +using OneSignalSDK.LiveActivities; + +namespace OneSignalSDK.iOS.LiveActivities +{ + internal sealed class iOSLiveActivitiesManager : ILiveActivitiesManager + { + [DllImport("__Internal")] + private static extern void _oneSignalSetupDefaultLiveActivity(string optionsJson); -namespace OneSignalSDK.iOS.LiveActivities { - internal sealed class iOSLiveActivitiesManager : ILiveActivitiesManager { - [DllImport("__Internal")] private static extern void _oneSignalSetupDefaultLiveActivity(string optionsJson); - [DllImport("__Internal")] private static extern void _oneSignalStartDefaultLiveActivity(string activityId, string attributesJson, string contentJson); - [DllImport("__Internal")] private static extern void _oneSignalEnterLiveActivity(string activityId, string token, int hashCode, BooleanResponseDelegate callback); - [DllImport("__Internal")] private static extern void _oneSignalExitLiveActivity(string activityId, int hashCode, BooleanResponseDelegate callback); + [DllImport("__Internal")] + private static extern void _oneSignalStartDefaultLiveActivity( + string activityId, + string attributesJson, + string contentJson + ); - [DllImport("__Internal")] private static extern void _oneSignalSetPushToStartToken(string activityType, string token); - [DllImport("__Internal")] private static extern void _oneSignalRemovePushToStartToken(string activityType); + [DllImport("__Internal")] + private static extern void _oneSignalEnterLiveActivity( + string activityId, + string token, + int hashCode, + BooleanResponseDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalExitLiveActivity( + string activityId, + int hashCode, + BooleanResponseDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalSetPushToStartToken(string activityType, string token); + + [DllImport("__Internal")] + private static extern void _oneSignalRemovePushToStartToken(string activityType); private delegate void BooleanResponseDelegate(int hashCode, bool response); - public async Task EnterAsync(string activityId, string token) { + public async Task EnterAsync(string activityId, string token) + { var (proxy, hashCode) = WaitingProxy._setupProxy(); _oneSignalEnterLiveActivity(activityId, token, hashCode, BooleanCallbackProxy); return await proxy; } - public async Task ExitAsync(string activityId) { + public async Task ExitAsync(string activityId) + { var (proxy, hashCode) = WaitingProxy._setupProxy(); _oneSignalExitLiveActivity(activityId, hashCode, BooleanCallbackProxy); return await proxy; @@ -57,7 +84,7 @@ public async Task ExitAsync(string activityId) { public void RemovePushToStartToken(string activityType) { - _oneSignalRemovePushToStartToken(activityType); + _oneSignalRemovePushToStartToken(activityType); } public void SetPushToStartToken(string activityType, string token) @@ -70,23 +97,33 @@ public void SetupDefault(LiveActivitySetupOptions options = null) string optionsJson = null; if (options != null) { - optionsJson = Json.Serialize(new Dictionary - { - { "enablePushToStart", options.EnablePushToStart }, - { "enablePushToUpdate", options.EnablePushToUpdate } - }); + optionsJson = Json.Serialize( + new Dictionary + { + { "enablePushToStart", options.EnablePushToStart }, + { "enablePushToUpdate", options.EnablePushToUpdate }, + } + ); } _oneSignalSetupDefaultLiveActivity(optionsJson); } - public void StartDefault(string activityId, IDictionary attributes, IDictionary content) + public void StartDefault( + string activityId, + IDictionary attributes, + IDictionary content + ) { - _oneSignalStartDefaultLiveActivity(activityId, Json.Serialize(attributes), Json.Serialize(content)); + _oneSignalStartDefaultLiveActivity( + activityId, + Json.Serialize(attributes), + Json.Serialize(content) + ); } [AOT.MonoPInvokeCallback(typeof(BooleanResponseDelegate))] - private static void BooleanCallbackProxy(int hashCode, bool response) - => WaitingProxy.ResolveCallbackProxy(hashCode, response); + private static void BooleanCallbackProxy(int hashCode, bool response) => + WaitingProxy.ResolveCallbackProxy(hashCode, response); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/iOSLocationManager.cs b/com.onesignal.unity.ios/Runtime/iOSLocationManager.cs index acdf2cd59..30b911d8b 100644 --- a/com.onesignal.unity.ios/Runtime/iOSLocationManager.cs +++ b/com.onesignal.unity.ios/Runtime/iOSLocationManager.cs @@ -25,24 +25,33 @@ * THE SOFTWARE. */ -using UnityEngine; +using System.Runtime.InteropServices; using System.Threading.Tasks; using OneSignalSDK.Location; -using System.Runtime.InteropServices; +using UnityEngine; + +namespace OneSignalSDK.iOS.Location +{ + internal sealed class iOSLocationManager : ILocationManager + { + [DllImport("__Internal")] + private static extern bool _oneSignalLocationGetIsShared(); + + [DllImport("__Internal")] + private static extern void _oneSignalLocationSetIsShared(bool shared); -namespace OneSignalSDK.iOS.Location { - internal sealed class iOSLocationManager : ILocationManager { - [DllImport("__Internal")] private static extern bool _oneSignalLocationGetIsShared(); - [DllImport("__Internal")] private static extern void _oneSignalLocationSetIsShared(bool shared); - [DllImport("__Internal")] private static extern void _oneSignalLocationRequestPermission(); + [DllImport("__Internal")] + private static extern void _oneSignalLocationRequestPermission(); - public bool IsShared { + public bool IsShared + { get => _oneSignalLocationGetIsShared(); set => _oneSignalLocationSetIsShared(value); } - public void RequestPermission() { + public void RequestPermission() + { _oneSignalLocationRequestPermission(); } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/iOSNotificationsManager.cs b/com.onesignal.unity.ios/Runtime/iOSNotificationsManager.cs index f4a81ea4d..a70a13606 100644 --- a/com.onesignal.unity.ios/Runtime/iOSNotificationsManager.cs +++ b/com.onesignal.unity.ios/Runtime/iOSNotificationsManager.cs @@ -26,31 +26,66 @@ */ using System; -using UnityEngine; -using System.Threading.Tasks; using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Threading.Tasks; +using OneSignalSDK.iOS.Notifications.Models; +using OneSignalSDK.iOS.Utilities; using OneSignalSDK.Notifications; -using OneSignalSDK.Notifications.Models; using OneSignalSDK.Notifications.Internal; -using OneSignalSDK.iOS.Utilities; -using OneSignalSDK.iOS.Notifications.Models; +using OneSignalSDK.Notifications.Models; +using UnityEngine; -namespace OneSignalSDK.iOS.Notifications { - internal sealed class iOSNotificationsManager : INotificationsManager { - [DllImport("__Internal")] private static extern bool _oneSignalNotificationsGetPermission(); - [DllImport("__Internal")] private static extern bool _oneSignalNotificationsGetCanRequestPermission(); - [DllImport("__Internal")] private static extern int _oneSignalNotificationsGetPermissionNative(); - [DllImport("__Internal")] private static extern void _oneSignalNotificationsRequestPermission(bool fallbackToSettings, int hashCode, BooleanResponseDelegate callback); - [DllImport("__Internal")] private static extern void _oneSignalNotificationsClearAll(); - [DllImport("__Internal")] private static extern void _oneSignalNotificationsAddPermissionObserver(PermissionListenerDelegate callback); - [DllImport("__Internal")] private static extern void _oneSignalNotificationsSetForegroundWillDisplayCallback(WillDisplayListenerDelegate callback); - [DllImport("__Internal")] private static extern void _oneSignalNotificationsWillDisplayEventPreventDefault(string notificationId); - [DllImport("__Internal")] private static extern void _oneSignalNotificationsSetClickCallback(ClickListenerDelegate callback); +namespace OneSignalSDK.iOS.Notifications +{ + internal sealed class iOSNotificationsManager : INotificationsManager + { + [DllImport("__Internal")] + private static extern bool _oneSignalNotificationsGetPermission(); + + [DllImport("__Internal")] + private static extern bool _oneSignalNotificationsGetCanRequestPermission(); + + [DllImport("__Internal")] + private static extern int _oneSignalNotificationsGetPermissionNative(); + + [DllImport("__Internal")] + private static extern void _oneSignalNotificationsRequestPermission( + bool fallbackToSettings, + int hashCode, + BooleanResponseDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalNotificationsClearAll(); + + [DllImport("__Internal")] + private static extern void _oneSignalNotificationsAddPermissionObserver( + PermissionListenerDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalNotificationsSetForegroundWillDisplayCallback( + WillDisplayListenerDelegate callback + ); + + [DllImport("__Internal")] + private static extern void _oneSignalNotificationsWillDisplayEventPreventDefault( + string notificationId + ); + + [DllImport("__Internal")] + private static extern void _oneSignalNotificationsSetClickCallback( + ClickListenerDelegate callback + ); private delegate void PermissionListenerDelegate(bool permission); private delegate void WillDisplayListenerDelegate(string notification); - private delegate void ClickListenerDelegate(string notification, string resultActionId, string resultUrl); + private delegate void ClickListenerDelegate( + string notification, + string resultActionId, + string resultUrl + ); private delegate void BooleanResponseDelegate(int hashCode, bool response); public event EventHandler ForegroundWillDisplay; @@ -60,11 +95,14 @@ internal sealed class iOSNotificationsManager : INotificationsManager { private bool _clickNativeListenerSet; private EventHandler _clicked; - public event EventHandler Clicked { - add { + public event EventHandler Clicked + { + add + { _clicked += value; - if (!_clickNativeListenerSet) { + if (!_clickNativeListenerSet) + { _clickNativeListenerSet = true; _oneSignalNotificationsSetClickCallback(_onClicked); } @@ -74,42 +112,56 @@ public event EventHandler Clicked { private static iOSNotificationsManager _instance; - public iOSNotificationsManager() { + public iOSNotificationsManager() + { _instance = this; } - public bool Permission { + public bool Permission + { get => _oneSignalNotificationsGetPermission(); } - public bool CanRequestPermission { + public bool CanRequestPermission + { get => _oneSignalNotificationsGetCanRequestPermission(); } - public NotificationPermission PermissionNative { + public NotificationPermission PermissionNative + { get => (NotificationPermission)_oneSignalNotificationsGetPermissionNative(); } - public async Task RequestPermissionAsync(bool fallbackToSettings) { + public async Task RequestPermissionAsync(bool fallbackToSettings) + { var (proxy, hashCode) = WaitingProxy._setupProxy(); - _oneSignalNotificationsRequestPermission(fallbackToSettings, hashCode, BooleanCallbackProxy); + _oneSignalNotificationsRequestPermission( + fallbackToSettings, + hashCode, + BooleanCallbackProxy + ); return await proxy; } - public void ClearAllNotifications() { + public void ClearAllNotifications() + { _oneSignalNotificationsClearAll(); } - public void Initialize() { + public void Initialize() + { _oneSignalNotificationsAddPermissionObserver(_onPermissionStateChanged); _oneSignalNotificationsSetForegroundWillDisplayCallback(_onForegroundWillDisplay); } [AOT.MonoPInvokeCallback(typeof(PermissionListenerDelegate))] - private static void _onPermissionStateChanged(bool permission) { - NotificationPermissionChangedEventArgs args = new NotificationPermissionChangedEventArgs(permission); + private static void _onPermissionStateChanged(bool permission) + { + NotificationPermissionChangedEventArgs args = + new NotificationPermissionChangedEventArgs(permission); - EventHandler handler = _instance.PermissionChanged; + EventHandler handler = + _instance.PermissionChanged; if (handler != null) { UnityMainThreadDispatch.Post(state => handler(_instance, args)); @@ -117,13 +169,16 @@ private static void _onPermissionStateChanged(bool permission) { } [AOT.MonoPInvokeCallback(typeof(WillDisplayListenerDelegate))] - private static void _onForegroundWillDisplay(string notification) { + private static void _onForegroundWillDisplay(string notification) + { var notif = JsonUtility.FromJson(notification); _fillNotifFromObj(ref notif, Json.Deserialize(notification)); - InternalNotificationWillDisplayEventArgs args = new InternalNotificationWillDisplayEventArgs(notif); + InternalNotificationWillDisplayEventArgs args = + new InternalNotificationWillDisplayEventArgs(notif); - EventHandler handler = _instance.ForegroundWillDisplay; + EventHandler handler = + _instance.ForegroundWillDisplay; if (handler != null) { // We use Send instead of Post because we need to *not* return to our caller until the @@ -133,16 +188,22 @@ private static void _onForegroundWillDisplay(string notification) { } } - public class InternalNotificationWillDisplayEventArgs : NotificationWillDisplayEventArgs { - public InternalNotificationWillDisplayEventArgs(IDisplayableNotification notification) : base(notification) { } + public class InternalNotificationWillDisplayEventArgs : NotificationWillDisplayEventArgs + { + public InternalNotificationWillDisplayEventArgs(IDisplayableNotification notification) + : base(notification) { } - public override void PreventDefault() { - _oneSignalNotificationsWillDisplayEventPreventDefault(this.Notification.NotificationId); + public override void PreventDefault() + { + _oneSignalNotificationsWillDisplayEventPreventDefault( + this.Notification.NotificationId + ); } } [AOT.MonoPInvokeCallback(typeof(ClickListenerDelegate))] - private static void _onClicked(string notification, string resultActionId, string resultUrl) { + private static void _onClicked(string notification, string resultActionId, string resultUrl) + { var notif = JsonUtility.FromJson(notification); _fillNotifFromObj(ref notif, Json.Deserialize(notification)); @@ -153,22 +214,26 @@ private static void _onClicked(string notification, string resultActionId, strin UnityMainThreadDispatch.Post(state => handler(_instance, args)); } - private static void _fillNotifFromObj(ref iOSDisplayableNotification notif, object notifObj) { - if (!(notifObj is Dictionary notifDict)) + private static void _fillNotifFromObj(ref iOSDisplayableNotification notif, object notifObj) + { + if (!(notifObj is Dictionary notifDict)) return; if (notifDict.ContainsKey("additionalData")) notif.additionalData = notifDict["additionalData"] as Dictionary; - + if (notifDict.ContainsKey("attachments")) notif.attachments = notifDict["attachments"] as Dictionary; - if (notifDict.ContainsKey("rawPayload") && notifDict["rawPayload"] is Dictionary payloadDict) + if ( + notifDict.ContainsKey("rawPayload") + && notifDict["rawPayload"] is Dictionary payloadDict + ) notif.rawPayload = Json.Serialize(payloadDict); } [AOT.MonoPInvokeCallback(typeof(BooleanResponseDelegate))] - private static void BooleanCallbackProxy(int hashCode, bool response) - => WaitingProxy.ResolveCallbackProxy(hashCode, response); + private static void BooleanCallbackProxy(int hashCode, bool response) => + WaitingProxy.ResolveCallbackProxy(hashCode, response); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/iOSPushSubscription.cs b/com.onesignal.unity.ios/Runtime/iOSPushSubscription.cs index a060fce20..56f095f9a 100644 --- a/com.onesignal.unity.ios/Runtime/iOSPushSubscription.cs +++ b/com.onesignal.unity.ios/Runtime/iOSPushSubscription.cs @@ -26,21 +26,35 @@ */ using System; -using UnityEngine; using System.Runtime.InteropServices; -using OneSignalSDK.User.Models; +using OneSignalSDK.Debug.Utilities; using OneSignalSDK.User.Internal; +using OneSignalSDK.User.Models; +using UnityEngine; -using OneSignalSDK.Debug.Utilities; +namespace OneSignalSDK.iOS.User.Models +{ + internal sealed class iOSPushSubscription : IPushSubscription + { + [DllImport("__Internal")] + private static extern string _oneSignalPushSubscriptionGetId(); + + [DllImport("__Internal")] + private static extern string _oneSignalPushSubscriptionGetToken(); + + [DllImport("__Internal")] + private static extern bool _oneSignalPushSubscriptionGetOptedIn(); + + [DllImport("__Internal")] + private static extern void _oneSignalPushSubscriptionOptIn(); + + [DllImport("__Internal")] + private static extern void _oneSignalPushSubscriptionOptOut(); -namespace OneSignalSDK.iOS.User.Models { - internal sealed class iOSPushSubscription : IPushSubscription { - [DllImport("__Internal")] private static extern string _oneSignalPushSubscriptionGetId(); - [DllImport("__Internal")] private static extern string _oneSignalPushSubscriptionGetToken(); - [DllImport("__Internal")] private static extern bool _oneSignalPushSubscriptionGetOptedIn(); - [DllImport("__Internal")] private static extern void _oneSignalPushSubscriptionOptIn(); - [DllImport("__Internal")] private static extern void _oneSignalPushSubscriptionOptOut(); - [DllImport("__Internal")] private static extern void _oneSignalPushSubscriptionAddStateChangedCallback(StateListenerDelegate callback); + [DllImport("__Internal")] + private static extern void _oneSignalPushSubscriptionAddStateChangedCallback( + StateListenerDelegate callback + ); public delegate void StateListenerDelegate(string current, string previous); @@ -48,34 +62,38 @@ internal sealed class iOSPushSubscription : IPushSubscription { private static iOSPushSubscription _instance; - public iOSPushSubscription() { + public iOSPushSubscription() + { _instance = this; } - public string Id { + public string Id + { get => _oneSignalPushSubscriptionGetId(); } - public string Token { + public string Token + { get => _oneSignalPushSubscriptionGetToken(); } - public bool OptedIn { + public bool OptedIn + { get => _oneSignalPushSubscriptionGetOptedIn(); } - public void OptIn() - => _oneSignalPushSubscriptionOptIn(); + public void OptIn() => _oneSignalPushSubscriptionOptIn(); - public void OptOut() - => _oneSignalPushSubscriptionOptOut(); + public void OptOut() => _oneSignalPushSubscriptionOptOut(); - public void Initialize() { + public void Initialize() + { _oneSignalPushSubscriptionAddStateChangedCallback(_onPushSubscriptionStateChanged); } [AOT.MonoPInvokeCallback(typeof(StateListenerDelegate))] - private static void _onPushSubscriptionStateChanged(string current, string previous) { + private static void _onPushSubscriptionStateChanged(string current, string previous) + { var curr = JsonUtility.FromJson(current); var prev = JsonUtility.FromJson(previous); @@ -89,4 +107,4 @@ private static void _onPushSubscriptionStateChanged(string current, string previ } } } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/iOSSessionManager.cs b/com.onesignal.unity.ios/Runtime/iOSSessionManager.cs index 2231e413c..e8a0d0349 100644 --- a/com.onesignal.unity.ios/Runtime/iOSSessionManager.cs +++ b/com.onesignal.unity.ios/Runtime/iOSSessionManager.cs @@ -25,23 +25,28 @@ * THE SOFTWARE. */ -using UnityEngine; -using OneSignalSDK.Session; using System.Runtime.InteropServices; +using OneSignalSDK.Session; +using UnityEngine; + +namespace OneSignalSDK.iOS.Session +{ + internal sealed class iOSSessionManager : ISessionManager + { + [DllImport("__Internal")] + private static extern void _oneSignalSessionAddOutcome(string name); + + [DllImport("__Internal")] + private static extern void _oneSignalSessionAddUniqueOutcome(string name); -namespace OneSignalSDK.iOS.Session { - internal sealed class iOSSessionManager : ISessionManager { - [DllImport("__Internal")] private static extern void _oneSignalSessionAddOutcome(string name); - [DllImport("__Internal")] private static extern void _oneSignalSessionAddUniqueOutcome(string name); - [DllImport("__Internal")] private static extern void _oneSignalSessionAddOutcomeWithValue(string name, float value); + [DllImport("__Internal")] + private static extern void _oneSignalSessionAddOutcomeWithValue(string name, float value); - public void AddOutcome(string name) - => _oneSignalSessionAddOutcome(name); + public void AddOutcome(string name) => _oneSignalSessionAddOutcome(name); - public void AddUniqueOutcome(string name) - => _oneSignalSessionAddUniqueOutcome(name); + public void AddUniqueOutcome(string name) => _oneSignalSessionAddUniqueOutcome(name); - public void AddOutcomeWithValue(string name, float value) - => _oneSignalSessionAddOutcomeWithValue(name, value); + public void AddOutcomeWithValue(string name, float value) => + _oneSignalSessionAddOutcomeWithValue(name, value); } -} \ No newline at end of file +} diff --git a/com.onesignal.unity.ios/Runtime/iOSUserManager.cs b/com.onesignal.unity.ios/Runtime/iOSUserManager.cs index 57ff77d43..2310bb9b5 100644 --- a/com.onesignal.unity.ios/Runtime/iOSUserManager.cs +++ b/com.onesignal.unity.ios/Runtime/iOSUserManager.cs @@ -25,35 +25,71 @@ * THE SOFTWARE. */ - -using UnityEngine; using System; using System.Collections.Generic; using System.Runtime.InteropServices; +using OneSignalSDK.iOS.User.Models; using OneSignalSDK.User; using OneSignalSDK.User.Internal; using OneSignalSDK.User.Models; -using OneSignalSDK.iOS.User.Models; +using UnityEngine; + +namespace OneSignalSDK.iOS.User +{ + internal sealed class iOSUserManager : IUserManager + { + [DllImport("__Internal")] + private static extern string _oneSignalUserGetOneSignalId(); + + [DllImport("__Internal")] + private static extern string _oneSignalUserGetExternalId(); + + [DllImport("__Internal")] + private static extern void _oneSignalUserSetLanguage(string languageCode); + + [DllImport("__Internal")] + private static extern void _oneSignalUserAddAlias(string aliasLabel, string aliasId); + + [DllImport("__Internal")] + private static extern void _oneSignalUserAddAliases(string aliasesJson); + + [DllImport("__Internal")] + private static extern void _oneSignalUserRemoveAlias(string aliasLabel); -namespace OneSignalSDK.iOS.User { - internal sealed class iOSUserManager : IUserManager { - [DllImport("__Internal")] private static extern string _oneSignalUserGetOneSignalId(); - [DllImport("__Internal")] private static extern string _oneSignalUserGetExternalId(); - [DllImport("__Internal")] private static extern void _oneSignalUserSetLanguage(string languageCode); - [DllImport("__Internal")] private static extern void _oneSignalUserAddAlias(string aliasLabel, string aliasId); - [DllImport("__Internal")] private static extern void _oneSignalUserAddAliases(string aliasesJson); - [DllImport("__Internal")] private static extern void _oneSignalUserRemoveAlias(string aliasLabel); - [DllImport("__Internal")] private static extern void _oneSignalUserRemoveAliases(string aliasesJson); - [DllImport("__Internal")] private static extern void _oneSignalUserAddEmail(string email); - [DllImport("__Internal")] private static extern void _oneSignalUserRemoveEmail(string email); - [DllImport("__Internal")] private static extern void _oneSignalUserAddSms(string smsNumber); - [DllImport("__Internal")] private static extern void _oneSignalUserRemoveSms(string smsNumber); - [DllImport("__Internal")] private static extern string _oneSignalUserGetTags(); - [DllImport("__Internal")] private static extern void _oneSignalUserAddTag(string key, string value); - [DllImport("__Internal")] private static extern void _oneSignalUserAddTags(string tagsJson); - [DllImport("__Internal")] private static extern void _oneSignalUserRemoveTag(string key); - [DllImport("__Internal")] private static extern void _oneSignalUserRemoveTags(string tagsJson); - [DllImport("__Internal")] private static extern void _oneSignalUserAddStateChangedCallback(UserStateListenerDelegate callback); + [DllImport("__Internal")] + private static extern void _oneSignalUserRemoveAliases(string aliasesJson); + + [DllImport("__Internal")] + private static extern void _oneSignalUserAddEmail(string email); + + [DllImport("__Internal")] + private static extern void _oneSignalUserRemoveEmail(string email); + + [DllImport("__Internal")] + private static extern void _oneSignalUserAddSms(string smsNumber); + + [DllImport("__Internal")] + private static extern void _oneSignalUserRemoveSms(string smsNumber); + + [DllImport("__Internal")] + private static extern string _oneSignalUserGetTags(); + + [DllImport("__Internal")] + private static extern void _oneSignalUserAddTag(string key, string value); + + [DllImport("__Internal")] + private static extern void _oneSignalUserAddTags(string tagsJson); + + [DllImport("__Internal")] + private static extern void _oneSignalUserRemoveTag(string key); + + [DllImport("__Internal")] + private static extern void _oneSignalUserRemoveTags(string tagsJson); + + [DllImport("__Internal")] + private static extern void _oneSignalUserAddStateChangedCallback( + UserStateListenerDelegate callback + ); public delegate void UserStateListenerDelegate(string current); @@ -62,78 +98,80 @@ internal sealed class iOSUserManager : IUserManager { private iOSPushSubscription _pushSubscription; private static iOSUserManager _instance; - - public iOSUserManager() { + + public iOSUserManager() + { _instance = this; _pushSubscription = new iOSPushSubscription(); } - public string OneSignalId { + public string OneSignalId + { get => _oneSignalUserGetOneSignalId(); } - public string ExternalId { + public string ExternalId + { get => _oneSignalUserGetExternalId(); } - public IPushSubscription PushSubscription { + public IPushSubscription PushSubscription + { get => _pushSubscription; } - public string Language { + public string Language + { set => _oneSignalUserSetLanguage(value); } - public Dictionary GetTags() { - Dictionary raw = (Dictionary)Json.Deserialize(_oneSignalUserGetTags()); + public Dictionary GetTags() + { + Dictionary raw = + (Dictionary)Json.Deserialize(_oneSignalUserGetTags()); Dictionary dict = new Dictionary(); - foreach (KeyValuePair kvp in raw) dict.Add(kvp.Key, kvp.Value.ToString()); + foreach (KeyValuePair kvp in raw) + dict.Add(kvp.Key, kvp.Value.ToString()); return dict; } - public void AddTag(string key, string value) - =>_oneSignalUserAddTag(key, value); + public void AddTag(string key, string value) => _oneSignalUserAddTag(key, value); - public void AddTags(Dictionary tags) - => _oneSignalUserAddTags(Json.Serialize(tags)); + public void AddTags(Dictionary tags) => + _oneSignalUserAddTags(Json.Serialize(tags)); - public void RemoveTag(string key) - => _oneSignalUserRemoveTag(key); + public void RemoveTag(string key) => _oneSignalUserRemoveTag(key); - public void RemoveTags(params string[] keys) - => _oneSignalUserRemoveTags(Json.Serialize(keys)); + public void RemoveTags(params string[] keys) => + _oneSignalUserRemoveTags(Json.Serialize(keys)); - public void AddAlias(string label, string id) - => _oneSignalUserAddAlias(label, id); + public void AddAlias(string label, string id) => _oneSignalUserAddAlias(label, id); - public void AddAliases(Dictionary aliases) - => _oneSignalUserAddAliases(Json.Serialize(aliases)); + public void AddAliases(Dictionary aliases) => + _oneSignalUserAddAliases(Json.Serialize(aliases)); - public void RemoveAlias(string label) - => _oneSignalUserRemoveAlias(label); + public void RemoveAlias(string label) => _oneSignalUserRemoveAlias(label); - public void RemoveAliases(params string[] labels) - => _oneSignalUserRemoveAliases(Json.Serialize(labels)); + public void RemoveAliases(params string[] labels) => + _oneSignalUserRemoveAliases(Json.Serialize(labels)); - public void AddEmail(string email) - => _oneSignalUserAddEmail(email); + public void AddEmail(string email) => _oneSignalUserAddEmail(email); - public void RemoveEmail(string email) - => _oneSignalUserRemoveEmail(email); + public void RemoveEmail(string email) => _oneSignalUserRemoveEmail(email); - public void AddSms(string sms) - => _oneSignalUserAddSms(sms); + public void AddSms(string sms) => _oneSignalUserAddSms(sms); - public void RemoveSms(string sms) - => _oneSignalUserRemoveSms(sms); + public void RemoveSms(string sms) => _oneSignalUserRemoveSms(sms); - public void Initialize() { + public void Initialize() + { _pushSubscription.Initialize(); _oneSignalUserAddStateChangedCallback(_onUserStateChanged); } [AOT.MonoPInvokeCallback(typeof(UserStateListenerDelegate))] - private static void _onUserStateChanged(string current) { + private static void _onUserStateChanged(string current) + { var curr = JsonUtility.FromJson(current); UserChangedState userChangedState = new UserChangedState(curr); @@ -146,4 +184,4 @@ private static void _onUserStateChanged(string current) { } } } -} \ No newline at end of file +}