diff --git a/OneSignalExample/Assets/OneSignal/Editor/AssemblyInfo.cs b/OneSignalExample/Assets/OneSignal/Editor/AssemblyInfo.cs index 59cb37669..137abe721 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/AssemblyInfo.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/AssemblyInfo.cs @@ -1,3 +1,30 @@ -using System.Runtime.CompilerServices; +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("OneSignal.Packager")] \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignal/Editor/OneSignalBootstrapper.cs b/OneSignalExample/Assets/OneSignal/Editor/OneSignalBootstrapper.cs index 88f5e2740..389194566 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/OneSignalBootstrapper.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/OneSignalBootstrapper.cs @@ -1,55 +1,79 @@ -using System.Linq; +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +using System.Linq; using UnityEditor; -/// -/// Handles informing the user on startup/import if the legacy SDK has been detected -/// -public static class OneSignalBootstrapper -{ +namespace OneSignalSDK { /// - /// Asks to open the SDK Setup if legacy files are found or core is missing + /// Handles informing the user on startup/import if the legacy SDK has been detected /// - [InitializeOnLoadMethod] - public static void CheckForLegacy() - { - if (SessionState.GetBool(_sessionCheckKey, false)) - return; - - SessionState.SetBool(_sessionCheckKey, true); - - EditorApplication.delayCall += _checkForLegacy; - } + public static class OneSignalBootstrapper { + /// + /// Asks to open the SDK Setup if legacy files are found or core is missing + /// + [InitializeOnLoadMethod] public static void CheckForLegacy() { + if (SessionState.GetBool(_sessionCheckKey, false)) + return; - private static void _checkForLegacy() - { -#if !ONE_SIGNAL_INSTALLED - EditorApplication.delayCall += _showOpenSetupDialog; -#else - var inventory = AssetDatabase.LoadAssetAtPath(OneSignalFileInventory.AssetPath); + SessionState.SetBool(_sessionCheckKey, true); - if (inventory == null) - return; // error - - var currentPaths = OneSignalFileInventory.GetCurrentPaths(); - var diff = currentPaths.Except(inventory.DistributedPaths); + EditorApplication.delayCall += _checkForLegacy; + } - if (diff.Any()) + private static void _checkForLegacy() { + #if !ONE_SIGNAL_INSTALLED EditorApplication.delayCall += _showOpenSetupDialog; -#endif - } + #else + var inventory = AssetDatabase.LoadAssetAtPath(OneSignalFileInventory.AssetPath); - private static void _showOpenSetupDialog() - { - var dialogResult = EditorUtility.DisplayDialog( - "OneSignal", - "The project contains an outdated version of OneSignal SDK! We recommend running the OneSignal SDK Setup.", - "Open SDK Setup", - "Cancel" - ); - - if (dialogResult) - OneSignalSetupWindow.ShowWindow(); - } + if (inventory == null) + return; // error + + var currentPaths = OneSignalFileInventory.GetCurrentPaths(); + var diff = currentPaths.Except(inventory.DistributedPaths); - private const string _sessionCheckKey = "onesignal.bootstrapper.check"; + if (diff.Any()) + EditorApplication.delayCall += _showOpenSetupDialog; + #endif + } + + private static void _showOpenSetupDialog() { + var dialogResult = EditorUtility.DisplayDialog( + "OneSignal", + "The project contains an outdated version of OneSignal SDK! We recommend running the OneSignal SDK Setup.", + "Open SDK Setup", + "Cancel" + ); + + if (dialogResult) + OneSignalSetupWindow.ShowWindow(); + } + + 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 7c9a229bf..5745bea08 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/OneSignalFileInventory.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/OneSignalFileInventory.cs @@ -1,42 +1,70 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System.IO; using System.Linq; using UnityEngine; -/// -/// Inventory distributed with the *.unitypackage in order to determine if there are any legacy files in need of removal -/// -internal sealed class OneSignalFileInventory : ScriptableObject -{ +namespace OneSignalSDK { /// - /// Array of paths within the OneSignal directory which were determined to be part of the distributed unitypackage + /// Inventory distributed with the *.unitypackage in order to determine if there are any legacy files in need of removal /// - public string[] DistributedPaths; + internal sealed class OneSignalFileInventory : ScriptableObject { + /// + /// Array of paths within the OneSignal directory which were determined to be part of the distributed unitypackage + /// + public string[] DistributedPaths; - /// - /// Array of current paths within the OneSignal directory - /// - public static string[] GetCurrentPaths() - => ConvertPathsToUnix(Directory.GetFiles(PackageAssetsPath, "*", SearchOption.AllDirectories)); + /// + /// Array of current paths within the OneSignal directory + /// + public static string[] GetCurrentPaths() + => ConvertPathsToUnix(Directory.GetFiles(PackageAssetsPath, "*", SearchOption.AllDirectories)); - /// - /// Makes sure are using forward slash to be Unix compatible. - /// https://docs.microsoft.com/en-us/dotnet/api/system.io.path.altdirectoryseparatorchar?view=net-5.0#examples - /// - /// the paths to check and convert - /// paths with / as the directory separator - public static string[] ConvertPathsToUnix(string[] paths) { - if (Path.DirectorySeparatorChar == Path.AltDirectorySeparatorChar) - return paths; - - var fixedPaths = paths.Select(path => - path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) - ); + /// + /// Makes sure are using forward slash to be Unix compatible. + /// https://docs.microsoft.com/en-us/dotnet/api/system.io.path.altdirectoryseparatorchar?view=net-5.0#examples + /// + /// the paths to check and convert + /// paths with / as the directory separator + public static string[] ConvertPathsToUnix(string[] paths) { + if (Path.DirectorySeparatorChar == Path.AltDirectorySeparatorChar) + return paths; - return fixedPaths.ToArray(); - } + var fixedPaths = paths.Select(path => + path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + ); - 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 AssetPath = Path.Combine(EditorResourcesPath, AssetName); + return fixedPaths.ToArray(); + } + + 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 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 f8990fc6b..666541bcf 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Dependency.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Dependency.cs @@ -1,48 +1,74 @@ -using System.Collections.Generic; +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ -/// -/// Representation of the manifest file "dependency" entry. -/// -class Dependency -{ - /// - /// The dependency name. - /// - public string Name { get; } +using System.Collections.Generic; +namespace OneSignalSDK { /// - /// The dependency version. + /// Representation of the manifest file "dependency" entry. /// - public string Version { get; private set; } + public class Dependency { + /// + /// The dependency name. + /// + public string Name { get; } - /// - /// Initializes a new instance of the class with provided properties. - /// - /// Dependency name. - /// Dependency version. - public Dependency(string name, string version) - { - Name = name; - Version = version; - } + /// + /// The dependency version. + /// + public string Version { get; private set; } - /// - /// Sets new dependency version. - /// - /// The version to be set for this dependency - public void SetVersion(string version) - { - Version = version; - } + /// + /// Initializes a new instance of the class with provided properties. + /// + /// Dependency name. + /// Dependency version. + public Dependency(string name, string version) { + Name = name; + Version = version; + } - /// - /// Creates a dictionary from this object. - /// - /// Dependency object representation as Dictionary<string, object>. - public Dictionary ToDictionary() - { - Dictionary result = new Dictionary(); - result.Add(Name, Version); - return result; + /// + /// Sets new dependency version. + /// + /// The version to be set for this dependency + public void SetVersion(string version) { + Version = version; + } + + /// + /// Creates a dictionary from this object. + /// + /// Dependency object representation as Dictionary<string, object>. + 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 1b7ebff1b..a6dd9184a 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Manifest.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/Manifest.cs @@ -1,189 +1,195 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System.Collections.Generic; using System.IO; -using OneSignalPush.Utilities; - -/// -/// Representation of Manifest JSON file. -/// Can be used for adding dependencies, scopeRegistries, etc to .json file -/// -class Manifest -{ - const string k_ProjectManifestPath = "Packages/manifest.json"; - const string k_DependenciesKey = "dependencies"; - const string k_ScopedRegistriesKey = "scopedRegistries"; +namespace OneSignalSDK { /// - /// Path to manifest file. + /// Representation of Manifest JSON file. + /// Can be used for adding dependencies, scopeRegistries, etc to .json file /// - public string Path { get; } - - readonly Dictionary m_ScopeRegistries; - readonly Dictionary m_Dependencies; - - Dictionary m_RawContent; - - /// - /// Initializes a new instance of the class. - /// - /// Path to manifest file. - public Manifest(string pathToFile = k_ProjectManifestPath) - { - Path = pathToFile; - m_ScopeRegistries = new Dictionary(); - m_Dependencies = new Dictionary(); - } + public class Manifest { + const string k_ProjectManifestPath = "Packages/manifest.json"; + const string k_DependenciesKey = "dependencies"; + const string k_ScopedRegistriesKey = "scopedRegistries"; + + /// + /// Path to manifest file. + /// + public string Path { get; } + + readonly Dictionary m_ScopeRegistries; + readonly Dictionary m_Dependencies; + + Dictionary m_RawContent; + + /// + /// Initializes a new instance of the class. + /// + /// Path to manifest file. + public Manifest(string pathToFile = k_ProjectManifestPath) { + Path = pathToFile; + m_ScopeRegistries = new Dictionary(); + m_Dependencies = new Dictionary(); + } - /// - /// Read the Manifest file and deserialize its content from JSON. - /// - 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; - var scopeRegistry = new ScopeRegistry(registryDict); - m_ScopeRegistries.Add(scopeRegistry.Url, scopeRegistry); + /// + /// Read the Manifest file and deserialize its content from JSON. + /// + 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; + 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()); - m_Dependencies.Add(dependency.Name, dependency); + 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); + } } } } - } - - /// - /// Returns dependency by a provided name. - /// - /// Name of the dependency. - /// Dependency with given name. - public Dependency GetDependency(string name) - { - return m_Dependencies[name]; - } - /// - /// Returns scope registry by a provided url. - /// - /// Scope registry url. - /// Scope registry with the given url. - public ScopeRegistry GetScopeRegistry(string url) - { - return m_ScopeRegistries[url]; - } + /// + /// Returns dependency by a provided name. + /// + /// Name of the dependency. + /// Dependency with given name. + public Dependency GetDependency(string name) { + return m_Dependencies[name]; + } - /// - /// Adds scope registry. - /// - /// An entry to add. - public void AddScopeRegistry(ScopeRegistry registry) - { - if (!IsRegistryPresent(registry.Url)) - { - m_ScopeRegistries.Add(registry.Url, registry); + /// + /// Returns scope registry by a provided url. + /// + /// Scope registry url. + /// Scope registry with the given url. + public ScopeRegistry GetScopeRegistry(string url) { + return m_ScopeRegistries[url]; } - } - - /// - /// Removes a scope registry - /// - /// - public void RemoveScopeRegistry(string url) - { - if (IsRegistryPresent(url)) - { - m_ScopeRegistries.Remove(url); + + /// + /// Adds scope registry. + /// + /// An entry to add. + public void AddScopeRegistry(ScopeRegistry registry) { + if (!IsRegistryPresent(registry.Url)) { + m_ScopeRegistries.Add(registry.Url, registry); + } } - } - /// - /// Adds dependency. - /// - /// Dependency name. - /// Dependency version. - public void AddDependency(string name, string version) - { - if (!IsDependencyPresent(name)) - { - var dependency = new Dependency(name, version); - m_Dependencies.Add(dependency.Name, dependency); + /// + /// Removes a scope registry + /// + /// + public void RemoveScopeRegistry(string url) { + if (IsRegistryPresent(url)) { + m_ScopeRegistries.Remove(url); + } } - } - - /// - /// Removes a dependency - /// - /// - public void RemoveDependency(string name) - { - if (IsDependencyPresent(name)) - { - m_Dependencies.Remove(name); + + /// + /// Adds dependency. + /// + /// Dependency name. + /// Dependency version. + public void AddDependency(string name, string version) { + if (!IsDependencyPresent(name)) { + var dependency = new Dependency(name, version); + m_Dependencies.Add(dependency.Name, dependency); + } } - } - /// - /// Writes changes back to the manifest file. - /// - public void ApplyChanges() - { - var registries = new List(); - foreach (var registry in m_ScopeRegistries.Values) - { - registries.Add(registry.ToDictionary()); + /// + /// Removes a dependency + /// + /// + public void RemoveDependency(string name) { + if (IsDependencyPresent(name)) { + m_Dependencies.Remove(name); + } } - m_RawContent[k_ScopedRegistriesKey] = registries; + /// + /// Writes changes back to the manifest file. + /// + public void ApplyChanges() { + var registries = new List(); - // Remove 'scopedRegistries' key from raw content if we have zero scope registries. - // Because we don't need an empty 'scopedRegistries' key in the manifest - if (registries.Count == 0) - m_RawContent.Remove(k_ScopedRegistriesKey); + foreach (var registry in m_ScopeRegistries.Values) { + registries.Add(registry.ToDictionary()); + } - Dictionary dependencies = new Dictionary(); - foreach (var dependency in m_Dependencies.Values) - { - dependencies.Add(dependency.Name, dependency.Version); - } + m_RawContent[k_ScopedRegistriesKey] = registries; - m_RawContent[k_DependenciesKey] = dependencies; + // Remove 'scopedRegistries' key from raw content if we have zero scope registries. + // Because we don't need an empty 'scopedRegistries' key in the manifest + if (registries.Count == 0) + m_RawContent.Remove(k_ScopedRegistriesKey); - string manifestText = Json.Serialize(m_RawContent, true); - File.WriteAllText(Path, manifestText); - } + Dictionary dependencies = new Dictionary(); - /// - /// Searches for ScopeRegistry with the provided Url. - /// - /// ScopeRegistry url to search for. - /// `true` if scoped registry found, `false` otherwise. - public bool IsRegistryPresent(string url) - { - return m_ScopeRegistries.ContainsKey(url); - } + foreach (var dependency in m_Dependencies.Values) { + dependencies.Add(dependency.Name, dependency.Version); + } - /// - /// Searches for a specific dependency by the provided name. - /// - /// The dependency name to search for. - /// `true` if found, `false` otherwise. - public bool IsDependencyPresent(string name) - { - return m_Dependencies.ContainsKey(name); + m_RawContent[k_DependenciesKey] = dependencies; + + string manifestText = Json.Serialize(m_RawContent, true); + File.WriteAllText(Path, manifestText); + } + + /// + /// Searches for ScopeRegistry with the provided Url. + /// + /// ScopeRegistry url to search for. + /// `true` if scoped registry found, `false` otherwise. + public bool IsRegistryPresent(string url) { + return m_ScopeRegistries.ContainsKey(url); + } + + /// + /// Searches for a specific dependency by the provided name. + /// + /// The dependency name to search for. + /// `true` if found, `false` otherwise. + public bool IsDependencyPresent(string name) { + return m_Dependencies.ContainsKey(name); + } } } \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistriesConfig.cs b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistriesConfig.cs deleted file mode 100644 index 147e15e6b..000000000 --- a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistriesConfig.cs +++ /dev/null @@ -1,4 +0,0 @@ -static class ScopeRegistriesConfig -{ - public static readonly string OneSignalScope = "com.onesignal.unity"; -} \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistriesConfig.cs.meta b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistriesConfig.cs.meta deleted file mode 100644 index 266826d10..000000000 --- a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistriesConfig.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 60133db353351420cb499e5f639dc3fb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs index d0f6a14fa..725312ebd 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs @@ -1,124 +1,145 @@ -using System.Collections.Generic; -using System.Linq; +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ -/// -/// Representation of "scopeRegistries" entry of the manifest file. -/// -class ScopeRegistry -{ - const string k_KeyName = "name"; - const string k_KeyUrl = "url"; - const string k_KeyScopes = "scopes"; +using System.Collections.Generic; +using System.Linq; +namespace OneSignalSDK { /// - /// Registry name. + /// Representation of "scopeRegistries" entry of the manifest file. /// - public string Name { get; } + public class ScopeRegistry { + const string k_KeyName = "name"; + const string k_KeyUrl = "url"; + const string k_KeyScopes = "scopes"; - /// - /// Registry url. - /// - public string Url { get; } + /// + /// Registry name. + /// + public string Name { get; } - /// - /// Registry scopes. - /// - public HashSet Scopes { get; } + /// + /// Registry url. + /// + public string Url { get; } - /// - /// Initializes a new instance of class with the provided properties. - /// - /// 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; - Scopes = scopes; - } + /// + /// Registry scopes. + /// + public HashSet Scopes { get; } - /// - /// Initializes a new instance of class with the provided data. - /// - /// Data to fill this object. Must contain name, - /// url and scopes. - public ScopeRegistry(Dictionary dictionary) - { - Name = (string) dictionary[k_KeyName]; - Url = (string) dictionary[k_KeyUrl]; - var scopes = (List) dictionary[k_KeyScopes]; - Scopes = new HashSet(); - foreach (var scope in scopes) - { - Scopes.Add((string) scope); + /// + /// Initializes a new instance of class with the provided properties. + /// + /// 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; + Scopes = scopes; } - } - /// - /// Returns true if provided scope exists in current scope registry. - /// - /// string scope to check if exists in this scope registry. - /// 'true' if this ScopeRegistry contains scope, `false` otherwise. - public bool HasScope(string scope) - { - return Scopes.Contains(scope); - } + /// + /// Initializes a new instance of class with the provided data. + /// + /// Data to fill this object. Must contain name, + /// url and scopes. + public ScopeRegistry(Dictionary dictionary) { + Name = (string)dictionary[k_KeyName]; + Url = (string)dictionary[k_KeyUrl]; + var scopes = (List)dictionary[k_KeyScopes]; + Scopes = new HashSet(); - /// - /// Adds scope. - /// - /// A scope to add. - public void AddScope(string scope) - { - if (!HasScope(scope)) - Scopes.Add(scope); - } + foreach (var scope in scopes) { + Scopes.Add((string)scope); + } + } - /// - /// Generates a hash of this object data, excluding Name. - /// - /// Hash of this object. - public override int GetHashCode() - { - int hash = 0; - if (!string.IsNullOrEmpty(Url)) - hash ^= Url.GetHashCode(); - if (Scopes != null) - { - foreach (var scope in Scopes) - { - hash ^= scope.GetHashCode(); + /// + /// Returns true if provided scope exists in current scope registry. + /// + /// string scope to check if exists in this scope registry. + /// 'true' if this ScopeRegistry contains scope, `false` otherwise. + public bool HasScope(string scope) { + return Scopes.Contains(scope); + } + + /// + /// Adds scope. + /// + /// A scope to add. + public void AddScope(string scope) { + if (!HasScope(scope)) + Scopes.Add(scope); + } + + /// + /// Generates a hash of this object data, excluding Name. + /// + /// Hash of this object. + public override int GetHashCode() { + int hash = 0; + if (!string.IsNullOrEmpty(Url)) + hash ^= Url.GetHashCode(); + + if (Scopes != null) { + foreach (var scope in Scopes) { + hash ^= scope.GetHashCode(); + } } + + return hash; } - return hash; - } + /// + /// Method for matching entries, Name matching is not necessary. + /// + /// 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); + } - /// - /// Method for matching entries, Name matching is not necessary. - /// - /// 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); - } + /// + /// Creates dictionary from this object. + /// + /// ScopeRegistry object representation as Dictionary<string, object>. + public Dictionary ToDictionary() { + Dictionary result = new Dictionary(); + result.Add(k_KeyName, Name); + result.Add(k_KeyUrl, Url); + result.Add(k_KeyScopes, Scopes.ToList()); - /// - /// Creates dictionary from this object. - /// - /// ScopeRegistry object representation as Dictionary<string, object>. - public Dictionary ToDictionary() - { - Dictionary result = new Dictionary(); - result.Add(k_KeyName, Name); - result.Add(k_KeyUrl, Url); - result.Add(k_KeyScopes, Scopes.ToList()); - return result; + return result; + } } } \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignal/Editor/Resources/OneSignalFileInventory.asset b/OneSignalExample/Assets/OneSignal/Editor/Resources/OneSignalFileInventory.asset index 05fca9f21..cf66ff1c6 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/Resources/OneSignalFileInventory.asset +++ b/OneSignalExample/Assets/OneSignal/Editor/Resources/OneSignalFileInventory.asset @@ -56,13 +56,10 @@ MonoBehaviour: - Assets/OneSignal/Editor/Resources.meta - Assets/OneSignal/Editor/Setup.meta - Assets/OneSignal/Editor/SetupSteps.meta - - Assets/OneSignal/Editor/Utilities.meta - Assets/OneSignal/Editor/PackageManagement/Dependency.cs - Assets/OneSignal/Editor/PackageManagement/Dependency.cs.meta - Assets/OneSignal/Editor/PackageManagement/Manifest.cs - Assets/OneSignal/Editor/PackageManagement/Manifest.cs.meta - - Assets/OneSignal/Editor/PackageManagement/ScopeRegistriesConfig.cs - - Assets/OneSignal/Editor/PackageManagement/ScopeRegistriesConfig.cs.meta - Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs - Assets/OneSignal/Editor/PackageManagement/ScopeRegistry.cs.meta - Assets/OneSignal/Editor/Resources/OneSignalFileInventory.asset @@ -75,10 +72,6 @@ MonoBehaviour: - Assets/OneSignal/Editor/SetupSteps/CleanUpLegacyStep.cs.meta - Assets/OneSignal/Editor/SetupSteps/ImportPackagesStep.cs - Assets/OneSignal/Editor/SetupSteps/ImportPackagesStep.cs.meta - - Assets/OneSignal/Editor/Utilities/GitHubUtility.cs - - Assets/OneSignal/Editor/Utilities/GitHubUtility.cs.meta - - Assets/OneSignal/Editor/Utilities/MiniJSON.cs - - Assets/OneSignal/Editor/Utilities/MiniJSON.cs.meta - Assets/OneSignal/Example/INCONSOLATA-VARIABLEFONT_WDTH,WGHT.TTF - Assets/OneSignal/Example/INCONSOLATA-VARIABLEFONT_WDTH,WGHT.TTF.meta - Assets/OneSignal/Example/OneSignal.UnityPackage.Example.asmdef diff --git a/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupStep.cs b/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupStep.cs index 7174e7429..0c98d60f9 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupStep.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupStep.cs @@ -1,59 +1,85 @@ #if !ONE_SIGNAL_INSTALLED -/// -/// Abstract class which must be inherited from in order to create a new setup step -/// -public abstract class OneSignalSetupStep -{ - /// - /// Short description of what this step will do - /// - public abstract string Summary { get; } - - /// - /// Detailed description of precisely what this step will do - /// - public abstract string Details { get; } +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +namespace OneSignalSDK { /// - /// Whether this step is required for operation of the SDK + /// Abstract class which must be inherited from in order to create a new setup step /// - public abstract bool IsRequired { get; } - - /// - /// Checks whether or not this step has been completed - /// - /// - /// The result is cached and only reset on run or specific other conditions - /// - public bool IsStepCompleted { - get - { - if (!_shouldCheckForCompletion) + public abstract class OneSignalSetupStep { + /// + /// Short description of what this step will do + /// + public abstract string Summary { get; } + + /// + /// Detailed description of precisely what this step will do + /// + public abstract string Details { get; } + + /// + /// Whether this step is required for operation of the SDK + /// + public abstract bool IsRequired { get; } + + /// + /// Checks whether or not this step has been completed + /// + /// + /// The result is cached and only reset on run or specific other conditions + /// + public bool IsStepCompleted { + get { + if (!_shouldCheckForCompletion) + return _isComplete; + + _isComplete = _getIsStepCompleted(); + _shouldCheckForCompletion = false; + return _isComplete; - - _isComplete = _getIsStepCompleted(); - _shouldCheckForCompletion = false; + } + } - return _isComplete; - } - } + /// + /// Runs all code necessary in order to fulfill the step + /// + public void RunStep() { + if (IsStepCompleted) + return; - /// - /// Runs all code necessary in order to fulfill the step - /// - public void RunStep() - { - if (IsStepCompleted) - return; - - _runStep(); - _shouldCheckForCompletion = true; - } + _runStep(); + _shouldCheckForCompletion = true; + } - protected abstract bool _getIsStepCompleted(); - protected abstract void _runStep(); + protected abstract bool _getIsStepCompleted(); + protected abstract void _runStep(); - private bool _isComplete = false; - protected bool _shouldCheckForCompletion = true; + private bool _isComplete = false; + protected bool _shouldCheckForCompletion = true; + } } #endif \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupWindow.cs b/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupWindow.cs index c636e32bf..aa7141bfd 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupWindow.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/Setup/OneSignalSetupWindow.cs @@ -1,189 +1,193 @@ #if !ONE_SIGNAL_INSTALLED +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System; using System.Collections.Generic; -using System.Linq; -using System.Xml; using UnityEditor; using UnityEngine; -using UnityEngine.UI; - -/// -/// Pop up window which displays any additional required or optional setup steps by the SDK -/// -public sealed class OneSignalSetupWindow : EditorWindow -{ - [MenuItem("Window/OneSignal")] - public static void ShowWindow() - { - var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); - window.minSize = _minSize; - window.Show(); - } - - public static void CloseWindow() - { - var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); - window.Close(); - } - 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 IReadOnlyList _setupSteps; - private readonly Queue _stepsToRun = new Queue(); - - private bool _guiSetupComplete = false; - private GUIStyle _summaryStyle; - private GUIStyle _runStyle; - private GUIStyle _detailsStyle; - private GUIStyle _requiredStyle; - private GUIStyle _optionalStyle; - private Texture _checkTexture; - private Texture _boxTexture; - - private Vector2 _scrollPosition; - - private void OnEnable() - { - var stepTypes = _findAllAssignableTypes("OneSignal"); - var steps = new List(); - - foreach (var stepType in stepTypes) - { - if (Activator.CreateInstance(stepType) is OneSignalSetupStep step) - steps.Add(step); - else - Debug.LogWarning($"could not create setup step from type {stepType.Name}"); +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")] public static void ShowWindow() { + var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); + window.minSize = _minSize; + window.Show(); } - _setupSteps = steps; - } + public static void CloseWindow() { + var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); + window.Close(); + } - private void OnGUI() - { - _setupGUI(); + private static readonly Vector2 _minSize = new Vector2(300, 400); - GUILayout.Label(_description); - EditorGUILayout.Separator(); + private const string _title = "OneSignal SDK Setup"; + private const string _description = "Additional steps required to get the OneSignal Unity SDK up and running"; - if (_setupSteps == null) - return; + private IReadOnlyList _setupSteps; + private readonly Queue _stepsToRun = new Queue(); - var willDisableControls = _stepsToRun.Count > 0 - || EditorApplication.isUpdating - || EditorApplication.isCompiling; + private bool _guiSetupComplete = false; + private GUIStyle _summaryStyle; + private GUIStyle _runStyle; + private GUIStyle _detailsStyle; + private GUIStyle _requiredStyle; + private GUIStyle _optionalStyle; + private Texture _checkTexture; + private Texture _boxTexture; - EditorGUI.BeginDisabledGroup(willDisableControls); - if (GUILayout.Button("Run All Steps")) - { - foreach (var step in _setupSteps) - _stepsToRun.Enqueue(step); + private Vector2 _scrollPosition; + + private void OnEnable() { + var stepTypes = ReflectionHelpers.FindAllAssignableTypes("OneSignal"); + var steps = new List(); + + foreach (var stepType in stepTypes) { + if (Activator.CreateInstance(stepType) is OneSignalSetupStep step) + steps.Add(step); + else + Debug.LogWarning($"could not create setup step from type {stepType.Name}"); + } + + _setupSteps = steps; } - EditorGUI.EndDisabledGroup(); - - EditorGUILayout.Separator(); - EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); - - EditorGUILayout.BeginHorizontal(); - _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); - - foreach (var step in _setupSteps) - { - EditorGUILayout.BeginHorizontal(); - var sumContent = new GUIContent(step.Summary); - var sumRect = GUILayoutUtility.GetRect(sumContent, _summaryStyle); + private void OnGUI() { + _setupGUI(); + + GUILayout.Label(_description); + EditorGUILayout.Separator(); + + if (_setupSteps == null) + return; + + var willDisableControls = _stepsToRun.Count > 0 + || EditorApplication.isUpdating + || EditorApplication.isCompiling; - var checkRect = new Rect(sumRect.x, sumRect.y, sumRect.height, sumRect.height); - GUI.DrawTexture(checkRect, step.IsStepCompleted ? _checkTexture: _boxTexture); + EditorGUI.BeginDisabledGroup(willDisableControls); + + if (GUILayout.Button("Run All Steps")) { + foreach (var step in _setupSteps) + _stepsToRun.Enqueue(step); + } - sumRect.x += sumRect.height + EditorStyles.label.padding.left; - GUI.Label(sumRect, sumContent); - - EditorGUI.BeginDisabledGroup(step.IsStepCompleted || willDisableControls); - if (GUILayout.Button("Run", _runStyle) && !_stepsToRun.Contains(step)) - _stepsToRun.Enqueue(step); EditorGUI.EndDisabledGroup(); - - EditorGUILayout.EndHorizontal(); - EditorGUILayout.Separator(); - GUILayout.Label(step.Details, _detailsStyle); - - if (step.IsRequired) - GUILayout.Label("Required", _requiredStyle); - else - GUILayout.Label("Optional", _optionalStyle); - + EditorGUILayout.Separator(); EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + + EditorGUILayout.BeginHorizontal(); + _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); + + foreach (var step in _setupSteps) { + EditorGUILayout.BeginHorizontal(); + + var sumContent = new GUIContent(step.Summary); + 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); + + sumRect.x += sumRect.height + EditorStyles.label.padding.left; + GUI.Label(sumRect, sumContent); + + EditorGUI.BeginDisabledGroup(step.IsStepCompleted || willDisableControls); + if (GUILayout.Button("Run", _runStyle) && !_stepsToRun.Contains(step)) + _stepsToRun.Enqueue(step); + + EditorGUI.EndDisabledGroup(); + + EditorGUILayout.EndHorizontal(); + EditorGUILayout.Separator(); + + GUILayout.Label(step.Details, _detailsStyle); + + if (step.IsRequired) + GUILayout.Label("Required", _requiredStyle); + else + GUILayout.Label("Optional", _optionalStyle); + + EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + } + + EditorGUILayout.EndScrollView(); + EditorGUILayout.EndHorizontal(); } - - EditorGUILayout.EndScrollView(); - EditorGUILayout.EndHorizontal(); - } - private void OnInspectorUpdate() - { - var runnerCount = _stepsToRun.Count + 1.0f; - while (_stepsToRun.Count > 0) - { - var step = _stepsToRun.Dequeue(); - - EditorUtility.DisplayProgressBar( - "OneSignal Setup", - $"Running step \"{step.Summary}\"", - _stepsToRun.Count / runnerCount - ); - - step.RunStep(); + private void OnInspectorUpdate() { + var runnerCount = _stepsToRun.Count + 1.0f; + + while (_stepsToRun.Count > 0) { + var step = _stepsToRun.Dequeue(); + + EditorUtility.DisplayProgressBar( + "OneSignal Setup", + $"Running step \"{step.Summary}\"", + _stepsToRun.Count / runnerCount + ); + + step.RunStep(); + } + + EditorUtility.ClearProgressBar(); } - EditorUtility.ClearProgressBar(); - } - private void _setupGUI() - { - if (_guiSetupComplete) - return; + private void _setupGUI() { + if (_guiSetupComplete) + return; - _summaryStyle = EditorStyles.boldLabel; + _summaryStyle = EditorStyles.boldLabel; - _detailsStyle = new GUIStyle(GUI.skin.textField); - _detailsStyle.wordWrap = true; + _detailsStyle = new GUIStyle(GUI.skin.textField); + _detailsStyle.wordWrap = true; - _runStyle = new GUIStyle(GUI.skin.button); - _runStyle.fixedWidth = _minSize.x * .3f; + _runStyle = new GUIStyle(GUI.skin.button); + _runStyle.fixedWidth = _minSize.x * .3f; - _requiredStyle = new GUIStyle(EditorStyles.miniBoldLabel); - _requiredStyle.normal.textColor = Color.red; + _requiredStyle = new GUIStyle(EditorStyles.miniBoldLabel); + _requiredStyle.normal.textColor = Color.red; - _optionalStyle = new GUIStyle(EditorStyles.miniBoldLabel); - _optionalStyle.normal.textColor = Color.yellow; - _optionalStyle.fontStyle = FontStyle.Italic; + _optionalStyle = new GUIStyle(EditorStyles.miniBoldLabel); + _optionalStyle.normal.textColor = Color.yellow; + _optionalStyle.fontStyle = FontStyle.Italic; - var checkContent = EditorGUIUtility.IconContent("TestPassed"); - _checkTexture = checkContent.image; + var checkContent = EditorGUIUtility.IconContent("TestPassed"); + _checkTexture = checkContent.image; - var boxContent = EditorGUIUtility.IconContent("Warning"); - _boxTexture = boxContent.image; - - _guiSetupComplete = true; - } + var boxContent = EditorGUIUtility.IconContent("Warning"); + _boxTexture = boxContent.image; - private static IEnumerable _findAllAssignableTypes(string assemblyFilter) - { - var assignableType = typeof(T); - - var assemblies = AppDomain.CurrentDomain.GetAssemblies(); - 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)); - - return assignableTypes; + _guiSetupComplete = true; + } } } #endif \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/CleanUpLegacyStep.cs b/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/CleanUpLegacyStep.cs index c03e3ee7b..61edeaec7 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/CleanUpLegacyStep.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/CleanUpLegacyStep.cs @@ -1,56 +1,82 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; -/// -/// 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 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; - - protected override bool _getIsStepCompleted() - { - var diff = _getDiff(); - - if (diff == null) - return true; // error - - return !diff.Any(); - } +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"; - protected override void _runStep() - { - var diff = _getDiff(); - - if (diff == null) - return; // error + public override string Details + => "Checks for the diff between the files distributed with the package and those which are in the " + + OneSignalFileInventory.PackageAssetsPath; - foreach (var path in diff) - File.Delete(path); - } + public override bool IsRequired + => true; - private IEnumerable _getDiff() - { - if (_inventory == null) - _inventory = AssetDatabase.LoadAssetAtPath(OneSignalFileInventory.AssetPath); + protected override bool _getIsStepCompleted() { + var diff = _getDiff(); - if (_inventory == null) - return null; // error - - var currentPaths = OneSignalFileInventory.GetCurrentPaths(); - return currentPaths.Except(_inventory.DistributedPaths); - } + if (diff == null) + return true; // error + + return !diff.Any(); + } + + protected override void _runStep() { + var diff = _getDiff(); + + if (diff == null) + return; // error - private OneSignalFileInventory _inventory; + foreach (var path in diff) + File.Delete(path); + } + + private IEnumerable _getDiff() { + if (_inventory == null) + _inventory = AssetDatabase.LoadAssetAtPath(OneSignalFileInventory.AssetPath); + + if (_inventory == null) + return null; // error + + var currentPaths = OneSignalFileInventory.GetCurrentPaths(); + + return currentPaths.Except(_inventory.DistributedPaths); + } + + 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 a94152358..de5898c87 100644 --- a/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/ImportPackagesStep.cs +++ b/OneSignalExample/Assets/OneSignal/Editor/SetupSteps/ImportPackagesStep.cs @@ -1,40 +1,66 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; -/// -/// 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"; +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 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 - protected override bool _getIsStepCompleted() => true; + protected override bool _getIsStepCompleted() => true; #else - protected override bool _getIsStepCompleted() => false; + protected override bool _getIsStepCompleted() => false; #endif - - protected override void _runStep() - { - var manifest = new Manifest(); - manifest.Fetch(); - - manifest.AddScopeRegistry(_scopeRegistry); - - var scopeRegistry = manifest.GetScopeRegistry(_registryUrl); - scopeRegistry.AddScope(_packagesScope); -#if UNITY_2017_3_OR_NEWER + protected override void _runStep() { + var manifest = new Manifest(); + manifest.Fetch(); + + manifest.AddScopeRegistry(_scopeRegistry); + + var scopeRegistry = manifest.GetScopeRegistry(_registryUrl); + scopeRegistry.AddScope(_packagesScope); + + #if UNITY_2017_3_OR_NEWER manifest.ApplyChanges(); var addRequest = UnityEditor.PackageManager.Client.Add(_coreVersion); @@ -47,54 +73,54 @@ protected override void _runStep() while (!addRequest.IsCompleted) { } #else manifest.AddDependency(_corePackageName, _coreVersion); - manifest.AddDependency(_androidPackageName, _androidVersion); - manifest.AddDependency(_iosPackageName, _iosVersion); + manifest.AddDependency(_androidPackageName, _androidVersion); + manifest.AddDependency(_iosPackageName, _iosVersion); - manifest.ApplyChanges(); - AssetDatabase.Refresh(); -#endif - OneSignalSetupWindow.CloseWindow(); - SessionState.SetBool(_shouldShowWindowKey, true); - } + manifest.ApplyChanges(); + AssetDatabase.Refresh(); + #endif + OneSignalSetupWindow.CloseWindow(); + SessionState.SetBool(_shouldShowWindowKey, true); + } -#if ONE_SIGNAL_INSTALLED - [InitializeOnLoadMethod] - public static void _showCoreInstallerWindow() - { - if (!SessionState.GetBool(_shouldShowWindowKey, false)) - return; - - SessionState.EraseBool(_shouldShowWindowKey); - EditorApplication.delayCall += OneSignalSetupWindow.ShowWindow; - } -#endif - - private const string _shouldShowWindowKey = "onesignal.importpackage.shouldshow"; - private const string _packagesScope = "com.onesignal"; - - private static readonly string _corePackageName = $"{_packagesScope}.unity.core"; - private static readonly string _androidPackageName = $"{_packagesScope}.unity.android"; - private static readonly string _iosPackageName = $"{_packagesScope}.unity.ios"; - -#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 - private static string _coreVersion => $"{_corePackageName}@{_version}"; - private static string _androidVersion => $"{_androidPackageName}@{_version}"; - private static string _iosVersion => $"{_iosPackageName}@{_version}"; + #if ONE_SIGNAL_INSTALLED + [InitializeOnLoadMethod] + public static void _showCoreInstallerWindow() { + if (!SessionState.GetBool(_shouldShowWindowKey, false)) + return; + + SessionState.EraseBool(_shouldShowWindowKey); + EditorApplication.delayCall += OneSignalSetupWindow.ShowWindow; + } + #endif + + private const string _shouldShowWindowKey = "onesignal.importpackage.shouldshow"; + private const string _packagesScope = "com.onesignal"; + + private static readonly string _corePackageName = $"{_packagesScope}.unity.core"; + private static readonly string _androidPackageName = $"{_packagesScope}.unity.android"; + private static readonly string _iosPackageName = $"{_packagesScope}.unity.ios"; - private const string _registryName = "npmjs"; - private const string _registryUrl = "https://registry.npmjs.org"; + #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 static readonly string _versionPath = Path.Combine("Assets", "OneSignal", "VERSION"); - private static string _version => File.ReadAllText(_versionPath); -#endif + private const string _registryName = "npmjs"; + private const string _registryUrl = "https://registry.npmjs.org"; + #else + private static string _coreVersion => $"{_corePackageName}@{_version}"; + private static string _androidVersion => $"{_androidPackageName}@{_version}"; + private static string _iosVersion => $"{_iosPackageName}@{_version}"; + + private const string _registryName = "npmjs"; + private const string _registryUrl = "https://registry.npmjs.org"; - private static readonly HashSet _scopes = new HashSet { _packagesScope }; - private static readonly ScopeRegistry _scopeRegistry = new ScopeRegistry(_registryName, _registryUrl, _scopes); + private static readonly string _versionPath = Path.Combine("Assets", "OneSignal", "VERSION"); + private static string _version => File.ReadAllText(_versionPath); + #endif + + private static readonly HashSet _scopes = new HashSet { _packagesScope }; + private static readonly ScopeRegistry _scopeRegistry = new ScopeRegistry(_registryName, _registryUrl, _scopes); + } } \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignal/Editor/Utilities.meta b/OneSignalExample/Assets/OneSignal/Editor/Utilities.meta deleted file mode 100644 index 3c61c594b..000000000 --- a/OneSignalExample/Assets/OneSignal/Editor/Utilities.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 5965219f4d384edc82f7e45bbb68eebb -timeCreated: 1624978578 \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignal/Editor/Utilities/GitHubUtility.cs b/OneSignalExample/Assets/OneSignal/Editor/Utilities/GitHubUtility.cs deleted file mode 100644 index 15e3de284..000000000 --- a/OneSignalExample/Assets/OneSignal/Editor/Utilities/GitHubUtility.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using OneSignalPush.Utilities; -using UnityEngine.Networking; - -static class GitHubUtility -{ - internal static void GetLatestRelease(string url, Action callback) - { - var rq = UnityWebRequest.Get(GetReleaseInfoFromURL(url)); - rq.SendWebRequest().completed += obj => - { - var jsonObject = (Dictionary) Json.Deserialize(rq.downloadHandler.text); - string releaseName = jsonObject.TryGetValue("name", out var name) ? (string) name : string.Empty; - callback(releaseName); - }; - } - - static string GetReleaseInfoFromURL(string repositoryURL) - { - if (repositoryURL.Contains("github.com")) - { - return repositoryURL.Replace(@".git", @"/releases/latest") - .Replace(@"ssh://git@github.com:", @"https://api.github.com/repos/"); - } - - throw new InvalidOperationException($"The provided URL {repositoryURL} is not a GitHub repository URL."); - } -} \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignal/Editor/Utilities/GitHubUtility.cs.meta b/OneSignalExample/Assets/OneSignal/Editor/Utilities/GitHubUtility.cs.meta deleted file mode 100644 index 4096d1c52..000000000 --- a/OneSignalExample/Assets/OneSignal/Editor/Utilities/GitHubUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 54e1af83b23e31840ba67b75104e4348 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs b/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs deleted file mode 100644 index 7f461e805..000000000 --- a/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs +++ /dev/null @@ -1,585 +0,0 @@ -/* - * Copyright (c) 2013 Calvin Rien - * - * Based on the JSON parser by Patrick van Bergen - * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html - * - * Simplified it so that it doesn't throw exceptions - * and can be used in Unity iPhone with maximum code stripping. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights 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: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * 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 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Text; - -// Forked from https://github.com/Jackyjjc/MiniJSON.cs -// version: 6de00beb134bbab9d873033a48b32e4067ed0c25 - -namespace OneSignalPush.Utilities -{ - // Example usage: - // - // using UnityEngine; - // using System.Collections; - // using System.Collections.Generic; - // using MiniJSON; - // - // public class MiniJSONTest : MonoBehaviour { - // void Start () { - // var jsonString = "{ \"array\": [1.44,2,3], " + - // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + - // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + - // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + - // "\"int\": 65536, " + - // "\"float\": 3.1415926, " + - // "\"bool\": true, " + - // "\"null\": null }"; - // - // var dict = Json.Deserialize(jsonString) as Dictionary; - // - // Debug.Log("deserialized: " + dict.GetType()); - // Debug.Log("dict['array'][0]: " + ((List) dict["array"])[0]); - // Debug.Log("dict['string']: " + (string) dict["string"]); - // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles - // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs - // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); - // - // var str = Json.Serialize(dict); - // - // Debug.Log("serialized: " + str); - // } - // } - - /// - /// This class encodes and decodes JSON strings. - /// Spec. details, see http://www.json.org/ - /// - /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. - /// All numbers are parsed to doubles. - /// - static class Json { - /// - /// Parses the string json into a value - /// - /// A JSON string. - /// An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false - public static object Deserialize(string json) { - // save the string for debug information - if (json == null) { - return null; - } - - return Parser.Parse(json); - } - - sealed class Parser : IDisposable { - const string WORD_BREAK = "{}[],:\""; - - public static bool IsWordBreak(char c) { - return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; - } - - enum TOKEN { - NONE, - CURLY_OPEN, - CURLY_CLOSE, - SQUARED_OPEN, - SQUARED_CLOSE, - COLON, - COMMA, - STRING, - NUMBER, - TRUE, - FALSE, - NULL - }; - - StringReader json; - - Parser(string jsonString) { - json = new StringReader(jsonString); - } - - public static object Parse(string jsonString) { - using (var instance = new Parser(jsonString)) { - return instance.ParseValue(); - } - } - - public void Dispose() { - json.Dispose(); - json = null; - } - - Dictionary ParseObject() { - Dictionary table = new Dictionary(); - - // ditch opening brace - json.Read(); - - while (true) { - switch (NextToken) { - case TOKEN.NONE: - return null; - case TOKEN.COMMA: - continue; - case TOKEN.CURLY_CLOSE: - return table; - default: - // name - string name = ParseString(); - if (name == null) { - return null; - } - - // : - if (NextToken != TOKEN.COLON) { - return null; - } - // ditch the colon - json.Read(); - - // value - table[name] = ParseValue(); - break; - } - } - } - - List ParseArray() { - List array = new List(); - - // ditch opening bracket - json.Read(); - - // [ - var parsing = true; - while (parsing) { - TOKEN nextToken = NextToken; - - switch (nextToken) { - case TOKEN.NONE: - return null; - case TOKEN.COMMA: - continue; - case TOKEN.SQUARED_CLOSE: - parsing = false; - break; - default: - object value = ParseByToken(nextToken); - - array.Add(value); - break; - } - } - - return array; - } - - object ParseValue() { - TOKEN nextToken = NextToken; - return ParseByToken(nextToken); - } - - object ParseByToken(TOKEN token) { - switch (token) { - case TOKEN.STRING: - return ParseString(); - case TOKEN.NUMBER: - return ParseNumber(); - case TOKEN.CURLY_OPEN: - return ParseObject(); - case TOKEN.SQUARED_OPEN: - return ParseArray(); - case TOKEN.TRUE: - return true; - case TOKEN.FALSE: - return false; - case TOKEN.NULL: - return null; - default: - return null; - } - } - - string ParseString() { - StringBuilder s = new StringBuilder(); - char c; - - // ditch opening quote - json.Read(); - - bool parsing = true; - while (parsing) { - - if (json.Peek() == -1) { - break; - } - - c = NextChar; - switch (c) { - case '"': - parsing = false; - break; - case '\\': - if (json.Peek() == -1) { - parsing = false; - break; - } - - c = NextChar; - switch (c) { - case '"': - case '\\': - case '/': - s.Append(c); - break; - case 'b': - s.Append('\b'); - break; - case 'f': - s.Append('\f'); - break; - case 'n': - s.Append('\n'); - break; - case 'r': - s.Append('\r'); - break; - case 't': - s.Append('\t'); - break; - case 'u': - var hex = new char[4]; - - for (int i=0; i< 4; i++) { - hex[i] = NextChar; - } - - s.Append((char) Convert.ToInt32(new string(hex), 16)); - break; - default: - s.Append(c); - break; - } - break; - default: - s.Append(c); - break; - } - } - - return s.ToString(); - } - - object ParseNumber() { - string number = NextWord; - - 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); - return parsedInt; - } - - double parsedDouble; - Double.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble); - return parsedDouble; - } - - void EatWhitespace() { - while (Char.IsWhiteSpace(PeekChar)) { - json.Read(); - - if (json.Peek() == -1) { - break; - } - } - } - - char PeekChar { - get { - return Convert.ToChar(json.Peek()); - } - } - - char NextChar { - get { - return Convert.ToChar(json.Read()); - } - } - - string NextWord { - get { - StringBuilder word = new StringBuilder(); - - while (!IsWordBreak(PeekChar)) { - word.Append(NextChar); - - if (json.Peek() == -1) { - break; - } - } - - return word.ToString(); - } - } - - TOKEN NextToken { - get { - EatWhitespace(); - - if (json.Peek() == -1) { - return TOKEN.NONE; - } - - switch (PeekChar) { - case '{': - return TOKEN.CURLY_OPEN; - case '}': - json.Read(); - return TOKEN.CURLY_CLOSE; - case '[': - return TOKEN.SQUARED_OPEN; - case ']': - json.Read(); - return TOKEN.SQUARED_CLOSE; - case ',': - json.Read(); - return TOKEN.COMMA; - case '"': - return TOKEN.STRING; - case ':': - return TOKEN.COLON; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - return TOKEN.NUMBER; - default: - switch (NextWord) { - case "false": - return TOKEN.FALSE; - case "true": - return TOKEN.TRUE; - case "null": - return TOKEN.NULL; - default: - return TOKEN.NONE; - } - } - } - } - } - - /// - /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string - /// - /// A Dictionary<string, object> / List<object> - /// Whether output as human readable format with spaces and - /// 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) { - return Serializer.MakeSerialization(obj, humanReadable, indentSpaces); - } - - sealed class Serializer { - readonly StringBuilder builder; - readonly bool humanReadable; - readonly int indentSpaces; - int indentLevel; - - Serializer(bool humanReadable, int indentSpaces) { - builder = new StringBuilder(); - this.humanReadable = humanReadable; - this.indentSpaces = indentSpaces; - indentLevel = 0; - } - - public static string MakeSerialization(object obj, bool humanReadable, int indentSpaces) { - var instance = new Serializer(humanReadable, indentSpaces); - - instance.SerializeValue(obj); - - return instance.builder.ToString(); - } - - void SerializeValue(object value) { - IList asList; - IDictionary asDict; - string asStr; - - if (value == null) { - builder.Append("null"); - } else if ((asStr = value as string) != null) { - SerializeString(asStr); - } else if (value is bool) { - builder.Append((bool) value ? "true" : "false"); - } else if ((asList = value as IList) != null) { - SerializeArray(asList); - } else if ((asDict = value as IDictionary) != null) { - SerializeObject(asDict); - } else if (value is char) { - SerializeString(new string((char) value, 1)); - } else { - SerializeOther(value); - } - } - - void AppendNewLineFunc() { - builder.AppendLine(); - builder.Append(' ', indentSpaces * indentLevel); - } - - void SerializeObject(IDictionary obj) { - bool first = true; - - builder.Append('{'); - ++indentLevel; - - foreach (object e in obj.Keys) { - if (first) { - if (humanReadable) AppendNewLineFunc(); - } else { - builder.Append(','); - if (humanReadable) AppendNewLineFunc(); - } - - SerializeString(e.ToString()); - builder.Append(':'); - if (humanReadable) builder.Append(' '); - - SerializeValue(obj[e]); - - first = false; - } - - --indentLevel; - if (humanReadable && obj.Count > 0) AppendNewLineFunc(); - - builder.Append('}'); - } - - void SerializeArray(IList anArray) { - builder.Append('['); - ++indentLevel; - - bool first = true; - - for (int i=0; i 0) AppendNewLineFunc(); - - builder.Append(']'); - } - - void SerializeString(string str) { - builder.Append('\"'); - - char[] charArray = str.ToCharArray(); - for (int i=0; i= 32) && (codepoint <= 126)) { - builder.Append(c); - } else { - builder.Append("\\u"); - builder.Append(codepoint.ToString("x4")); - } - break; - } - } - - builder.Append('\"'); - } - - void SerializeOther(object value) { - // NOTE: decimals lose precision during serialization. - // They always have, I'm just letting you know. - // Previously floats and doubles lost precision too. - if (value is float) { - 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) { - builder.Append(value); - } else if (value is double - || value is decimal) { - builder.Append(Convert.ToDouble(value).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); - } else { - SerializeString(value.ToString()); - } - } - } - } -} diff --git a/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs.meta b/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs.meta deleted file mode 100644 index 530013ff6..000000000 --- a/OneSignalExample/Assets/OneSignal/Editor/Utilities/MiniJSON.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4d72009a2475be35697639eaf34a7221 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/OneSignalExample/Assets/OneSignal/Example/OneSignalExampleBehaviour.cs b/OneSignalExample/Assets/OneSignal/Example/OneSignalExampleBehaviour.cs index 5fc50620e..4a70f13e5 100644 --- a/OneSignalExample/Assets/OneSignal/Example/OneSignalExampleBehaviour.cs +++ b/OneSignalExample/Assets/OneSignal/Example/OneSignalExampleBehaviour.cs @@ -1,446 +1,471 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + #if ONE_SIGNAL_INSTALLED using System; using System.Collections.Generic; +using OneSignalSDK; using UnityEngine; using UnityEngine.UI; -using UnityEngine.UIElements; // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace -namespace OneSignalSDK { +/// +/// Example class to show how an application can utilize the public methods of the OneSignal SDK +/// +public class OneSignalExampleBehaviour : MonoBehaviour { /// - /// Example class to show how an application can utilize the public methods of the OneSignal SDK + /// set to an email address you would like to test notifications against /// - public class OneSignalExampleBehaviour : MonoBehaviour { - /// - /// set to an email address you would like to test notifications against - /// - public string email; - - /// - /// set to an external user id you would like to test notifications against - /// - public string externalId; - - /// - /// set to an external user id you would like to test notifications against - /// - public string phoneNumber; - - /// - /// set to your app id (https://documentation.onesignal.com/docs/accounts-and-keys) - /// - public string appId; - - /// - /// whether you would prefer OneSignal Unity SDK prevent initialization until consent is granted via - /// in this test MonoBehaviour - /// - public bool requiresUserPrivacyConsent; - - /// - /// - /// - public string tagKey; - - /// - /// - /// - public string tagValue; - - /// - /// - /// - public string triggerKey; - - /// - /// - /// - public string triggerValue; - - /// - /// - /// - public string outcomeKey; - - /// - /// - /// - public float outcomeValue; - - /// - /// 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() { - // Enable lines below to debug issues with OneSignal - OneSignal.Default.LogLevel = LogLevel.Info; - OneSignal.Default.AlertLevel = LogLevel.Fatal; - - // Setting RequiresPrivacyConsent to true will prevent the OneSignalSDK from operating until - // PrivacyConsent is also set to true - OneSignal.Default.RequiresPrivacyConsent = requiresUserPrivacyConsent; - - // Setup the below to listen for and respond to events from notifications - OneSignal.Default.NotificationOpened += _notificationOpened; - OneSignal.Default.NotificationWillShow += _notificationReceived; - - // Setup the below to listen for and respond to events from in app messages - OneSignal.Default.InAppMessageWillDisplay += _iamWillDisplay; - OneSignal.Default.InAppMessageDidDisplay += _iamDidDisplay; - OneSignal.Default.InAppMessageWillDismiss += _iamWillDismiss; - OneSignal.Default.InAppMessageDidDismiss += _iamDidDismiss; - OneSignal.Default.InAppMessageTriggeredAction += _iamTriggeredAction; - - // Setup the below to listen for and respond to state changes - OneSignal.Default.NotificationPermissionChanged += _notificationPermissionChanged; - OneSignal.Default.PushSubscriptionStateChanged += _pushStateChanged; - OneSignal.Default.EmailSubscriptionStateChanged += _emailStateChanged; - OneSignal.Default.SMSSubscriptionStateChanged += _smsStateChanged; - } - - /* - * SDK events - */ + public string email; - private void _notificationOpened(NotificationOpenedResult result) { - _log($"Notification was opened with result: {JsonUtility.ToJson(result)}"); - } + /// + /// set to an external user id you would like to test notifications against + /// + public string externalId; + + /// + /// set to an external user id you would like to test notifications against + /// + public string phoneNumber; - private Notification _notificationReceived(Notification notification) { - var additionalData = notification.additionalData != null - ? Json.Serialize(notification.additionalData) + /// + /// set to your app id (https://documentation.onesignal.com/docs/accounts-and-keys) + /// + public string appId; + + /// + /// whether you would prefer OneSignal Unity SDK prevent initialization until consent is granted via + /// in this test MonoBehaviour + /// + public bool requiresUserPrivacyConsent; + + /// + /// + /// + public string tagKey; + + /// + /// + /// + public string tagValue; + + /// + /// + /// + public string triggerKey; + + /// + /// + /// + public string triggerValue; + + /// + /// + /// + public string outcomeKey; + + /// + /// + /// + public float outcomeValue; + + /// + /// 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() { + // Enable lines below to debug issues with OneSignal + OneSignal.Default.LogLevel = LogLevel.Info; + OneSignal.Default.AlertLevel = LogLevel.Fatal; + + // Setting RequiresPrivacyConsent to true will prevent the OneSignalSDK from operating until + // PrivacyConsent is also set to true + OneSignal.Default.RequiresPrivacyConsent = requiresUserPrivacyConsent; + + // Setup the below to listen for and respond to events from notifications + OneSignal.Default.NotificationOpened += _notificationOpened; + OneSignal.Default.NotificationWillShow += _notificationReceived; + + // Setup the below to listen for and respond to events from in app messages + OneSignal.Default.InAppMessageWillDisplay += _iamWillDisplay; + OneSignal.Default.InAppMessageDidDisplay += _iamDidDisplay; + OneSignal.Default.InAppMessageWillDismiss += _iamWillDismiss; + OneSignal.Default.InAppMessageDidDismiss += _iamDidDismiss; + OneSignal.Default.InAppMessageTriggeredAction += _iamTriggeredAction; + + // Setup the below to listen for and respond to state changes + OneSignal.Default.NotificationPermissionChanged += _notificationPermissionChanged; + OneSignal.Default.PushSubscriptionStateChanged += _pushStateChanged; + OneSignal.Default.EmailSubscriptionStateChanged += _emailStateChanged; + OneSignal.Default.SMSSubscriptionStateChanged += _smsStateChanged; + } + + /* + * SDK events + */ + + private void _notificationOpened(NotificationOpenedResult result) { + _log($"Notification was opened with result: {JsonUtility.ToJson(result)}"); + } + + private Notification _notificationReceived(Notification notification) { + var additionalData = notification.additionalData != null + ? Json.Serialize(notification.additionalData) : null; _log($"Notification was received in foreground: {JsonUtility.ToJson(notification)}\n{additionalData}"); return notification; // show the notification } - private void _iamWillDisplay(InAppMessage inAppMessage) { - _log($"IAM will display: {JsonUtility.ToJson(inAppMessage)}"); - } + private void _iamWillDisplay(InAppMessage inAppMessage) { + _log($"IAM will display: {JsonUtility.ToJson(inAppMessage)}"); + } - private void _iamDidDisplay(InAppMessage inAppMessage) { - _log($"IAM did display: {JsonUtility.ToJson(inAppMessage)}"); - } + private void _iamDidDisplay(InAppMessage inAppMessage) { + _log($"IAM did display: {JsonUtility.ToJson(inAppMessage)}"); + } - private void _iamWillDismiss(InAppMessage inAppMessage) { - _log($"IAM will dismiss: {JsonUtility.ToJson(inAppMessage)}"); - } + private void _iamWillDismiss(InAppMessage inAppMessage) { + _log($"IAM will dismiss: {JsonUtility.ToJson(inAppMessage)}"); + } - private void _iamDidDismiss(InAppMessage inAppMessage) { - _log($"IAM did dismiss: {JsonUtility.ToJson(inAppMessage)}"); - } + private void _iamDidDismiss(InAppMessage inAppMessage) { + _log($"IAM did dismiss: {JsonUtility.ToJson(inAppMessage)}"); + } - private void _iamTriggeredAction(InAppMessageAction inAppMessageAction) { - _log($"IAM triggered action: {JsonUtility.ToJson(inAppMessageAction)}"); - } + private void _iamTriggeredAction(InAppMessageAction inAppMessageAction) { + _log($"IAM triggered action: {JsonUtility.ToJson(inAppMessageAction)}"); + } - private void _notificationPermissionChanged(NotificationPermission current, NotificationPermission previous) { - _log($"Notification Permissions changed to: {current}"); - } + private void _notificationPermissionChanged(NotificationPermission current, NotificationPermission previous) { + _log($"Notification Permissions changed to: {current}"); + } - private void _pushStateChanged(PushSubscriptionState current, PushSubscriptionState previous) { - _log($"Push state changed to: {JsonUtility.ToJson(current)}"); - } + private void _pushStateChanged(PushSubscriptionState current, PushSubscriptionState previous) { + _log($"Push state changed to: {JsonUtility.ToJson(current)}"); + } - private void _emailStateChanged(EmailSubscriptionState current, EmailSubscriptionState previous) { - _log($"Email state changed to: {JsonUtility.ToJson(current)}"); - } + private void _emailStateChanged(EmailSubscriptionState current, EmailSubscriptionState previous) { + _log($"Email state changed to: {JsonUtility.ToJson(current)}"); + } - private void _smsStateChanged(SMSSubscriptionState current, SMSSubscriptionState previous) { - _log($"SMS state changed to: {JsonUtility.ToJson(current)}"); - } - - /* - * SDK setup - */ - - public void Initialize() { - _log($"Initializing with appId {appId}"); - OneSignal.Default.Initialize(appId); - } + private void _smsStateChanged(SMSSubscriptionState current, SMSSubscriptionState previous) { + _log($"SMS state changed to: {JsonUtility.ToJson(current)}"); + } - public void ToggleRequiresPrivacyConsent() { - _log($"Toggling RequiresPrivacyConsent to {!OneSignal.Default.RequiresPrivacyConsent}"); - OneSignal.Default.RequiresPrivacyConsent = !OneSignal.Default.RequiresPrivacyConsent; - } + /* + * SDK setup + */ - public void TogglePrivacyConsent() { - _log($"Toggling PrivacyConsent to {!OneSignal.Default.PrivacyConsent}"); - OneSignal.Default.PrivacyConsent = !OneSignal.Default.PrivacyConsent; - } + public void Initialize() { + _log($"Initializing with appId {appId}"); + OneSignal.Default.Initialize(appId); + } - public void SetLogLevel() { - var newLevel = _nextEnum(OneSignal.Default.LogLevel); - _log($"Setting LogLevel to {newLevel}"); - - // LogLevel uses the standard Unity LogType - OneSignal.Default.LogLevel = newLevel; - } + public void ToggleRequiresPrivacyConsent() { + _log($"Toggling RequiresPrivacyConsent to {!OneSignal.Default.RequiresPrivacyConsent}"); + OneSignal.Default.RequiresPrivacyConsent = !OneSignal.Default.RequiresPrivacyConsent; + } - public void SetAlertLevel() { - var newLevel = _nextEnum(OneSignal.Default.AlertLevel); - _log($"Setting AlertLevel to {newLevel}"); - - // AlertLevel uses the standard Unity LogType - OneSignal.Default.AlertLevel = newLevel; - } - - /* - * User identification - */ + public void TogglePrivacyConsent() { + _log($"Toggling PrivacyConsent to {!OneSignal.Default.PrivacyConsent}"); + OneSignal.Default.PrivacyConsent = !OneSignal.Default.PrivacyConsent; + } - public async void SetEmail() { - _log($"Calling SetEmail({email}) and awaiting result..."); - - var result = await OneSignal.Default.SetEmail(email); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + public void SetLogLevel() { + var newLevel = _nextEnum(OneSignal.Default.LogLevel); + _log($"Setting LogLevel to {newLevel}"); - public async void SetExternalId() { - _log($"Calling SetExternalUserId({externalId}) and awaiting result..."); - - var result = await OneSignal.Default.SetExternalUserId(externalId); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + // LogLevel uses the standard Unity LogType + OneSignal.Default.LogLevel = newLevel; + } - public async void SetSMSNumber() { - _log($"Calling SetSMSNumber({phoneNumber}) and awaiting result..."); - - var result = await OneSignal.Default.SetSMSNumber(phoneNumber); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } - - /* - * Push - */ + public void SetAlertLevel() { + var newLevel = _nextEnum(OneSignal.Default.AlertLevel); + _log($"Setting AlertLevel to {newLevel}"); - public async void PromptForPush() { - _log("Calling PromptForPushNotificationsWithUserResponse and awaiting result..."); + // AlertLevel uses the standard Unity LogType + OneSignal.Default.AlertLevel = newLevel; + } - var result = await OneSignal.Default.PromptForPushNotificationsWithUserResponse(); + /* + * User identification + */ - _log($"Prompt completed with {result}"); - } + public async void SetEmail() { + _log($"Calling SetEmail({email}) and awaiting result..."); - public void ClearPush() { - _log("Clearing existing OneSignal push notifications..."); - OneSignal.Default.ClearOneSignalNotifications(); - } + var result = await OneSignal.Default.SetEmail(email); - public async void SendPushToSelf() { - _log("Sending push notification to this device via PostNotification..."); - - // Check out our API docs at https://documentation.onesignal.com/reference/create-notification - // for a full list of possibilities for notification options. - var pushOptions = new Dictionary { - ["contents"] = new Dictionary { - ["en"] = "Test Message" - }, + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } - // Send notification to this user - ["include_external_user_ids"] = new List { externalId }, + public async void SetExternalId() { + _log($"Calling SetExternalUserId({externalId}) and awaiting result..."); - // Example of scheduling a notification in the future - ["send_after"] = DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U") - }; + var result = await OneSignal.Default.SetExternalUserId(externalId); - var result = await OneSignal.Default.PostNotification(pushOptions); - - if (Json.Serialize(result) is string resultString) - _log($"Notification sent with result {resultString}"); - else - _error("Could not serialize result of PostNotification"); - } - - /* - * In App Messages - */ - - public void SetTrigger() { - _log($"Setting trigger with key {triggerKey} and value {triggerValue}"); - OneSignal.Default.SetTrigger(triggerKey, triggerValue); - } + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } - public void GetTrigger() { - _log($"Getting trigger for key {triggerKey}"); - var value = OneSignal.Default.GetTrigger(triggerKey); - _log($"Trigger for key {triggerKey} is of value {value}"); - } + public async void SetSMSNumber() { + _log($"Calling SetSMSNumber({phoneNumber}) and awaiting result..."); - public void RemoveTrigger() { - _log($"Removing trigger for key {triggerKey}"); - OneSignal.Default.RemoveTrigger(triggerKey); - } + var result = await OneSignal.Default.SetSMSNumber(phoneNumber); - public void GetTriggers() { - _log("Getting all trigger keys and values"); - var triggers = OneSignal.Default.GetTriggers(); - - if (Json.Serialize(triggers) is string triggersString) - _log($"Current triggers are {triggersString}"); - else - _error("Could not serialize triggers"); - } - - public void ToggleInAppMessagesArePaused() { - _log($"Toggling InAppMessagesArePaused to {!OneSignal.Default.InAppMessagesArePaused}"); - OneSignal.Default.InAppMessagesArePaused = !OneSignal.Default.InAppMessagesArePaused; - } - - /* - * Tags - */ + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } - public async void SetTag() { - _log($"Setting tag with key {tagKey} and value {tagValue} and awaiting result..."); + /* + * Push + */ - var result = await OneSignal.Default.SendTag(tagKey, tagValue); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + public async void PromptForPush() { + _log("Calling PromptForPushNotificationsWithUserResponse and awaiting result..."); - public async void RemoveTag() { - _log($"Removing tag for key {triggerKey} and awaiting result..."); + var result = await OneSignal.Default.PromptForPushNotificationsWithUserResponse(); - var result = await OneSignal.Default.DeleteTag(tagKey); - - if (result) - _log("Remove succeeded"); - else - _error("Remove failed"); - } + _log($"Prompt completed with {result}"); + } - public async void GetTags() { - _log("Requesting all tag keys and values for this user..."); - var tags = await OneSignal.Default.GetTags(); - - if (Json.Serialize(tags) is string tagsString) - _log($"Current tags are {tagsString}"); - else - _error("Could not serialize tags"); - } - - /* - * Outcomes - */ + public void ClearPush() { + _log("Clearing existing OneSignal push notifications..."); + OneSignal.Default.ClearOneSignalNotifications(); + } - public async void SetOutcome() { - _log($"Setting outcome with key {outcomeKey} and awaiting result..."); + public async void SendPushToSelf() { + _log("Sending push notification to this device via PostNotification..."); - var result = await OneSignal.Default.SendOutcome(outcomeKey); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + // Check out our API docs at https://documentation.onesignal.com/reference/create-notification + // for a full list of possibilities for notification options. + var pushOptions = new Dictionary { + ["contents"] = new Dictionary { + ["en"] = "Test Message" + }, - public async void SetUniqueOutcome() { - _log($"Setting unique outcome with key {outcomeKey} and awaiting result..."); + // Send notification to this user + ["include_external_user_ids"] = new List { externalId }, - var result = await OneSignal.Default.SendUniqueOutcome(outcomeKey); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + // Example of scheduling a notification in the future + ["send_after"] = DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U") + }; - public async void SetOutcomeWithValue() { - _log($"Setting outcome with key {outcomeKey} and value {outcomeValue} and awaiting result..."); + var result = await OneSignal.Default.PostNotification(pushOptions); - var result = await OneSignal.Default.SendOutcomeWithValue(outcomeKey, outcomeValue); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } - - /* - * Location - */ - - public void PromptLocation() { - _log("Opening prompt to ask for user consent to access location"); - OneSignal.Default.PromptLocation(); - } - - public void ToggleShareLocation() { - _log($"Toggling ShareLocation to {!OneSignal.Default.ShareLocation}"); - OneSignal.Default.ShareLocation = !OneSignal.Default.ShareLocation; - } + if (Json.Serialize(result) is string resultString) + _log($"Notification sent with result {resultString}"); + else + _error("Could not serialize result of PostNotification"); + } - #region Rendering - /* - * You can safely ignore everything in this region and below - */ - - public Text console; - - 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 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); - - private void Awake() { - SDKDebug.LogIntercept += _log; - SDKDebug.WarnIntercept += _warn; - SDKDebug.ErrorIntercept += _error; - } + /* + * In App Messages + */ - private void _log(object message) { - Debug.Log(message); - console.text += $"\nI> {message}"; - } + public void SetTrigger() { + _log($"Setting trigger with key {triggerKey} and value {triggerValue}"); + OneSignal.Default.SetTrigger(triggerKey, triggerValue); + } - private void _warn(object message) { - Debug.LogWarning(message); - console.text += $"\nW> {message}"; - } + public void GetTrigger() { + _log($"Getting trigger for key {triggerKey}"); + var value = OneSignal.Default.GetTrigger(triggerKey); + _log($"Trigger for key {triggerKey} is of value {value}"); + } - private void _error(object message) { - Debug.LogError(message); - console.text += $"\nE> {message}"; - } - #endregion - - #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 + public void RemoveTrigger() { + _log($"Removing trigger for key {triggerKey}"); + OneSignal.Default.RemoveTrigger(triggerKey); + } + + public void GetTriggers() { + _log("Getting all trigger keys and values"); + var triggers = OneSignal.Default.GetTriggers(); + + if (Json.Serialize(triggers) is string triggersString) + _log($"Current triggers are {triggersString}"); + else + _error("Could not serialize triggers"); + } + + public void ToggleInAppMessagesArePaused() { + _log($"Toggling InAppMessagesArePaused to {!OneSignal.Default.InAppMessagesArePaused}"); + OneSignal.Default.InAppMessagesArePaused = !OneSignal.Default.InAppMessagesArePaused; + } + + /* + * Tags + */ + + public async void SetTag() { + _log($"Setting tag with key {tagKey} and value {tagValue} and awaiting result..."); + + var result = await OneSignal.Default.SendTag(tagKey, tagValue); + + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } + + public async void RemoveTag() { + _log($"Removing tag for key {triggerKey} and awaiting result..."); + + var result = await OneSignal.Default.DeleteTag(tagKey); + + if (result) + _log("Remove succeeded"); + else + _error("Remove failed"); + } + + public async void GetTags() { + _log("Requesting all tag keys and values for this user..."); + var tags = await OneSignal.Default.GetTags(); + + if (Json.Serialize(tags) is string tagsString) + _log($"Current tags are {tagsString}"); + else + _error("Could not serialize tags"); + } + + /* + * Outcomes + */ + + public async void SetOutcome() { + _log($"Setting outcome with key {outcomeKey} and awaiting result..."); + + var result = await OneSignal.Default.SendOutcome(outcomeKey); + + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } + + public async void SetUniqueOutcome() { + _log($"Setting unique outcome with key {outcomeKey} and awaiting result..."); + + var result = await OneSignal.Default.SendUniqueOutcome(outcomeKey); + + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } + + public async void SetOutcomeWithValue() { + _log($"Setting outcome with key {outcomeKey} and value {outcomeValue} and awaiting result..."); + + var result = await OneSignal.Default.SendOutcomeWithValue(outcomeKey, outcomeValue); + + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } + + /* + * Location + */ + + public void PromptLocation() { + _log("Opening prompt to ask for user consent to access location"); + OneSignal.Default.PromptLocation(); + } + + public void ToggleShareLocation() { + _log($"Toggling ShareLocation to {!OneSignal.Default.ShareLocation}"); + OneSignal.Default.ShareLocation = !OneSignal.Default.ShareLocation; + } + +#region Rendering + /* + * You can safely ignore everything in this region and below + */ + + public Text console; + + 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 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); + + private void Awake() { + SDKDebug.LogIntercept += _log; + SDKDebug.WarnIntercept += _warn; + SDKDebug.ErrorIntercept += _error; + } + + private void _log(object message) { + Debug.Log(message); + console.text += $"\nI> {message}"; + } + + private void _warn(object message) { + Debug.LogWarning(message); + console.text += $"\nW> {message}"; + } + + private void _error(object message) { + Debug.LogError(message); + console.text += $"\nE> {message}"; + } +#endregion + +#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 } #endif \ No newline at end of file diff --git a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalFileInventoryGenerator.cs b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalFileInventoryGenerator.cs index e0f9711f8..49343abdb 100644 --- a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalFileInventoryGenerator.cs +++ b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalFileInventoryGenerator.cs @@ -1,23 +1,49 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System.IO; -using System.Linq; using UnityEditor; using UnityEngine; -/// -/// Creates the resource to be distributed with the SDK *.unitypackage -/// -public static class OneSignalFileInventoryGenerator -{ +namespace OneSignalSDK { /// - /// Run from the internal OneSignal menu or cmdline to create a inventory resource to distribute + /// Creates the resource to be distributed with the SDK *.unitypackage /// - [MenuItem("OneSignal/Generate File Inventory", false, 100)] - public static void GenerateInventory() - { - var inventory = ScriptableObject.CreateInstance(); - inventory.DistributedPaths = OneSignalFileInventory.GetCurrentPaths(); - - Directory.CreateDirectory(OneSignalFileInventory.EditorResourcesPath); - AssetDatabase.CreateAsset(inventory, OneSignalFileInventory.AssetPath); + 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() { + var inventory = ScriptableObject.CreateInstance(); + inventory.DistributedPaths = OneSignalFileInventory.GetCurrentPaths(); + + Directory.CreateDirectory(OneSignalFileInventory.EditorResourcesPath); + 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 d9f1ca5b3..dfdead93b 100644 --- a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalPackagePublisher.cs +++ b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalPackagePublisher.cs @@ -1,46 +1,75 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System.IO; using System.Linq; using UnityEditor; -/// -/// Creates a unitypackage file for publishing -/// -public static class OneSignalPackagePublisher { - public static void UpdateProjectVersion() { - var packageVersion = File.ReadAllText(VersionFilePath); - PlayerSettings.bundleVersion = packageVersion; - } - - [MenuItem("OneSignal/ExportUnityPackage")] - public static void ExportUnityPackage() { - AssetDatabase.Refresh(); - var packageVersion = File.ReadAllText(VersionFilePath); - var packageName = $"OneSignal-v{packageVersion}.unitypackage"; - - AssetDatabase.ExportPackage( - _filePaths(), - packageName, - ExportPackageOptions.Recurse | ExportPackageOptions.IncludeDependencies - ); - } +namespace OneSignalSDK { + /// + /// Creates a unitypackage file for publishing + /// + public static class OneSignalPackagePublisher { + public static void UpdateProjectVersion() { + var packageVersion = File.ReadAllText(VersionFilePath); + PlayerSettings.bundleVersion = packageVersion; + } + + [MenuItem("OneSignal/ExportUnityPackage")] + public static void ExportUnityPackage() { + AssetDatabase.Refresh(); + var packageVersion = File.ReadAllText(VersionFilePath); + var packageName = $"OneSignal-v{packageVersion}.unitypackage"; + + AssetDatabase.ExportPackage( + _filePaths(), + packageName, + ExportPackageOptions.Recurse | ExportPackageOptions.IncludeDependencies + ); + } + + private static readonly string PackagePath = Path.Combine("Assets", "OneSignal"); + private static readonly string VersionFilePath = Path.Combine(PackagePath, "VERSION"); - private static readonly string PackagePath = Path.Combine("Assets", "OneSignal"); - private static readonly string VersionFilePath = Path.Combine(PackagePath, "VERSION"); - - private static readonly string[] Exclusions = { - Path.Combine(PackagePath, "Attribution"), - ".DS_Store" - }; + private static readonly string[] Exclusions = { + Path.Combine(PackagePath, "Attribution"), + ".DS_Store" + }; - private static string[] _filePaths() { - var files = Directory.GetFileSystemEntries(PackagePath); - var pathsToInclude = files.Where(file => { - if (file.EndsWith(".meta")) - file = file.Substring(0, file.Length - 5); + private static string[] _filePaths() { + var files = Directory.GetFileSystemEntries(PackagePath); + var pathsToInclude = files.Where(file => { + if (file.EndsWith(".meta")) + file = file.Substring(0, file.Length - 5); - return !Exclusions.Contains(file); - }); + return !Exclusions.Contains(file); + }); - return pathsToInclude.ToArray(); + 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 1261ce368..11755a2dd 100644 --- a/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalSetupReset.cs +++ b/OneSignalExample/Assets/OneSignalPackager/Editor/OneSignalSetupReset.cs @@ -1,55 +1,82 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System.IO; using UnityEditor; -/// -/// For debugging all of the OneSignalSetupSteps -/// -public static class OneSignalSetupReset -{ +namespace OneSignalSDK { /// - /// Resets all setup steps + /// For debugging all of the OneSignalSetupSteps /// - [MenuItem("OneSignal/Reset All Setup Steps", false, 100)] - public static void ResetAllSteps() - { - /* - * ExportAndroidResourcesStep - * deletes the OneSignalConfig.plugin directory - */ - AssetDatabase.DeleteAsset(Path.Combine("Assets", "Plugins", "Android", "OneSignalConfig.plugin")); + public static class OneSignalSetupReset { + /// + /// Resets all setup steps + /// + [MenuItem("OneSignal/Reset All Setup Steps", false, 100)] + public static void ResetAllSteps() { + /* + * ExportAndroidResourcesStep + * deletes the OneSignalConfig.plugin directory + */ + AssetDatabase.DeleteAsset(Path.Combine("Assets", "Plugins", "Android", "OneSignalConfig.plugin")); + + /* + * InstallEdm4UStep + * deletes the edm4u directory + */ + AssetDatabase.DeleteAsset(Path.Combine("Assets", "ExternalDependencyManager")); - /* - * InstallEdm4UStep - * deletes the edm4u directory - */ - AssetDatabase.DeleteAsset(Path.Combine("Assets", "ExternalDependencyManager")); + /* + * SetupManifestStep + * handled by ExportAndroidResourcesStep + */ + // do nothing - /* - * SetupManifestStep - * handled by ExportAndroidResourcesStep - */ - // do nothing + /* + * CleanUpLegacyStep + * adds a random file to the Assets/OneSignal folder + */ + File.Create(Path.Combine("Assets", "OneSignal", "tempfile")); - /* - * CleanUpLegacyStep - * adds a random file to the Assets/OneSignal folder - */ - File.Create(Path.Combine("Assets", "OneSignal", "tempfile")); + /* + * ImportPackagesStep + * removes packages from manifest + */ + var manifest = new Manifest(); + manifest.Fetch(); + manifest.RemoveDependency("com.onesignal.unity.core"); + manifest.RemoveDependency("com.onesignal.unity.android"); + manifest.RemoveDependency("com.onesignal.unity.ios"); + manifest.RemoveScopeRegistry("https://registry.npmjs.org"); + manifest.ApplyChanges(); - /* - * ImportPackagesStep - * removes packages from manifest - */ - var manifest = new Manifest(); - manifest.Fetch(); - manifest.RemoveDependency("com.onesignal.unity.core"); - manifest.RemoveDependency("com.onesignal.unity.android"); - manifest.RemoveDependency("com.onesignal.unity.ios"); - manifest.RemoveScopeRegistry("https://registry.npmjs.org"); - manifest.ApplyChanges(); - -#if UNITY_2020_1_OR_NEWER - UnityEditor.PackageManager.Client.Resolve(); -#endif + #if UNITY_2020_1_OR_NEWER + UnityEditor.PackageManager.Client.Resolve(); + #endif + } } } \ No newline at end of file diff --git a/buildpackage.sh b/buildpackage.sh deleted file mode 100755 index 52b03554c..000000000 --- a/buildpackage.sh +++ /dev/null @@ -1,96 +0,0 @@ -#! /bin/sh - -#let users pass in the final filename for the .unitypackage if they wish -if [ $# -eq 0 ] - then - package_name=OneSignalSDK.unitypackage -else - package_name=$1 -fi - -#paths -project_path=$(pwd)/OneSignalExample -log_file=$(pwd)/build.log -generated_path=$project_path/$package_name -final_path=$(pwd)/$package_name -temp_location=$(pwd)/onesignal_temp -icons_location=$project_path/Assets/AppIcons -icons_temp_location=$(pwd)/onesignal_temp/tempAppIcons -android_location=$project_path/Assets/Plugins/Android -config_location=$android_location/OneSignalConfig.plugin -package_manifest=$project_path/Packages/manifest.json -temp_package_manifest=$temp_location/Packages/manifest.json - -mkdir -p $temp_location - -# Removed generated Android manifest files -rm $config_location/AndroidManifest.xml 2> /dev/null -rm $config_location/AndroidManifest.xml.meta 2> /dev/null - -# temp move out Packages/manifest.json -# This prevents possible crashes due to old versions in this manifest -mkdir -p $temp_location/Packages/ -mv $package_manifest $temp_package_manifest - -#temporarily remove Android AppIcons -mv $icons_location $icons_temp_location -mv $icons_location.meta $icons_temp_location.meta - -## START - Clean Android files -# This removes any .aar files we don't want to bundle in our package - -# temporarily move some necessary files -mv $config_location $temp_location/OneSignalConfig.plugin -mv $config_location.meta $temp_location/OneSignalConfig.plugin.meta - -# get rid of a bunch of unnecessary files -rm -r $android_location -mkdir $android_location - -# put the config files back -mv $temp_location/OneSignalConfig.plugin $config_location -mv $temp_location/OneSignalConfig.plugin.meta $config_location.meta - -## END - Clean Android files - -# Create the .unitypackage -echo "Creating unitypackage." -# Setting standalone keeps AndroidManifest.xml from being regenerated -# buildTarget must be before exportPackage for this to work -/Applications/Unity/Hub/Editor/2019.2.14f1/Unity.app/Contents/MacOS/Unity \ - -batchMode \ - -buildTarget standalone \ - -projectPath $project_path \ - -exportPackage Assets $package_name \ - -logFile $log_file \ - -nographics \ - -quit - -if [ $? = 0 ] ; then - echo "Created package successfully." - error_code=0 -else - echo "Creating package failed. Exited with $?." - error_code=1 -fi - -#the .unitypackage file is created in the OneSignalExample directory -#move it to the root of the repo -mv $generated_path $final_path - -# move back Packages/manifest.json -mv $temp_package_manifest $package_manifest - -#move the icons back to their original location -mv $icons_temp_location $icons_location -mv $icons_temp_location.meta $icons_location.meta - -#delete the temp folder -rm -r $temp_location - -echo 'Build logs location:' -echo $log_file - -echo "Finished with code $error_code" - -exit $error_code diff --git a/com.onesignal.unity.android/Editor/SetupSteps/ExportAndroidResourcesStep.cs b/com.onesignal.unity.android/Editor/SetupSteps/ExportAndroidResourcesStep.cs index 7a17fb6b3..6002ef89c 100644 --- a/com.onesignal.unity.android/Editor/SetupSteps/ExportAndroidResourcesStep.cs +++ b/com.onesignal.unity.android/Editor/SetupSteps/ExportAndroidResourcesStep.cs @@ -1,68 +1,94 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System; using System.IO; using System.Linq; using UnityEditor; -/// -/// Copies the OneSignalConfig.plugin to Assets/Plugins/Android/* -/// -public sealed class ExportAndroidResourcesStep : OneSignalSetupStep -{ - public override string Summary - => "Copy Android plugin to Assets"; - - public override string Details - => $"Will create a plugin directory of {_pluginExportPath} filled with files necessary for the OneSignal SDK " + - "to operate on Android."; - - public override bool IsRequired - => true; - - protected override bool _getIsStepCompleted() - { - if (!Directory.Exists(_pluginExportPath)) - return false; - - var packagePaths = Directory.GetFiles(_pluginPackagePath, "*", 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); - return !fileDiff.Any(); - } +namespace OneSignalSDK { + /// + /// Copies the OneSignalConfig.plugin to Assets/Plugins/Android/* + /// + public sealed class ExportAndroidResourcesStep : OneSignalSetupStep { + public override string Summary + => "Copy Android plugin to Assets"; + + public override string Details + => $"Will create a plugin directory of {_pluginExportPath} filled with files necessary for the OneSignal SDK " + + "to operate on Android."; - protected override void _runStep() - { - var files = Directory.GetFiles(_pluginPackagePath, "*", SearchOption.AllDirectories); - var filteredFiles = files.Where(file => !file.EndsWith(".meta")); + public override bool IsRequired + => true; - 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)); + protected override bool _getIsStepCompleted() { + if (!Directory.Exists(_pluginExportPath)) + return false; - /* - * Export the file. - * By default the CreateDirectory and Copy methods don't overwrite but we use the Exists - * checks to avoid polluting the console with warnings. - */ + var packagePaths = Directory.GetFiles(_pluginPackagePath, "*", SearchOption.AllDirectories) + .Select(path => path.Remove(0, path.LastIndexOf(_pluginName, StringComparison.InvariantCulture))); - if (!Directory.Exists(containingPath)) - Directory.CreateDirectory(containingPath); + var exportPaths = Directory.GetFiles(_pluginExportPath, "*", SearchOption.AllDirectories) + .Select(path => path.Remove(0, path.LastIndexOf(_pluginName, StringComparison.InvariantCulture))); - if (!File.Exists(fileExportPath)) - File.Copy(file, fileExportPath); + var fileDiff = packagePaths.Except(exportPaths); + + return !fileDiff.Any(); } - AssetDatabase.Refresh(); - } + protected override void _runStep() { + 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); + var fileExportPath = Path.Combine(_pluginExportPath, trimmedPath); + var containingPath = fileExportPath.Remove(fileExportPath.LastIndexOf(Path.DirectorySeparatorChar)); - private const string _pluginName = "OneSignalConfig.plugin"; - private static readonly string _packagePath = Path.Combine("Packages", "com.onesignal.unity.android", "Editor"); - private static readonly string _androidPluginsPath = Path.Combine("Assets", "Plugins", "Android"); - private static readonly string _pluginPackagePath = Path.Combine(_packagePath, _pluginName); - private static readonly string _pluginExportPath = Path.Combine(_androidPluginsPath, _pluginName); + /* + * Export the file. + * By default the CreateDirectory and Copy methods don't overwrite but we use the Exists + * checks to avoid polluting the console with warnings. + */ + + if (!Directory.Exists(containingPath)) + Directory.CreateDirectory(containingPath); + + if (!File.Exists(fileExportPath)) + File.Copy(file, fileExportPath); + } + + AssetDatabase.Refresh(); + } + + private const string _pluginName = "OneSignalConfig.plugin"; + private static readonly string _packagePath = Path.Combine("Packages", "com.onesignal.unity.android", "Editor"); + private static readonly string _androidPluginsPath = Path.Combine("Assets", "Plugins", "Android"); + private static readonly string _pluginPackagePath = Path.Combine(_packagePath, _pluginName); + private static readonly string _pluginExportPath = Path.Combine(_androidPluginsPath, _pluginName); + } } \ No newline at end of file diff --git a/com.onesignal.unity.android/Editor/SetupSteps/InstallEdm4uStep.cs b/com.onesignal.unity.android/Editor/SetupSteps/InstallEdm4uStep.cs index c6c2f250e..d0c745d2c 100644 --- a/com.onesignal.unity.android/Editor/SetupSteps/InstallEdm4uStep.cs +++ b/com.onesignal.unity.android/Editor/SetupSteps/InstallEdm4uStep.cs @@ -1,33 +1,63 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System.Linq; using UnityEditor.Compilation; -/// -/// 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 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; - - protected override bool _getIsStepCompleted() - => CompilationPipeline.GetPrecompiledAssemblyNames() - .Any(assemblyName => assemblyName.StartsWith("Google.VersionHandler")); - - protected override void _runStep() { - const string msg = "Downloading Google External Dependency Manager"; - UnityPackageInstaller.DownloadAndInstall(_edm4UPackageDownloadUrl, msg, result => { - if (result) - _shouldCheckForCompletion = true; - }); - } +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 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; - private const string _edm4UVersion = "1.2.167"; - private static readonly string _edm4UPackageDownloadUrl - = $"https://github.com/googlesamples/unity-jar-resolver/blob/v{_edm4UVersion}/external-dependency-manager-{_edm4UVersion}.unitypackage?raw=true"; + protected override bool _getIsStepCompleted() + => CompilationPipeline.GetPrecompiledAssemblyNames() + .Any(assemblyName => assemblyName.StartsWith("Google.VersionHandler")); + + protected override void _runStep() { + const string msg = "Downloading Google External Dependency Manager"; + UnityPackageInstaller.DownloadAndInstall(_edm4UPackageDownloadUrl, msg, result => { + if (result) + _shouldCheckForCompletion = true; + }); + } + + private const string _edm4UVersion = "1.2.167"; + + 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.android/Editor/SetupSteps/SetupManifestStep.cs b/com.onesignal.unity.android/Editor/SetupSteps/SetupManifestStep.cs index 6ac82232e..5998b8f5d 100644 --- a/com.onesignal.unity.android/Editor/SetupSteps/SetupManifestStep.cs +++ b/com.onesignal.unity.android/Editor/SetupSteps/SetupManifestStep.cs @@ -1,3 +1,30 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System; using System.Collections.Generic; using System.IO; @@ -7,81 +34,83 @@ using UnityEditor.Compilation; using UnityEngine; -/// -/// Makes sure that the OneSignalConfig.plugin folder exists and is populated with the correct files within the project -/// -public class SetupManifestStep : OneSignalSetupStep -{ - public override string Summary - => "Setup keys in Android manifest"; - - public override string Details - => $"Adds the {PlayerSettings.applicationIdentifier} applicationIdentifier to the {_manifestPath}." + - $"If you intend to change this id then please re-run this step"; - - public override bool IsRequired - => true; - - protected override bool _getIsStepCompleted() - { - if (!File.Exists(_manifestPath)) - return false; - - var reader = new StreamReader(_manifestPath); - var contents = reader.ReadToEnd(); - reader.Close(); - - var matches = Regex.Matches(contents, _manifestRegex); - foreach (var match in matches) { - if (match.ToString() != PlayerSettings.applicationIdentifier) - return false; - } - - return true; - } +namespace OneSignalSDK { + /// + /// Makes sure that the OneSignalConfig.plugin folder exists and is populated with the correct files within the project + /// + public class SetupManifestStep : OneSignalSetupStep { + public override string Summary + => "Setup keys in Android manifest"; - protected override void _runStep() - { - var replacements = new Dictionary - { - [_manifestRegex] = PlayerSettings.applicationIdentifier - }; + public override string Details + => $"Adds the {PlayerSettings.applicationIdentifier} applicationIdentifier to the {_manifestPath}." + + $"If you intend to change this id then please re-run this step"; - // modifies the manifest in place - _replaceStringsInFile(_manifestPath, _manifestPath, replacements); - } - - private const string _pluginName = "OneSignalConfig.plugin"; - private static readonly string _androidPluginsPath = Path.Combine("Assets", "Plugins", "Android"); - private static readonly string _manifestPath = Path.Combine(_androidPluginsPath, _pluginName, "AndroidManifest.xml"); - - private const string _manifestRegex = @"((?<=)|(?<=)|(?<=))"; - - private static void _replaceStringsInFile(string sourcePath, string destinationPath, - IReadOnlyDictionary replacements) - { - try - { - if (!File.Exists(sourcePath)) - { - Debug.LogError($"could not find {sourcePath}"); - return; - } + public override bool IsRequired + => true; - var reader = new StreamReader(sourcePath); + protected override bool _getIsStepCompleted() { + if (!File.Exists(_manifestPath)) + return false; + + var reader = new StreamReader(_manifestPath); var contents = reader.ReadToEnd(); reader.Close(); - foreach (var replacement in replacements) - contents = Regex.Replace(contents, replacement.Key, replacement.Value); + var matches = Regex.Matches(contents, _manifestRegex); + + foreach (var match in matches) { + if (match.ToString() != PlayerSettings.applicationIdentifier) + return false; + } - var writer = new StreamWriter(destinationPath); - writer.Write(contents); - writer.Close(); + return true; } - catch (Exception exception) - { - Debug.LogError($"could not replace strings of {sourcePath} because:\n{exception.Message}"); + + protected override void _runStep() { + var replacements = new Dictionary { + [_manifestRegex] = PlayerSettings.applicationIdentifier + }; + + // modifies the manifest in place + _replaceStringsInFile(_manifestPath, _manifestPath, replacements); + } + + private const string _pluginName = "OneSignalConfig.plugin"; + private static readonly string _androidPluginsPath = Path.Combine("Assets", "Plugins", "Android"); + + private static readonly string _manifestPath + = Path.Combine(_androidPluginsPath, _pluginName, "AndroidManifest.xml"); + + private const string _manifestRegex + = @"((?<=)|(?<=)|(?<=))"; + + private static void _replaceStringsInFile( + string sourcePath, + string destinationPath, + IReadOnlyDictionary replacements + ) { + try { + if (!File.Exists(sourcePath)) { + Debug.LogError($"could not find {sourcePath}"); + + return; + } + + var reader = new StreamReader(sourcePath); + var contents = reader.ReadToEnd(); + reader.Close(); + + foreach (var replacement in replacements) + contents = Regex.Replace(contents, replacement.Key, replacement.Value); + + var writer = new StreamWriter(destinationPath); + writer.Write(contents); + writer.Close(); + } + catch (Exception exception) { + Debug.LogError($"could not replace strings of {sourcePath} because:\n{exception.Message}"); + } } } } \ 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 dc58ffbe7..8e2ac3e05 100644 --- a/com.onesignal.unity.android/Runtime/AssemblyInfo.cs +++ b/com.onesignal.unity.android/Runtime/AssemblyInfo.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.android/Runtime/OneSignalAndroid.Callbacks.cs b/com.onesignal.unity.android/Runtime/OneSignalAndroid.Callbacks.cs index 283c74654..0991f22a0 100755 --- a/com.onesignal.unity.android/Runtime/OneSignalAndroid.Callbacks.cs +++ b/com.onesignal.unity.android/Runtime/OneSignalAndroid.Callbacks.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -28,7 +28,6 @@ using System.Collections.Generic; using Laters; using UnityEngine; -using UnityEngine.Scripting; // ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Local @@ -50,15 +49,15 @@ public sealed partial class OneSignalAndroid : OneSignal { private abstract class OneSignalAndroidJavaProxy : AndroidJavaProxy { protected OneSignalAndroidJavaProxy(string listenerClassName, bool innerClass = false) - : base(innerClass - ? QualifiedSDKClass + "$" + listenerClassName + : base(innerClass + ? QualifiedSDKClass + "$" + listenerClassName : SDKPackage + "." + listenerClassName ) { } } private abstract class OneSignalAwaitableAndroidJavaProxy : AwaitableAndroidJavaProxy { protected OneSignalAwaitableAndroidJavaProxy(string listenerClassName) - : base(QualifiedSDKClass + "$" + listenerClassName ) { } // all inner class + : base(QualifiedSDKClass + "$" + listenerClassName) { } // all inner class } /* @@ -76,17 +75,17 @@ public OneSignalAndroid() { _instance = this; } - + private sealed class OSPermissionObserver : OneSignalAndroidJavaProxy { public OSPermissionObserver() : base("OSPermissionObserver") { } /// OSPermissionStateChanges public void onOSPermissionChanged(AndroidJavaObject stateChanges) { - var currJO = stateChanges.Call("getTo"); - var prevJO = stateChanges.Call("getFrom"); - var curr = _stateNotificationPermission(currJO); - var prev = _stateNotificationPermission(prevJO); - + var currJO = stateChanges.Call("getTo"); + var prevJO = stateChanges.Call("getFrom"); + var curr = _stateNotificationPermission(currJO); + var prev = _stateNotificationPermission(prevJO); + _instance.NotificationPermissionChanged?.Invoke(curr, prev); } } @@ -140,9 +139,9 @@ public void notificationWillShowInForeground(AndroidJavaObject notificationRecei var dataJsonStr = dataJson.Call("toString"); notification.additionalData = Json.Deserialize(dataJsonStr) as Dictionary; } - - var resultNotif = _instance.NotificationWillShow(notification); - + + var resultNotif = _instance.NotificationWillShow(notification); + notificationReceivedEvent.Call("complete", resultNotif != null ? notifJO : null); } } @@ -154,22 +153,22 @@ public OSNotificationOpenedHandler() : base("OSNotificationOpenedHandler", true) public void notificationOpened(AndroidJavaObject result) => _instance.NotificationOpened?.Invoke(result.ToSerializable()); } - + private sealed class OSInAppMessageLifecycleHandler : OneSignalAndroidJavaProxy { public OSInAppMessageLifecycleHandler() : base(IAMLifecycleClassName + "$WrapperLifecycleHandler") { } - + /// OSInAppMessage public void onWillDisplayInAppMessage(AndroidJavaObject message) => _instance.InAppMessageWillDisplay?.Invoke(message.ToSerializable()); - + /// OSInAppMessage public void onDidDisplayInAppMessage(AndroidJavaObject message) => _instance.InAppMessageDidDisplay?.Invoke(message.ToSerializable()); - + /// OSInAppMessage public void onWillDismissInAppMessage(AndroidJavaObject message) => _instance.InAppMessageWillDismiss?.Invoke(message.ToSerializable()); - + /// OSInAppMessage public void onDidDismissInAppMessage(AndroidJavaObject message) => _instance.InAppMessageDidDismiss?.Invoke(message.ToSerializable()); diff --git a/com.onesignal.unity.android/Runtime/OneSignalAndroid.Mappings.cs b/com.onesignal.unity.android/Runtime/OneSignalAndroid.Mappings.cs index d68bcb94b..08f69e89b 100755 --- a/com.onesignal.unity.android/Runtime/OneSignalAndroid.Mappings.cs +++ b/com.onesignal.unity.android/Runtime/OneSignalAndroid.Mappings.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.android/Runtime/OneSignalAndroid.cs b/com.onesignal.unity.android/Runtime/OneSignalAndroid.cs index c37e36fab..2295d77ce 100755 --- a/com.onesignal.unity.android/Runtime/OneSignalAndroid.cs +++ b/com.onesignal.unity.android/Runtime/OneSignalAndroid.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.android/Runtime/OneSignalAndroidInit.cs b/com.onesignal.unity.android/Runtime/OneSignalAndroidInit.cs index f59466b34..6fc747655 100755 --- a/com.onesignal.unity.android/Runtime/OneSignalAndroidInit.cs +++ b/com.onesignal.unity.android/Runtime/OneSignalAndroidInit.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.android/Runtime/Plugins/Android/UnityIAMLifecycleHandler.java b/com.onesignal.unity.android/Runtime/Plugins/Android/UnityIAMLifecycleHandler.java index 96fa6d477..492733ddf 100644 --- a/com.onesignal.unity.android/Runtime/Plugins/Android/UnityIAMLifecycleHandler.java +++ b/com.onesignal.unity.android/Runtime/Plugins/Android/UnityIAMLifecycleHandler.java @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaObjectExtensions.cs b/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaObjectExtensions.cs index accda5e9d..9f7f9c7ba 100644 --- a/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaObjectExtensions.cs +++ b/com.onesignal.unity.android/Runtime/Utilities/AndroidJavaObjectExtensions.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Editor/AssemblyInfo.cs b/com.onesignal.unity.core/Editor/AssemblyInfo.cs index db2bf9d37..8c874e993 100644 --- a/com.onesignal.unity.core/Editor/AssemblyInfo.cs +++ b/com.onesignal.unity.core/Editor/AssemblyInfo.cs @@ -1,3 +1,30 @@ -using System.Runtime.CompilerServices; +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("OneSignal.Android.Editor")] diff --git a/com.onesignal.unity.core/Editor/Platform/OneSignalNative.cs b/com.onesignal.unity.core/Editor/Platform/OneSignalNative.cs index 0cefdef8c..b58b1d2d6 100755 --- a/com.onesignal.unity.core/Editor/Platform/OneSignalNative.cs +++ b/com.onesignal.unity.core/Editor/Platform/OneSignalNative.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Editor/Platform/OneSignalNativeInit.cs b/com.onesignal.unity.core/Editor/Platform/OneSignalNativeInit.cs index 6186e48a5..0e80222b7 100755 --- a/com.onesignal.unity.core/Editor/Platform/OneSignalNativeInit.cs +++ b/com.onesignal.unity.core/Editor/Platform/OneSignalNativeInit.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Editor/Setup/OneSignalSetupStep.cs b/com.onesignal.unity.core/Editor/Setup/OneSignalSetupStep.cs index 5f460326f..2533cd1d8 100644 --- a/com.onesignal.unity.core/Editor/Setup/OneSignalSetupStep.cs +++ b/com.onesignal.unity.core/Editor/Setup/OneSignalSetupStep.cs @@ -1,57 +1,83 @@ -/// -/// Abstract class which must be inherited from in order to create a new setup step -/// -public abstract class OneSignalSetupStep -{ - /// - /// Short description of what this step will do - /// - public abstract string Summary { get; } - - /// - /// Detailed description of precisely what this step will do - /// - public abstract string Details { get; } +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +namespace OneSignalSDK { /// - /// Whether this step is required for operation of the SDK + /// Abstract class which must be inherited from in order to create a new setup step /// - public abstract bool IsRequired { get; } - - /// - /// Checks whether or not this step has been completed - /// - /// - /// The result is cached and only reset on run or specific other conditions - /// - public bool IsStepCompleted { - get - { - if (!_shouldCheckForCompletion) + public abstract class OneSignalSetupStep { + /// + /// Short description of what this step will do + /// + public abstract string Summary { get; } + + /// + /// Detailed description of precisely what this step will do + /// + public abstract string Details { get; } + + /// + /// Whether this step is required for operation of the SDK + /// + public abstract bool IsRequired { get; } + + /// + /// Checks whether or not this step has been completed + /// + /// + /// The result is cached and only reset on run or specific other conditions + /// + public bool IsStepCompleted { + get { + if (!_shouldCheckForCompletion) + return _isComplete; + + _isComplete = _getIsStepCompleted(); + _shouldCheckForCompletion = false; + return _isComplete; - - _isComplete = _getIsStepCompleted(); - _shouldCheckForCompletion = false; + } + } - return _isComplete; - } - } + /// + /// Runs all code necessary in order to fulfill the step + /// + public void RunStep() { + if (IsStepCompleted) + return; - /// - /// Runs all code necessary in order to fulfill the step - /// - public void RunStep() - { - if (IsStepCompleted) - return; - - _runStep(); - _shouldCheckForCompletion = true; - } + _runStep(); + _shouldCheckForCompletion = true; + } - protected abstract bool _getIsStepCompleted(); - protected abstract void _runStep(); + protected abstract bool _getIsStepCompleted(); + protected abstract void _runStep(); - private bool _isComplete = false; - protected bool _shouldCheckForCompletion = true; + 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 35b1a118a..2163cc762 100644 --- a/com.onesignal.unity.core/Editor/Setup/OneSignalSetupWindow.cs +++ b/com.onesignal.unity.core/Editor/Setup/OneSignalSetupWindow.cs @@ -1,173 +1,191 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System; using System.Collections.Generic; -using System.Linq; -using System.Xml; -using OneSignalSDK; using UnityEditor; using UnityEngine; -using UnityEngine.UI; - -/// -/// Pop up window which displays any additional required or optional setup steps by the SDK -/// -public sealed class OneSignalSetupWindow : EditorWindow -{ - [MenuItem("Window/OneSignal")] - public static void ShowWindow() - { - var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); - window.minSize = _minSize; - window.Show(); - } - - public static void CloseWindow() - { - var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); - window.Close(); - } - 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 IReadOnlyList _setupSteps; - private readonly Queue _stepsToRun = new Queue(); - - private bool _guiSetupComplete = false; - private GUIStyle _summaryStyle; - private GUIStyle _runStyle; - private GUIStyle _detailsStyle; - private GUIStyle _requiredStyle; - private GUIStyle _optionalStyle; - private Texture _checkTexture; - private Texture _boxTexture; - - private Vector2 _scrollPosition; - - private void OnEnable() - { - var stepTypes = ReflectionHelpers.FindAllAssignableTypes("OneSignal"); - var steps = new List(); - - foreach (var stepType in stepTypes) - { - if (Activator.CreateInstance(stepType) is OneSignalSetupStep step) - steps.Add(step); - else - Debug.LogWarning($"could not create setup step from type {stepType.Name}"); +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")] public static void ShowWindow() { + var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); + window.minSize = _minSize; + window.Show(); } - _setupSteps = steps; - } + public static void CloseWindow() { + var window = GetWindow(typeof(OneSignalSetupWindow), false, _title); + window.Close(); + } - private void OnGUI() - { - _setupGUI(); + private static readonly Vector2 _minSize = new Vector2(300, 400); - GUILayout.Label(_description); - EditorGUILayout.Separator(); + private const string _title = "OneSignal SDK Setup"; + private const string _description = "Additional steps required to get the OneSignal Unity SDK up and running"; - if (_setupSteps == null) - return; + private IReadOnlyList _setupSteps; + private readonly Queue _stepsToRun = new Queue(); - var willDisableControls = _stepsToRun.Count > 0 - || EditorApplication.isUpdating - || EditorApplication.isCompiling; + private bool _guiSetupComplete = false; + private GUIStyle _summaryStyle; + private GUIStyle _runStyle; + private GUIStyle _detailsStyle; + private GUIStyle _requiredStyle; + private GUIStyle _optionalStyle; + private Texture _checkTexture; + private Texture _boxTexture; - EditorGUI.BeginDisabledGroup(willDisableControls); - if (GUILayout.Button("Run All Steps")) - { - foreach (var step in _setupSteps) - _stepsToRun.Enqueue(step); + private Vector2 _scrollPosition; + + private void OnEnable() { + var stepTypes = ReflectionHelpers.FindAllAssignableTypes("OneSignal"); + var steps = new List(); + + foreach (var stepType in stepTypes) { + if (Activator.CreateInstance(stepType) is OneSignalSetupStep step) + steps.Add(step); + else + Debug.LogWarning($"could not create setup step from type {stepType.Name}"); + } + + _setupSteps = steps; } - EditorGUI.EndDisabledGroup(); - - EditorGUILayout.Separator(); - EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); - - EditorGUILayout.BeginHorizontal(); - _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); - - foreach (var step in _setupSteps) - { - EditorGUILayout.BeginHorizontal(); - var sumContent = new GUIContent(step.Summary); - var sumRect = GUILayoutUtility.GetRect(sumContent, _summaryStyle); + private void OnGUI() { + _setupGUI(); + + GUILayout.Label(_description); + EditorGUILayout.Separator(); + + if (_setupSteps == null) + return; + + var willDisableControls = _stepsToRun.Count > 0 + || EditorApplication.isUpdating + || EditorApplication.isCompiling; - var checkRect = new Rect(sumRect.x, sumRect.y, sumRect.height, sumRect.height); - GUI.DrawTexture(checkRect, step.IsStepCompleted ? _checkTexture: _boxTexture); + EditorGUI.BeginDisabledGroup(willDisableControls); + + if (GUILayout.Button("Run All Steps")) { + foreach (var step in _setupSteps) + _stepsToRun.Enqueue(step); + } - sumRect.x += sumRect.height + EditorStyles.label.padding.left; - GUI.Label(sumRect, sumContent); - - EditorGUI.BeginDisabledGroup(step.IsStepCompleted || willDisableControls); - if (GUILayout.Button("Run", _runStyle) && !_stepsToRun.Contains(step)) - _stepsToRun.Enqueue(step); EditorGUI.EndDisabledGroup(); - - EditorGUILayout.EndHorizontal(); - EditorGUILayout.Separator(); - GUILayout.Label(step.Details, _detailsStyle); - - if (step.IsRequired) - GUILayout.Label("Required", _requiredStyle); - else - GUILayout.Label("Optional", _optionalStyle); - + EditorGUILayout.Separator(); EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + + EditorGUILayout.BeginHorizontal(); + _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); + + foreach (var step in _setupSteps) { + EditorGUILayout.BeginHorizontal(); + + var sumContent = new GUIContent(step.Summary); + 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); + + sumRect.x += sumRect.height + EditorStyles.label.padding.left; + GUI.Label(sumRect, sumContent); + + EditorGUI.BeginDisabledGroup(step.IsStepCompleted || willDisableControls); + if (GUILayout.Button("Run", _runStyle) && !_stepsToRun.Contains(step)) + _stepsToRun.Enqueue(step); + + EditorGUI.EndDisabledGroup(); + + EditorGUILayout.EndHorizontal(); + EditorGUILayout.Separator(); + + GUILayout.Label(step.Details, _detailsStyle); + + if (step.IsRequired) + GUILayout.Label("Required", _requiredStyle); + else + GUILayout.Label("Optional", _optionalStyle); + + EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + } + + EditorGUILayout.EndScrollView(); + EditorGUILayout.EndHorizontal(); } - - EditorGUILayout.EndScrollView(); - EditorGUILayout.EndHorizontal(); - } - private void OnInspectorUpdate() - { - var runnerCount = _stepsToRun.Count + 1.0f; - while (_stepsToRun.Count > 0) - { - var step = _stepsToRun.Dequeue(); - - EditorUtility.DisplayProgressBar( - "OneSignal Setup", - $"Running step \"{step.Summary}\"", - _stepsToRun.Count / runnerCount - ); - - step.RunStep(); + private void OnInspectorUpdate() { + var runnerCount = _stepsToRun.Count + 1.0f; + + while (_stepsToRun.Count > 0) { + var step = _stepsToRun.Dequeue(); + + EditorUtility.DisplayProgressBar( + "OneSignal Setup", + $"Running step \"{step.Summary}\"", + _stepsToRun.Count / runnerCount + ); + + step.RunStep(); + } + + EditorUtility.ClearProgressBar(); } - EditorUtility.ClearProgressBar(); - } - private void _setupGUI() - { - if (_guiSetupComplete) - return; + private void _setupGUI() { + if (_guiSetupComplete) + return; - _summaryStyle = EditorStyles.boldLabel; + _summaryStyle = EditorStyles.boldLabel; - _detailsStyle = new GUIStyle(GUI.skin.textField); - _detailsStyle.wordWrap = true; + _detailsStyle = new GUIStyle(GUI.skin.textField); + _detailsStyle.wordWrap = true; - _runStyle = new GUIStyle(GUI.skin.button); - _runStyle.fixedWidth = _minSize.x * .3f; + _runStyle = new GUIStyle(GUI.skin.button); + _runStyle.fixedWidth = _minSize.x * .3f; - _requiredStyle = new GUIStyle(EditorStyles.miniBoldLabel); - _requiredStyle.normal.textColor = Color.red; + _requiredStyle = new GUIStyle(EditorStyles.miniBoldLabel); + _requiredStyle.normal.textColor = Color.red; - _optionalStyle = new GUIStyle(EditorStyles.miniBoldLabel); - _optionalStyle.normal.textColor = Color.yellow; - _optionalStyle.fontStyle = FontStyle.Italic; + _optionalStyle = new GUIStyle(EditorStyles.miniBoldLabel); + _optionalStyle.normal.textColor = Color.yellow; + _optionalStyle.fontStyle = FontStyle.Italic; - var checkContent = EditorGUIUtility.IconContent("TestPassed"); - _checkTexture = checkContent.image; + var checkContent = EditorGUIUtility.IconContent("TestPassed"); + _checkTexture = checkContent.image; - var boxContent = EditorGUIUtility.IconContent("Warning"); - _boxTexture = boxContent.image; - - _guiSetupComplete = true; + var boxContent = EditorGUIUtility.IconContent("Warning"); + _boxTexture = boxContent.image; + + _guiSetupComplete = 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 8894643c7..2f2b495f1 100644 --- a/com.onesignal.unity.core/Editor/SetupSteps/LinkXMLStep.cs +++ b/com.onesignal.unity.core/Editor/SetupSteps/LinkXMLStep.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -27,6 +27,7 @@ using System.IO; +namespace OneSignalSDK { /// /// Makes sure that the link.xml file for the OneSignal SDK exists /// @@ -56,4 +57,5 @@ protected override void _runStep() { 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 fecfbd3eb..2e8c16c93 100644 --- a/com.onesignal.unity.core/Editor/SetupSteps/SyncCodeBundleStep.cs +++ b/com.onesignal.unity.core/Editor/SetupSteps/SyncCodeBundleStep.cs @@ -27,59 +27,60 @@ using System.Collections.Generic; using System.IO; -using UnityEditor; using UnityEngine; -/// -/// 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"; +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 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)) { - Debug.LogError("Could not find package.json"); + protected override bool _getIsStepCompleted() { + if (!File.Exists(_packageJsonPath)) { + Debug.LogError("Could not find package.json"); - return true; - } + return true; + } - var packageJson = File.ReadAllText(_packageJsonPath); + var packageJson = File.ReadAllText(_packageJsonPath); - if (Json.Deserialize(packageJson) is Dictionary packageInfo) { - _sdkVersion = packageInfo["version"] as string; + if (Json.Deserialize(packageJson) is Dictionary packageInfo) { + _sdkVersion = packageInfo["version"] as string; - return _bundleVersion == _sdkVersion; - } + return _bundleVersion == _sdkVersion; + } - Debug.LogError("Could not deserialize package.json"); + Debug.LogError("Could not deserialize package.json"); - return true; - } + return true; + } - protected override void _runStep() { - var msg = $"Downloading OneSignal Unity SDK {_sdkVersion}"; - UnityPackageInstaller.DownloadAndInstall(_onesignalUnityPackageDownloadUrl, msg, result => { - if (!result) - _shouldCheckForCompletion = true; - }); - } + protected override void _runStep() { + var msg = $"Downloading OneSignal Unity SDK {_sdkVersion}"; + UnityPackageInstaller.DownloadAndInstall(_onesignalUnityPackageDownloadUrl, msg, result => { + if (!result) + _shouldCheckForCompletion = true; + }); + } - private static readonly string _versionPath = Path.Combine("Assets", "OneSignal", "VERSION"); - private static string _bundleVersion => File.ReadAllText(_versionPath); + 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/blob/{_sdkVersion}/OneSignal-v{_sdkVersion}.unitypackage"; + private static string _onesignalUnityPackageDownloadUrl + => $"https://github.com/OneSignal/OneSignal-Unity-SDK/blob/{_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; + 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 2ee6604ba..d453e772a 100644 --- a/com.onesignal.unity.core/Editor/Utilities/EditorWebRequest.cs +++ b/com.onesignal.unity.core/Editor/Utilities/EditorWebRequest.cs @@ -1,79 +1,108 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + using System; using UnityEditor; using UnityEngine.Networking; -/// -/// The EditorWebRequest is a wrapper around the `UnityWebRequest` that can work in Edit mode. -/// -class EditorWebRequest { - Action m_OnComplete = null; - - bool m_ShowProgress = false; - string m_ProgressDialogTitle = string.Empty; - +namespace OneSignalSDK { /// - /// Create an EditorWebRequest for HTTP GET. - /// Use the method to create a `EditorWebRequest`. - /// Set the target `URL` to the `uri` with a `string` or `Uri` argument. - /// No custom flags or headers are set. + /// The EditorWebRequest is a wrapper around the `UnityWebRequest` that can work in Edit mode. /// - /// The URI of the resource to retrieve via HTTP GET. - public static EditorWebRequest Get(string url) { - var unityRequest = UnityWebRequest.Get(url); + public class EditorWebRequest { + Action m_OnComplete = null; - return new EditorWebRequest(unityRequest); - } + bool m_ShowProgress = false; + string m_ProgressDialogTitle = string.Empty; - /// - /// Create new `EditorWebRequest` instance based on `UnityWebRequest`. - /// - /// - public EditorWebRequest(UnityWebRequest request) { - UnityRequest = request; - } + /// + /// Create an EditorWebRequest for HTTP GET. + /// Use the method to create a `EditorWebRequest`. + /// Set the target `URL` to the `uri` with a `string` or `Uri` argument. + /// No custom flags or headers are set. + /// + /// The URI of the resource to retrieve via HTTP GET. + public static EditorWebRequest Get(string url) { + var unityRequest = UnityWebRequest.Get(url); - /// - /// Request will display editor progress dialog with the given title. - /// - /// Editor progress dialog title. - public void AddEditorProgressDialog(string title) { - m_ShowProgress = true; - m_ProgressDialogTitle = title; - } - - /// - /// Begin communicating with the remote server. - /// - /// Communication callback. - public void Send(Action callback) { - m_OnComplete = callback; - EditorApplication.update += OnEditorUpdate; - UnityRequest.SendWebRequest(); - } + return new EditorWebRequest(unityRequest); + } - /// - /// The `UnityWebRequest` instance that is stored inside `EditorWebRequest`. - /// - public UnityWebRequest UnityRequest { get; } = null; + /// + /// Create new `EditorWebRequest` instance based on `UnityWebRequest`. + /// + /// + public EditorWebRequest(UnityWebRequest request) { + UnityRequest = request; + } - /// - /// The shortcut for `UnityRequest.downloadHandler.text`. - /// - public string DataAsText => UnityRequest.downloadHandler.text; + /// + /// Request will display editor progress dialog with the given title. + /// + /// Editor progress dialog title. + public void AddEditorProgressDialog(string title) { + m_ShowProgress = true; + m_ProgressDialogTitle = title; + } - void OnEditorUpdate() { - if (m_ShowProgress) { - var progress = $"Download Progress: {Convert.ToInt32(UnityRequest.downloadProgress * 100f)}%"; - EditorUtility.DisplayProgressBar(m_ProgressDialogTitle, progress, UnityRequest.downloadProgress); + /// + /// Begin communicating with the remote server. + /// + /// Communication callback. + public void Send(Action callback) { + m_OnComplete = callback; + EditorApplication.update += OnEditorUpdate; + UnityRequest.SendWebRequest(); } - if (UnityRequest.isDone) { + /// + /// The `UnityWebRequest` instance that is stored inside `EditorWebRequest`. + /// + public UnityWebRequest UnityRequest { get; } = null; + + /// + /// The shortcut for `UnityRequest.downloadHandler.text`. + /// + public string DataAsText => UnityRequest.downloadHandler.text; + + void OnEditorUpdate() { if (m_ShowProgress) { - EditorUtility.ClearProgressBar(); + var progress = $"Download Progress: {Convert.ToInt32(UnityRequest.downloadProgress * 100f)}%"; + EditorUtility.DisplayProgressBar(m_ProgressDialogTitle, progress, UnityRequest.downloadProgress); } - EditorApplication.update -= OnEditorUpdate; - m_OnComplete.Invoke(UnityRequest); + if (UnityRequest.isDone) { + if (m_ShowProgress) { + EditorUtility.ClearProgressBar(); + } + + EditorApplication.update -= OnEditorUpdate; + m_OnComplete.Invoke(UnityRequest); + } } } } \ 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 68b83d9af..cc5d2a5ee 100644 --- a/com.onesignal.unity.core/Editor/Utilities/UnityPackageInstaller.cs +++ b/com.onesignal.unity.core/Editor/Utilities/UnityPackageInstaller.cs @@ -30,29 +30,31 @@ using UnityEditor; using UnityEngine; -/// -/// Helper to download and install packages -/// -public static class UnityPackageInstaller { +namespace OneSignalSDK { /// - /// Downloads and install a unitypackage from the specified url + /// Helper to download and install packages /// - 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"); - onComplete(false); - } + public static class UnityPackageInstaller { + /// + /// Downloads and install a unitypackage from the specified url + /// + 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"); + 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); + File.WriteAllBytes(tmpPackageFile, unityRequest.downloadHandler.data); + AssetDatabase.ImportPackage(tmpPackageFile, false); - onComplete(true); - }); + onComplete(true); + }); + } } } \ No newline at end of file diff --git a/com.onesignal.unity.core/LICENSE.md b/com.onesignal.unity.core/LICENSE.md index 859d8e642..a65566a84 100644 --- a/com.onesignal.unity.core/LICENSE.md +++ b/com.onesignal.unity.core/LICENSE.md @@ -1,6 +1,6 @@ Modified MIT License -Copyright 2020 OneSignal +Copyright 2022 OneSignal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/AssemblyInfo.cs b/com.onesignal.unity.core/Runtime/AssemblyInfo.cs index cac435d46..0f4f0eb02 100644 --- a/com.onesignal.unity.core/Runtime/AssemblyInfo.cs +++ b/com.onesignal.unity.core/Runtime/AssemblyInfo.cs @@ -1,4 +1,31 @@ -using System.Runtime.CompilerServices; +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("OneSignal.iOS")] [assembly: InternalsVisibleTo("OneSignal.Android")] diff --git a/com.onesignal.unity.core/Runtime/Models/EmailSubscriptionState.cs b/com.onesignal.unity.core/Runtime/Models/EmailSubscriptionState.cs index 04cd1dae0..b6edc30e3 100755 --- a/com.onesignal.unity.core/Runtime/Models/EmailSubscriptionState.cs +++ b/com.onesignal.unity.core/Runtime/Models/EmailSubscriptionState.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/Models/InAppMessage.cs b/com.onesignal.unity.core/Runtime/Models/InAppMessage.cs index c641034bc..7305bec88 100644 --- a/com.onesignal.unity.core/Runtime/Models/InAppMessage.cs +++ b/com.onesignal.unity.core/Runtime/Models/InAppMessage.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/Models/InAppMessageAction.cs b/com.onesignal.unity.core/Runtime/Models/InAppMessageAction.cs index a4ed02c08..3ef40a4a4 100755 --- a/com.onesignal.unity.core/Runtime/Models/InAppMessageAction.cs +++ b/com.onesignal.unity.core/Runtime/Models/InAppMessageAction.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/Models/Notification.cs b/com.onesignal.unity.core/Runtime/Models/Notification.cs index 0f99b2ed0..d1cfd0da5 100755 --- a/com.onesignal.unity.core/Runtime/Models/Notification.cs +++ b/com.onesignal.unity.core/Runtime/Models/Notification.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/Models/NotificationAction.cs b/com.onesignal.unity.core/Runtime/Models/NotificationAction.cs index dd5d86583..6b0e120ba 100755 --- a/com.onesignal.unity.core/Runtime/Models/NotificationAction.cs +++ b/com.onesignal.unity.core/Runtime/Models/NotificationAction.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/Models/NotificationOpenedResult.cs b/com.onesignal.unity.core/Runtime/Models/NotificationOpenedResult.cs index d62205692..654be715b 100755 --- a/com.onesignal.unity.core/Runtime/Models/NotificationOpenedResult.cs +++ b/com.onesignal.unity.core/Runtime/Models/NotificationOpenedResult.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/Models/NotificationPermission.cs b/com.onesignal.unity.core/Runtime/Models/NotificationPermission.cs index 68b7b53f3..5d3362ca6 100755 --- a/com.onesignal.unity.core/Runtime/Models/NotificationPermission.cs +++ b/com.onesignal.unity.core/Runtime/Models/NotificationPermission.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/Models/PushSubscriptionState.cs b/com.onesignal.unity.core/Runtime/Models/PushSubscriptionState.cs index dbb60ebdc..47b1d6968 100644 --- a/com.onesignal.unity.core/Runtime/Models/PushSubscriptionState.cs +++ b/com.onesignal.unity.core/Runtime/Models/PushSubscriptionState.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/Models/SMSSubscriptionState.cs b/com.onesignal.unity.core/Runtime/Models/SMSSubscriptionState.cs index cab30f008..05ffec539 100644 --- a/com.onesignal.unity.core/Runtime/Models/SMSSubscriptionState.cs +++ b/com.onesignal.unity.core/Runtime/Models/SMSSubscriptionState.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/OneSignal.Internal.cs b/com.onesignal.unity.core/Runtime/OneSignal.Internal.cs index 770db5ff2..84112a697 100755 --- a/com.onesignal.unity.core/Runtime/OneSignal.Internal.cs +++ b/com.onesignal.unity.core/Runtime/OneSignal.Internal.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/OneSignal.cs b/com.onesignal.unity.core/Runtime/OneSignal.cs index fee67498b..79314e56e 100755 --- a/com.onesignal.unity.core/Runtime/OneSignal.cs +++ b/com.onesignal.unity.core/Runtime/OneSignal.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -25,7 +25,6 @@ * THE SOFTWARE. */ -using System; using System.Collections.Generic; using System.Threading.Tasks; using UnityEngine; diff --git a/com.onesignal.unity.core/Runtime/OneSignalBehaviour.cs b/com.onesignal.unity.core/Runtime/OneSignalBehaviour.cs index 3e063bff7..2dd9d67fd 100644 --- a/com.onesignal.unity.core/Runtime/OneSignalBehaviour.cs +++ b/com.onesignal.unity.core/Runtime/OneSignalBehaviour.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/OneSignalSettings.cs b/com.onesignal.unity.core/Runtime/OneSignalSettings.cs deleted file mode 100755 index 1cfcd61b0..000000000 --- a/com.onesignal.unity.core/Runtime/OneSignalSettings.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.IO; -using UnityEngine; -#if UNITY_EDITOR -using UnityEditor; -#endif - -/// -/// OneSignal Project Config. -/// -public class OneSignalSettings : ScriptableObject -{ - static OneSignalSettings s_Instance; - - /// - /// OneSignal Application Id. - /// - public string ApplicationId; - - /// - /// Project folder related settings ScriptableObject location path - /// - public static readonly string SettingsLocation = Path.Combine("Assets", "Plugins", "OneSignal", "Resources"); - - internal const string ProductName = "OneSignal"; - - /// - /// Returns a singleton class instance. - /// If current instance is not assigned it will try to find an object of the instance type, - /// in case instance already exists in a project. If not, new instance will be created, - /// and saved under the . - /// - public static OneSignalSettings Instance - { - get - { - if (s_Instance == null) - { - s_Instance = Resources.Load(nameof(OneSignalSettings)); - if (s_Instance == null) - { - s_Instance = CreateInstance(); - s_Instance.SaveToAssetDatabase(); - } - } - - return s_Instance; - } - } - -#if UNITY_EDITOR - internal static void Save() => EditorUtility.SetDirty(Instance); -#endif - - void SaveToAssetDatabase() - { -#if UNITY_EDITOR - if (!Directory.Exists(SettingsLocation)) - { - Directory.CreateDirectory(SettingsLocation); - } - - AssetDatabase.CreateAsset(this, $"{SettingsLocation}/{nameof(OneSignalSettings)}.asset"); -#endif - } -} \ No newline at end of file diff --git a/com.onesignal.unity.core/Runtime/OneSignalSettings.cs.meta b/com.onesignal.unity.core/Runtime/OneSignalSettings.cs.meta deleted file mode 100755 index f6fb9c12d..000000000 --- a/com.onesignal.unity.core/Runtime/OneSignalSettings.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: c411a0a4613442d7a4cbfd5471c5bb87 -timeCreated: 1629813820 \ No newline at end of file diff --git a/com.onesignal.unity.core/Runtime/Utilities/SDKDebug.cs b/com.onesignal.unity.core/Runtime/Utilities/SDKDebug.cs index 72aafe41f..557cd8029 100644 --- a/com.onesignal.unity.core/Runtime/Utilities/SDKDebug.cs +++ b/com.onesignal.unity.core/Runtime/Utilities/SDKDebug.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Runtime/Utilities/UnityMainThreadDispatch.cs b/com.onesignal.unity.core/Runtime/Utilities/UnityMainThreadDispatch.cs index 72069dc78..e191109e1 100644 --- a/com.onesignal.unity.core/Runtime/Utilities/UnityMainThreadDispatch.cs +++ b/com.onesignal.unity.core/Runtime/Utilities/UnityMainThreadDispatch.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.core/Samples~/OneSignalExampleBehaviour.cs b/com.onesignal.unity.core/Samples~/OneSignalExampleBehaviour.cs index 27404ba54..4a70f13e5 100644 --- a/com.onesignal.unity.core/Samples~/OneSignalExampleBehaviour.cs +++ b/com.onesignal.unity.core/Samples~/OneSignalExampleBehaviour.cs @@ -1,418 +1,471 @@ +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + #if ONE_SIGNAL_INSTALLED using System; using System.Collections.Generic; +using OneSignalSDK; using UnityEngine; using UnityEngine.UI; -using UnityEngine.UIElements; // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace -namespace OneSignalSDK { - public class OneSignalExampleBehaviour : MonoBehaviour { - /// - /// set to an email address you would like to test notifications against - /// - public string email; - - /// - /// set to an external user id you would like to test notifications against - /// - public string externalId; - - /// - /// set to an external user id you would like to test notifications against - /// - public string phoneNumber; - - /// - /// set to your app id (https://documentation.onesignal.com/docs/accounts-and-keys) - /// - public string appId; - - /// - /// whether you would prefer OneSignal Unity SDK prevent initialization until consent is granted via - /// in this test MonoBehaviour - /// - public bool requiresUserPrivacyConsent; - - /// - /// - /// - public string tagKey; - - /// - /// - /// - public string tagValue; - - /// - /// - /// - public string triggerKey; - - /// - /// - /// - public string triggerValue; - - /// - /// - /// - public string outcomeKey; - - /// - /// - /// - public float outcomeValue; - - /// - /// 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() { - // Enable lines below to debug issues with OneSignal - OneSignal.Default.LogLevel = LogType.Log; - OneSignal.Default.AlertLevel = LogType.Exception; - - // Setting RequiresPrivacyConsent to true will prevent the OneSignalSDK from operating until - // PrivacyConsent is also set to true - OneSignal.Default.RequiresPrivacyConsent = requiresUserPrivacyConsent; - - // Setup the below to listen for and respond to events from notifications - OneSignal.Default.NotificationOpened += _notificationOpened; - OneSignal.Default.NotificationReceived += _notificationReceived; - - // Setup the below to listen for and respond to events from in app messages - OneSignal.Default.InAppMessageTriggeredAction += IamTriggeredAction; +/// +/// Example class to show how an application can utilize the public methods of the OneSignal SDK +/// +public class OneSignalExampleBehaviour : MonoBehaviour { + /// + /// set to an email address you would like to test notifications against + /// + public string email; + + /// + /// set to an external user id you would like to test notifications against + /// + public string externalId; + + /// + /// set to an external user id you would like to test notifications against + /// + public string phoneNumber; + + /// + /// set to your app id (https://documentation.onesignal.com/docs/accounts-and-keys) + /// + public string appId; + + /// + /// whether you would prefer OneSignal Unity SDK prevent initialization until consent is granted via + /// in this test MonoBehaviour + /// + public bool requiresUserPrivacyConsent; + + /// + /// + /// + public string tagKey; + + /// + /// + /// + public string tagValue; + + /// + /// + /// + public string triggerKey; + + /// + /// + /// + public string triggerValue; + + /// + /// + /// + public string outcomeKey; + + /// + /// + /// + public float outcomeValue; + + /// + /// 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() { + // Enable lines below to debug issues with OneSignal + OneSignal.Default.LogLevel = LogLevel.Info; + OneSignal.Default.AlertLevel = LogLevel.Fatal; + + // Setting RequiresPrivacyConsent to true will prevent the OneSignalSDK from operating until + // PrivacyConsent is also set to true + OneSignal.Default.RequiresPrivacyConsent = requiresUserPrivacyConsent; + + // Setup the below to listen for and respond to events from notifications + OneSignal.Default.NotificationOpened += _notificationOpened; + OneSignal.Default.NotificationWillShow += _notificationReceived; + + // Setup the below to listen for and respond to events from in app messages + OneSignal.Default.InAppMessageWillDisplay += _iamWillDisplay; + OneSignal.Default.InAppMessageDidDisplay += _iamDidDisplay; + OneSignal.Default.InAppMessageWillDismiss += _iamWillDismiss; + OneSignal.Default.InAppMessageDidDismiss += _iamDidDismiss; + OneSignal.Default.InAppMessageTriggeredAction += _iamTriggeredAction; + + // Setup the below to listen for and respond to state changes + OneSignal.Default.NotificationPermissionChanged += _notificationPermissionChanged; + OneSignal.Default.PushSubscriptionStateChanged += _pushStateChanged; + OneSignal.Default.EmailSubscriptionStateChanged += _emailStateChanged; + OneSignal.Default.SMSSubscriptionStateChanged += _smsStateChanged; + } + + /* + * SDK events + */ + + private void _notificationOpened(NotificationOpenedResult result) { + _log($"Notification was opened with result: {JsonUtility.ToJson(result)}"); + } + + private Notification _notificationReceived(Notification notification) { + var additionalData = notification.additionalData != null + ? Json.Serialize(notification.additionalData) + : null; - // Setup the below to listen for and respond to state changes - OneSignal.Default.PermissionStateChanged += _permissionStateChanged; - OneSignal.Default.PushSubscriptionStateChanged += _pushStateChanged; - OneSignal.Default.EmailSubscriptionStateChanged += _emailStateChanged; - OneSignal.Default.SMSSubscriptionStateChanged += _smsStateChanged; + _log($"Notification was received in foreground: {JsonUtility.ToJson(notification)}\n{additionalData}"); + return notification; // show the notification } - - /* - * SDK events - */ - private void _notificationOpened(NotificationOpenedResult result) { - _log($"Notification was opened with result: {JsonUtility.ToJson(result)}"); - } + private void _iamWillDisplay(InAppMessage inAppMessage) { + _log($"IAM will display: {JsonUtility.ToJson(inAppMessage)}"); + } - private void _notificationReceived(Notification notification) { - _log($"Notification was received in foreground: {JsonUtility.ToJson(notification)}"); - } + private void _iamDidDisplay(InAppMessage inAppMessage) { + _log($"IAM did display: {JsonUtility.ToJson(inAppMessage)}"); + } - private void IamTriggeredAction(InAppMessageAction inAppMessageAction) { - _log($"IAM triggered action: {JsonUtility.ToJson(inAppMessageAction)}"); - } + private void _iamWillDismiss(InAppMessage inAppMessage) { + _log($"IAM will dismiss: {JsonUtility.ToJson(inAppMessage)}"); + } - private void _permissionStateChanged(PermissionState current, PermissionState previous) { - _log($"Permission state changed to: {JsonUtility.ToJson(current)}"); - } + private void _iamDidDismiss(InAppMessage inAppMessage) { + _log($"IAM did dismiss: {JsonUtility.ToJson(inAppMessage)}"); + } - private void _pushStateChanged(PushSubscriptionState current, PushSubscriptionState previous) { - _log($"Push state changed to: {JsonUtility.ToJson(current)}"); - } + private void _iamTriggeredAction(InAppMessageAction inAppMessageAction) { + _log($"IAM triggered action: {JsonUtility.ToJson(inAppMessageAction)}"); + } - private void _emailStateChanged(EmailSubscriptionState current, EmailSubscriptionState previous) { - _log($"Email state changed to: {JsonUtility.ToJson(current)}"); - } + private void _notificationPermissionChanged(NotificationPermission current, NotificationPermission previous) { + _log($"Notification Permissions changed to: {current}"); + } - private void _smsStateChanged(SMSSubscriptionState current, SMSSubscriptionState previous) { - _log($"SMS state changed to: {JsonUtility.ToJson(current)}"); - } - - /* - * SDK setup - */ - - public void Initialize() { - _log($"Initializing with appId {appId}"); - OneSignal.Default.Initialize(appId); - } + private void _pushStateChanged(PushSubscriptionState current, PushSubscriptionState previous) { + _log($"Push state changed to: {JsonUtility.ToJson(current)}"); + } - public void ToggleRequiresPrivacyConsent() { - _log($"Toggling RequiresPrivacyConsent to {!OneSignal.Default.RequiresPrivacyConsent}"); - OneSignal.Default.RequiresPrivacyConsent = !OneSignal.Default.RequiresPrivacyConsent; - } + private void _emailStateChanged(EmailSubscriptionState current, EmailSubscriptionState previous) { + _log($"Email state changed to: {JsonUtility.ToJson(current)}"); + } - public void TogglePrivacyConsent() { - _log($"Toggling PrivacyConsent to {!OneSignal.Default.PrivacyConsent}"); - OneSignal.Default.PrivacyConsent = !OneSignal.Default.PrivacyConsent; - } + private void _smsStateChanged(SMSSubscriptionState current, SMSSubscriptionState previous) { + _log($"SMS state changed to: {JsonUtility.ToJson(current)}"); + } - public void SetLogLevel() { - var newLevel = _nextEnum(OneSignal.Default.LogLevel); - _log($"Setting LogLevel to {newLevel}"); - - // LogLevel uses the standard Unity LogType - OneSignal.Default.LogLevel = newLevel; - } + /* + * SDK setup + */ - public void SetAlertLevel() { - var newLevel = _nextEnum(OneSignal.Default.AlertLevel); - _log($"Setting AlertLevel to {newLevel}"); - - // AlertLevel uses the standard Unity LogType - OneSignal.Default.AlertLevel = newLevel; - } - - /* - * User identification - */ + public void Initialize() { + _log($"Initializing with appId {appId}"); + OneSignal.Default.Initialize(appId); + } - public async void SetEmail() { - _log($"Calling SetEmail({email}) and awaiting result..."); - - var result = await OneSignal.Default.SetEmail(email); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + public void ToggleRequiresPrivacyConsent() { + _log($"Toggling RequiresPrivacyConsent to {!OneSignal.Default.RequiresPrivacyConsent}"); + OneSignal.Default.RequiresPrivacyConsent = !OneSignal.Default.RequiresPrivacyConsent; + } - public async void SetExternalId() { - _log($"Calling SetExternalUserId({externalId}) and awaiting result..."); - - var result = await OneSignal.Default.SetExternalUserId(externalId); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + public void TogglePrivacyConsent() { + _log($"Toggling PrivacyConsent to {!OneSignal.Default.PrivacyConsent}"); + OneSignal.Default.PrivacyConsent = !OneSignal.Default.PrivacyConsent; + } - public async void SetSMSNumber() { - _log($"Calling SetSMSNumber({phoneNumber}) and awaiting result..."); - - var result = await OneSignal.Default.SetSMSNumber(phoneNumber); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } - - /* - * Push - */ + public void SetLogLevel() { + var newLevel = _nextEnum(OneSignal.Default.LogLevel); + _log($"Setting LogLevel to {newLevel}"); - public async void PromptForPush() { - _log("Calling PromptForPushNotificationsWithUserResponse and awaiting result..."); + // LogLevel uses the standard Unity LogType + OneSignal.Default.LogLevel = newLevel; + } - var result = await OneSignal.Default.PromptForPushNotificationsWithUserResponse(); + public void SetAlertLevel() { + var newLevel = _nextEnum(OneSignal.Default.AlertLevel); + _log($"Setting AlertLevel to {newLevel}"); - _log($"Prompt completed with {result}"); - } + // AlertLevel uses the standard Unity LogType + OneSignal.Default.AlertLevel = newLevel; + } - public void ClearPush() { - _log("Clearing existing OneSignal push notifications..."); - OneSignal.Default.ClearOneSignalNotifications(); - } + /* + * User identification + */ - public async void SendPushToSelf() { - _log("Sending push notification to this device via PostNotification..."); - - // Check out our API docs at https://documentation.onesignal.com/reference/create-notification - // for a full list of possibilities for notification options. - var pushOptions = new Dictionary { - ["contents"] = new Dictionary { - ["en"] = "Test Message" - }, + public async void SetEmail() { + _log($"Calling SetEmail({email}) and awaiting result..."); - // Send notification to this user - ["include_external_user_ids"] = new List { externalId }, + var result = await OneSignal.Default.SetEmail(email); - // Example of scheduling a notification in the future - ["send_after"] = DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U") - }; + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } - var result = await OneSignal.Default.PostNotification(pushOptions); - - if (Json.Serialize(result) is string resultString) - _log($"Notification sent with result {resultString}"); - else - _error("Could not serialize result of PostNotification"); - } - - /* - * In App Messages - */ - - public void SetTrigger() { - _log($"Setting trigger with key {triggerKey} and value {triggerValue}"); - OneSignal.Default.SetTrigger(triggerKey, triggerValue); - } + public async void SetExternalId() { + _log($"Calling SetExternalUserId({externalId}) and awaiting result..."); - public void GetTrigger() { - _log($"Getting trigger for key {triggerKey}"); - var value = OneSignal.Default.GetTrigger(triggerKey); - _log($"Trigger for key {triggerKey} is of value {value}"); - } + var result = await OneSignal.Default.SetExternalUserId(externalId); - public void RemoveTrigger() { - _log($"Removing trigger for key {triggerKey}"); - OneSignal.Default.RemoveTrigger(triggerKey); - } + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } - public void GetTriggers() { - _log("Getting all trigger keys and values"); - var triggers = OneSignal.Default.GetTriggers(); - - if (Json.Serialize(triggers) is string triggersString) - _log($"Current triggers are {triggersString}"); - else - _error("Could not serialize triggers"); - } - - public void ToggleInAppMessagesArePaused() { - _log($"Toggling InAppMessagesArePaused to {!OneSignal.Default.InAppMessagesArePaused}"); - OneSignal.Default.InAppMessagesArePaused = !OneSignal.Default.InAppMessagesArePaused; - } - - /* - * Tags - */ + public async void SetSMSNumber() { + _log($"Calling SetSMSNumber({phoneNumber}) and awaiting result..."); - public async void SetTag() { - _log($"Setting tag with key {tagKey} and value {tagValue} and awaiting result..."); + var result = await OneSignal.Default.SetSMSNumber(phoneNumber); - var result = await OneSignal.Default.SendTag(tagKey, tagValue); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } - public async void RemoveTag() { - _log($"Removing tag for key {triggerKey} and awaiting result..."); + /* + * Push + */ - var result = await OneSignal.Default.DeleteTag(tagKey); - - if (result) - _log("Remove succeeded"); - else - _error("Remove failed"); - } + public async void PromptForPush() { + _log("Calling PromptForPushNotificationsWithUserResponse and awaiting result..."); - public async void GetTags() { - _log("Requesting all tag keys and values for this user..."); - var tags = await OneSignal.Default.GetTags(); - - if (Json.Serialize(tags) is string tagsString) - _log($"Current tags are {tagsString}"); - else - _error("Could not serialize tags"); - } - - /* - * Outcomes - */ + var result = await OneSignal.Default.PromptForPushNotificationsWithUserResponse(); - public async void SetOutcome() { - _log($"Setting outcome with key {outcomeKey} and awaiting result..."); + _log($"Prompt completed with {result}"); + } - var result = await OneSignal.Default.SendOutcome(outcomeKey); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + public void ClearPush() { + _log("Clearing existing OneSignal push notifications..."); + OneSignal.Default.ClearOneSignalNotifications(); + } - public async void SetUniqueOutcome() { - _log($"Setting unique outcome with key {outcomeKey} and awaiting result..."); + public async void SendPushToSelf() { + _log("Sending push notification to this device via PostNotification..."); - var result = await OneSignal.Default.SendUniqueOutcome(outcomeKey); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } + // Check out our API docs at https://documentation.onesignal.com/reference/create-notification + // for a full list of possibilities for notification options. + var pushOptions = new Dictionary { + ["contents"] = new Dictionary { + ["en"] = "Test Message" + }, - public async void SetOutcomeWithValue() { - _log($"Setting outcome with key {outcomeKey} and value {outcomeValue} and awaiting result..."); + // Send notification to this user + ["include_external_user_ids"] = new List { externalId }, - var result = await OneSignal.Default.SendOutcomeWithValue(outcomeKey, outcomeValue); - - if (result) - _log("Set succeeded"); - else - _error("Set failed"); - } - - /* - * Location - */ - - public void PromptLocation() { - _log("Opening prompt to ask for user consent to access location"); - OneSignal.Default.PromptLocation(); - } - - public void ToggleShareLocation() { - _log($"Toggling ShareLocation to {!OneSignal.Default.ShareLocation}"); - OneSignal.Default.ShareLocation = !OneSignal.Default.ShareLocation; - } + // Example of scheduling a notification in the future + ["send_after"] = DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U") + }; - #region Rendering - /* - * You can safely ignore everything in this region and below - */ - - public Text console; - - 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 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); - - private void Awake() { - SDKDebug.LogIntercept += _log; - SDKDebug.WarnIntercept += _warn; - SDKDebug.ErrorIntercept += _error; - } + var result = await OneSignal.Default.PostNotification(pushOptions); - private void _log(object message) { - Debug.Log(message); - console.text += $"\nI> {message}"; - } + if (Json.Serialize(result) is string resultString) + _log($"Notification sent with result {resultString}"); + else + _error("Could not serialize result of PostNotification"); + } - private void _warn(object message) { - Debug.LogWarning(message); - console.text += $"\nW> {message}"; - } + /* + * In App Messages + */ - private void _error(object message) { - Debug.LogError(message); - console.text += $"\nE> {message}"; - } - #endregion - - #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 + public void SetTrigger() { + _log($"Setting trigger with key {triggerKey} and value {triggerValue}"); + OneSignal.Default.SetTrigger(triggerKey, triggerValue); + } + + public void GetTrigger() { + _log($"Getting trigger for key {triggerKey}"); + var value = OneSignal.Default.GetTrigger(triggerKey); + _log($"Trigger for key {triggerKey} is of value {value}"); + } + + public void RemoveTrigger() { + _log($"Removing trigger for key {triggerKey}"); + OneSignal.Default.RemoveTrigger(triggerKey); + } + + public void GetTriggers() { + _log("Getting all trigger keys and values"); + var triggers = OneSignal.Default.GetTriggers(); + + if (Json.Serialize(triggers) is string triggersString) + _log($"Current triggers are {triggersString}"); + else + _error("Could not serialize triggers"); + } + + public void ToggleInAppMessagesArePaused() { + _log($"Toggling InAppMessagesArePaused to {!OneSignal.Default.InAppMessagesArePaused}"); + OneSignal.Default.InAppMessagesArePaused = !OneSignal.Default.InAppMessagesArePaused; + } + + /* + * Tags + */ + + public async void SetTag() { + _log($"Setting tag with key {tagKey} and value {tagValue} and awaiting result..."); + + var result = await OneSignal.Default.SendTag(tagKey, tagValue); + + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } + + public async void RemoveTag() { + _log($"Removing tag for key {triggerKey} and awaiting result..."); + + var result = await OneSignal.Default.DeleteTag(tagKey); + + if (result) + _log("Remove succeeded"); + else + _error("Remove failed"); + } + + public async void GetTags() { + _log("Requesting all tag keys and values for this user..."); + var tags = await OneSignal.Default.GetTags(); + + if (Json.Serialize(tags) is string tagsString) + _log($"Current tags are {tagsString}"); + else + _error("Could not serialize tags"); + } + + /* + * Outcomes + */ + + public async void SetOutcome() { + _log($"Setting outcome with key {outcomeKey} and awaiting result..."); + + var result = await OneSignal.Default.SendOutcome(outcomeKey); + + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } + + public async void SetUniqueOutcome() { + _log($"Setting unique outcome with key {outcomeKey} and awaiting result..."); + + var result = await OneSignal.Default.SendUniqueOutcome(outcomeKey); + + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } + + public async void SetOutcomeWithValue() { + _log($"Setting outcome with key {outcomeKey} and value {outcomeValue} and awaiting result..."); + + var result = await OneSignal.Default.SendOutcomeWithValue(outcomeKey, outcomeValue); + + if (result) + _log("Set succeeded"); + else + _error("Set failed"); + } + + /* + * Location + */ + + public void PromptLocation() { + _log("Opening prompt to ask for user consent to access location"); + OneSignal.Default.PromptLocation(); + } + + public void ToggleShareLocation() { + _log($"Toggling ShareLocation to {!OneSignal.Default.ShareLocation}"); + OneSignal.Default.ShareLocation = !OneSignal.Default.ShareLocation; + } + +#region Rendering + /* + * You can safely ignore everything in this region and below + */ + + public Text console; + + 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 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); + + private void Awake() { + SDKDebug.LogIntercept += _log; + SDKDebug.WarnIntercept += _warn; + SDKDebug.ErrorIntercept += _error; + } + + private void _log(object message) { + Debug.Log(message); + console.text += $"\nI> {message}"; + } + + private void _warn(object message) { + Debug.LogWarning(message); + console.text += $"\nW> {message}"; + } + + private void _error(object message) { + Debug.LogError(message); + console.text += $"\nE> {message}"; + } +#endregion + +#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 } #endif \ No newline at end of file diff --git a/com.onesignal.unity.ios/Editor/BuildPostProcessor.cs b/com.onesignal.unity.ios/Editor/BuildPostProcessor.cs index e9d86c9e9..aff08c44e 100644 --- a/com.onesignal.unity.ios/Editor/BuildPostProcessor.cs +++ b/com.onesignal.unity.ios/Editor/BuildPostProcessor.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,6 +24,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + /* * Testing Notes * When making any changes please test the following senerios @@ -47,6 +48,7 @@ // can't be fix. // ADD_APP_GROUP is required for; // Outcomes, Badge Increment, and possibly for future features + #define ADD_APP_GROUP using System.IO; @@ -82,7 +84,7 @@ [Flags] private enum Entitlement { } private static readonly Dictionary EntitlementKeys = new Dictionary { - [Entitlement.ApsEnv] = "aps-environment", + [Entitlement.ApsEnv] = "aps-environment", [Entitlement.AppGroups] = "com.apple.security.application-groups" }; @@ -104,9 +106,9 @@ [Flags] private enum Entitlement { 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)); @@ -135,8 +137,10 @@ public void OnPostprocessBuild(BuildReport report) { /// private string GetEntitlementsPath(string targetGuid, string targetName) { var relativePath = _project.GetBuildPropertyForAnyConfig(targetGuid, "CODE_SIGN_ENTITLEMENTS"); + if (relativePath != null) { var fullPath = Path.Combine(_outputPath, relativePath); + if (File.Exists(fullPath)) return fullPath; } @@ -148,7 +152,7 @@ private string GetEntitlementsPath(string targetGuid, string targetName) { /// Add or update the values of necessary entitlements /// private void UpdateEntitlements(Entitlement entitlements, string targetGuid, string targetName) { - var entitlementsPath = GetEntitlementsPath(targetGuid, targetName); + var entitlementsPath = GetEntitlementsPath(targetGuid, targetName); var entitlementsPlist = new PlistDocument(); var existingEntitlements = File.Exists(entitlementsPath); @@ -157,8 +161,9 @@ private void UpdateEntitlements(Entitlement entitlements, string targetGuid, str entitlementsPlist.ReadFromFile(entitlementsPath); var groupsKey = EntitlementKeys[Entitlement.AppGroups]; + if ((entitlements & Entitlement.AppGroups) != 0) { - var groups = entitlementsPlist.root[groupsKey] == null + var groups = entitlementsPlist.root[groupsKey] == null ? entitlementsPlist.root.CreateArray(groupsKey) : entitlementsPlist.root[groupsKey].AsArray(); @@ -189,6 +194,7 @@ private void AddPushCapability(string targetGuid, string targetName) { _project.AddCapability(targetGuid, PBXCapabilityType.BackgroundModes); var entitlementsPath = GetEntitlementsPath(targetGuid, targetName); + // NOTE: ProjectCapabilityManager's 4th constructor param requires Unity 2019.3+ var projCapability = new ProjectCapabilityManager(_projectPath, entitlementsPath, targetName); projCapability.AddBackgroundModes(BackgroundModesOptions.RemoteNotifications); @@ -226,6 +232,7 @@ private void AddNotificationServiceExtension() { _project.AddBuildProperty(extensionGuid, "LIBRARY_SEARCH_PATHS", $"$(PROJECT_DIR)/Libraries/{PluginLibrariesPath.Replace("\\", "/")}"); + _project.WriteToFile(_projectPath); UpdateEntitlements(Entitlement.AppGroups, extensionGuid, ServiceExtensionTargetName); @@ -236,8 +243,8 @@ 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 buildPhaseID = _project.AddSourcesBuildPhase(extensionGuid); + var sourcePath = Path.Combine(PluginFilesPath, ServiceExtensionFilename); var destPathRelative = Path.Combine(ServiceExtensionTargetName, ServiceExtensionFilename); var destPath = Path.Combine(_outputPath, destPathRelative); @@ -256,7 +263,7 @@ 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(); diff --git a/com.onesignal.unity.ios/Editor/PBXProjectExtensions.cs b/com.onesignal.unity.ios/Editor/PBXProjectExtensions.cs index cb9d7eec6..b79f7c3cf 100644 --- a/com.onesignal.unity.ios/Editor/PBXProjectExtensions.cs +++ b/com.onesignal.unity.ios/Editor/PBXProjectExtensions.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,8 +29,8 @@ namespace OneSignalSDK { public static class PBXProjectExtensions { -#if UNITY_2019_3_OR_NEWER - public static string GetMainTargetName(this PBXProject project) + #if UNITY_2019_3_OR_NEWER + public static string GetMainTargetName(this PBXProject project) => "Unity-iPhone"; public static string GetMainTargetGuid(this PBXProject project) @@ -38,7 +38,7 @@ public static string GetMainTargetGuid(this PBXProject project) public static string GetFrameworkGuid(this PBXProject project) => project.GetUnityFrameworkTargetGuid(); -#else + #else public static string GetMainTargetName(this PBXProject project) => PBXProject.GetUnityTargetName(); @@ -47,6 +47,6 @@ public static string GetMainTargetGuid(this PBXProject project) public static string GetFrameworkGuid(this PBXProject project) => GetPBXProjectTargetGuid(project); -#endif + #endif } } \ No newline at end of file diff --git a/com.onesignal.unity.ios/Runtime/AssemblyInfo.cs b/com.onesignal.unity.ios/Runtime/AssemblyInfo.cs index 3c6c83669..8e2ac3e05 100644 --- a/com.onesignal.unity.ios/Runtime/AssemblyInfo.cs +++ b/com.onesignal.unity.ios/Runtime/AssemblyInfo.cs @@ -1,3 +1,30 @@ -using UnityEngine.Scripting; +/* + * Modified MIT License + * + * Copyright 2022 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +using UnityEngine.Scripting; [assembly: AlwaysLinkAssembly] \ No newline at end of file diff --git a/com.onesignal.unity.ios/Runtime/OneSignalIOS.Callbacks.cs b/com.onesignal.unity.ios/Runtime/OneSignalIOS.Callbacks.cs index 366e0d86d..ccd1f0c3f 100644 --- a/com.onesignal.unity.ios/Runtime/OneSignalIOS.Callbacks.cs +++ b/com.onesignal.unity.ios/Runtime/OneSignalIOS.Callbacks.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -43,7 +43,7 @@ public sealed partial class OneSignalIOS : OneSignal { private static readonly Dictionary WaitingProxies = new Dictionary(); private static (Later proxy, int hashCode) _setupProxy() { - var proxy = new Later(); + var proxy = new Later(); var hashCode = proxy.GetHashCode(); WaitingProxies[hashCode] = proxy; return (proxy, hashCode); @@ -103,7 +103,7 @@ private static bool _onNotificationReceived(string response) { if (Json.Deserialize(response) is Dictionary notifDict && notifDict.ContainsKey("additionalData")) notification.additionalData = notifDict["additionalData"] as Dictionary; - var resultNotif = _instance.NotificationWillShow(notification); + var resultNotif = _instance.NotificationWillShow(notification); return resultNotif != null; } @@ -144,8 +144,8 @@ private static void _onPermissionStateChanged(string current, string previous) { return; } - var curr = (NotificationPermission) currState["status"]; - var prev = (NotificationPermission) prevState["status"]; + var curr = (NotificationPermission)currState["status"]; + var prev = (NotificationPermission)prevState["status"]; _instance.NotificationPermissionChanged?.Invoke(curr, prev); } diff --git a/com.onesignal.unity.ios/Runtime/OneSignalIOS.Interface.cs b/com.onesignal.unity.ios/Runtime/OneSignalIOS.Interface.cs index bd30fe229..4f303b55a 100644 --- a/com.onesignal.unity.ios/Runtime/OneSignalIOS.Interface.cs +++ b/com.onesignal.unity.ios/Runtime/OneSignalIOS.Interface.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.ios/Runtime/OneSignalIOS.cs b/com.onesignal.unity.ios/Runtime/OneSignalIOS.cs index fdaffc248..a11f1eefa 100644 --- a/com.onesignal.unity.ios/Runtime/OneSignalIOS.cs +++ b/com.onesignal.unity.ios/Runtime/OneSignalIOS.cs @@ -1,7 +1,7 @@ -/* +/* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.ios/Runtime/OneSignalIOSInit.cs b/com.onesignal.unity.ios/Runtime/OneSignalIOSInit.cs index ffbc08bff..637be35c8 100644 --- a/com.onesignal.unity.ios/Runtime/OneSignalIOSInit.cs +++ b/com.onesignal.unity.ios/Runtime/OneSignalIOSInit.cs @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/com.onesignal.unity.ios/Runtime/Plugins/iOS/OneSignalUnityBridge.mm b/com.onesignal.unity.ios/Runtime/Plugins/iOS/OneSignalUnityBridge.mm index 62468bdd9..8e105ffb4 100644 --- a/com.onesignal.unity.ios/Runtime/Plugins/iOS/OneSignalUnityBridge.mm +++ b/com.onesignal.unity.ios/Runtime/Plugins/iOS/OneSignalUnityBridge.mm @@ -1,7 +1,7 @@ /* * Modified MIT License * - * Copyright 2021 OneSignal + * Copyright 2022 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/composeRelease.sh b/composeRelease.sh index a93afcd82..eb01b6678 100755 --- a/composeRelease.sh +++ b/composeRelease.sh @@ -203,11 +203,11 @@ executeUnityMethod() { # update project version projectsettings_path="OneSignalExample/ProjectSettings/ProjectSettings.asset" -executeUnityMethod "OneSignalExample" "Android" "OneSignalPackagePublisher.UpdateProjectVersion" +executeUnityMethod "OneSignalExample" "Android" "OneSignalSDK.OneSignalPackagePublisher.UpdateProjectVersion" # build a unitypackage for release package_path="OneSignalExample/OneSignal-v${new_version}.unitypackage" -executeUnityMethod "OneSignalExample" "Android" "OneSignalPackagePublisher.ExportUnityPackage" +executeUnityMethod "OneSignalExample" "Android" "OneSignalSDK.OneSignalPackagePublisher.ExportUnityPackage" # preserve current workspace current_branch=$(git branch --show-current)