repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Core; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Windows.Settings.Pages.AllFeatures; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// The base class for all Feature pages displayed in the AWS GameKit Settings window. /// </summary> [Serializable] public abstract class FeaturePage : AllFeaturesPage { public static string DeploymentTabName => L10n.Tr("Deployment"); public static string TestingTabName => L10n.Tr("Testing"); public override string DisplayName => FeatureType.GetDisplayName(); /// <summary> /// The feature this page is for. /// </summary> public abstract FeatureType FeatureType { get; } [SerializeField] private TabWidget _tabViewWidget; /// <summary> /// Change the currently selected tab to the named tab. /// </summary> /// <remarks> /// If the named tab does not exist, then an Error will be logged and the page's currently selected tab will not change.<br/><br/> /// </remarks> /// <param name="tabName">The name of the tab to select. All <see cref="FeaturePage"/>'s should have tabs named <see cref="DeploymentTabName"/> and <see cref="TestingTabName"/> at minimum.</param> public override void SelectTab(string tabName) { _tabViewWidget.SelectTab(tabName); } /// <summary> /// Create a new FeaturePage with an arbitrary set of tabs. /// </summary> protected void Initialize(Tab[] tabs, SettingsDependencyContainer dependencies) { GUI.ToolbarButtonSize tabSelectorButtonSize = GUI.ToolbarButtonSize.FitToContents; _tabViewWidget.Initialize(tabs, tabSelectorButtonSize); base.Initialize(dependencies); } /// <summary> /// Get the default set of tabs that every <see cref="FeaturePage"/> should have. /// </summary> protected static Tab[] GetDefaultTabs(FeatureSettingsTab settingsTab, FeatureExamplesTab examplesTab) { return new Tab[] { CreateSettingsTab(settingsTab), CreateExamplesTab(examplesTab) }; } /// <summary> /// Create a <see cref="FeatureSettingsTab"/>. This should only be used during the constructor to build a <c>Tab[]</c> when not using <see cref="GetDefaultTabs"/>. /// </summary> protected static Tab CreateSettingsTab(FeatureSettingsTab settingsTab) { return new Tab(DeploymentTabName, settingsTab); } /// <summary> /// Create a <see cref="FeatureExamplesTab"/>. This should only be used during the constructor to build a <c>Tab[]</c> when not using <see cref="GetDefaultTabs"/>. /// </summary> protected static Tab CreateExamplesTab(FeatureExamplesTab examplesTab) { return new Tab(TestingTabName, examplesTab); } protected override void DrawContent() { // Feature Description EditorGUILayout.LabelField(FeatureType.GetDescription(withEndingPeriod: true), SettingsGUIStyles.FeaturePage.Description); // Tab View _tabViewWidget.OnGUI(SettingsGUIStyles.FeaturePage.TabSelector); } } }
98
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Linq; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Core; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Models.FeatureSettings; using AWS.GameKit.Editor.Utils; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// Base class for all feature settings tabs.<br/><br/> /// /// This tab lets users configure the feature's settings and create/redeploy/delete the feature and it's dashboard. /// </summary> [Serializable] public abstract class FeatureSettingsTab : IDrawable { private const string LEARN_MORE_TEXT = "Learn more about dashboards"; private const string CURRENT_VALUE = "CurrentValue"; private List<string> _resourceList; protected bool _isFeatureBeingProcessed = false; protected bool _isFeatureMainStackBeingRedeployed = false; /// <summary> /// A list of all features settings tabs that are initialized, used to create the short versions in All Features /// </summary> public static List<FeatureSettingsTab> FeatureSettingsTabsInstances = new List<FeatureSettingsTab>(); /// <summary> /// The feature which these settings are for. /// </summary> public abstract FeatureType FeatureType { get; } /// <summary> /// This feature's specific settings, excluding common settings such as dashboards. /// </summary> protected abstract IEnumerable<IFeatureSetting> FeatureSpecificSettings { get; } /// <summary> /// Any secrets that a feature may need to store such as password fields and secret keys. Secrets will be stored in AWS Secrets Manager. /// </summary> protected abstract IEnumerable<SecretSetting> FeatureSecrets { get; } /// <summary> /// Whether the <c>DrawSettings()</c> method should be called. If false, then a message saying "No feature settings" will be displayed in the settings section. /// </summary> protected virtual bool ShouldDrawSettingsSection() => true; /// <summary> /// Whether the feature allows reload of settings. /// </summary> protected virtual bool ShouldReloadFeatureSettings() => true; /// <summary> /// All of this feature's settings, including both feature-specific settings and common settings (such as dashboards). /// </summary> private IEnumerable<IFeatureSetting> AllFeatureSettings => CommonSettings.Concat(FeatureSpecificSettings); // Common Feature Settings private IEnumerable<IFeatureSetting> CommonSettings => new List<IFeatureSetting>() { _isDashboardEnabled }; [SerializeField] private FeatureSettingBool _isDashboardEnabled = new FeatureSettingBool("cloudwatch_dashboard_enabled", defaultValue: true); // State [SerializeField] private Vector2 _scrollPosition; private bool _isRefreshing; // Dependencies protected ICoreWrapperProvider _coreWrapper; private GameKitManager _gameKitManager; private GameKitEditorManager _gameKitEditorManager; private FeatureResourceManager _featureResourceManager; private FeatureDeploymentOrchestrator _featureDeploymentOrchestrator; protected SerializedProperty _serializedProperty; // Links private readonly LinkWidget _learnMoreAboutDashboardsDeployedLink = new LinkWidget(L10n.Tr("Active"), L10n.Tr(LEARN_MORE_TEXT), DocumentationURLs.CLOUDWATCH_DASHBOARDS_REFERENCE); private readonly LinkWidget _learnMoreAboutDashboardsUndeployedLink = new LinkWidget(L10n.Tr("Inactive"), L10n.Tr(LEARN_MORE_TEXT), DocumentationURLs.CLOUDWATCH_DASHBOARDS_REFERENCE, spaceAfterPrependedText: 10f); private readonly LinkWidget _learnMoreAboutDashboardsNoCredentialsLink = new LinkWidget(L10n.Tr("Enter valid environment and credentials to see dashboard status."), L10n.Tr(LEARN_MORE_TEXT), DocumentationURLs.CLOUDWATCH_DASHBOARDS_REFERENCE, spaceAfterPrependedText: 10f); public virtual void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { // Dependencies _coreWrapper = dependencies.CoreWrapper; _gameKitManager = dependencies.GameKitManager; _gameKitEditorManager = dependencies.GameKitEditorManager; _featureResourceManager = dependencies.FeatureResourceManager; _featureDeploymentOrchestrator = dependencies.FeatureDeploymentOrchestrator; _serializedProperty = serializedProperty; foreach (SecretSetting featureSecret in FeatureSecrets) { if (_coreWrapper.GameKitAccountCheckSecretExists(featureSecret.SecretIdentifier) == GameKitErrors.GAMEKIT_SUCCESS) { featureSecret.IsStoredInCloud = true; } } LoadFeatureSettings(false); if (!FeatureSettingsTabsInstances.Contains(this)) { FeatureSettingsTabsInstances.Add(this); } } public void ReloadFeatureSettings() { if (ShouldReloadFeatureSettings()) { LoadFeatureSettings(true); } } public void OnGUI() { using (EditorGUILayout.ScrollViewScope scrollView = new EditorGUILayout.ScrollViewScope(_scrollPosition)) { _scrollPosition = scrollView.scrollPosition; EditorGUILayoutElements.Description(L10n.Tr("Configure how you want this feature to function and create or redeploy the game backend."), indentationLevel: 0); EditorGUILayoutElements.SectionDivider(); if (ShouldDrawSettingsSection()) { EditorGUILayoutElements.SectionHeader(L10n.Tr("Configure")); DrawSettings(); } else { DrawNoSettingsToDisplay(); } } GUILayout.FlexibleSpace(); DrawFooter(); } /// <summary> /// Draw the settings for this feature. /// </summary> protected abstract void DrawSettings(); /// <summary> /// Display a GUI element to let the user know there are no settings to display for the current feature. /// </summary> private void DrawNoSettingsToDisplay() { GUILayout.FlexibleSpace(); EditorGUILayoutElements.SectionHeader(L10n.Tr("No feature settings"), 0, TextAnchor.MiddleCenter); GUIStyle centeredTextStyle = new GUIStyle("label"); centeredTextStyle.alignment = TextAnchor.MiddleCenter; EditorGUILayout.LabelField(L10n.Tr("This feature has no settings to configure."), centeredTextStyle); } private void DrawFooter() { EditorGUILayoutElements.SectionDivider(); EditorGUILayoutElements.SectionHeader(L10n.Tr("Deploy")); DrawDashboardDeployment(); EditorGUILayout.Space(15f); DrawFeatureDeployment(); EditorGUILayout.Space(15f); DrawFeatureDescription(); } private void DrawDashboardDeployment() { const string CLOUD_DEPLOY_STATE = "cloudwatch_dashboard_enabled"; bool isDashboardDeployed; Dictionary<string, string> settings = new Dictionary<string, string>(); if (_gameKitEditorManager.CredentialsSubmitted) { settings = _coreWrapper.SettingsGetFeatureVariables(FeatureType); } if (settings.ContainsKey(CLOUD_DEPLOY_STATE)) { string dashboardDeployed; settings.TryGetValue(CLOUD_DEPLOY_STATE, out dashboardDeployed); isDashboardDeployed = Boolean.Parse(dashboardDeployed); } else { isDashboardDeployed = false; } bool isDeployButtonEnabled = _featureDeploymentOrchestrator.CanCreateFeature(FeatureType).CanExecuteAction || _featureDeploymentOrchestrator.CanRedeployFeature(FeatureType).CanExecuteAction; // Dashboard status if (_gameKitEditorManager.CredentialsSubmitted) { if (isDashboardDeployed) { EditorGUILayoutElements.CustomField(L10n.Tr("Dashboard status"), () => { if (isDeployButtonEnabled) { EditorGUILayoutElements.DeploymentStatusIcon(FeatureStatus.Deployed); GetOpenDashboardLink().OnGUI(); EditorGUILayout.Space(20f); } _learnMoreAboutDashboardsDeployedLink.OnGUI(); }, indentationLevel: 0); } else { EditorGUILayoutElements.CustomField(L10n.Tr("Dashboard status"), () => { EditorGUILayoutElements.DeploymentStatusIcon(FeatureStatus.Undeployed); _learnMoreAboutDashboardsUndeployedLink.OnGUI(); }, indentationLevel: 0); } } else { EditorGUILayoutElements.CustomField(L10n.Tr("Dashboard status"), () => { EditorGUILayoutElements.DeploymentStatusIcon(FeatureStatus.Unknown); _learnMoreAboutDashboardsNoCredentialsLink.OnGUI(); }, indentationLevel: 0); } // Dashboard action using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel(L10n.Tr("Dashboard action"), indentationLevel: 0); EditorGUILayoutElements.KeepPreviousPrefixLabelEnabled(); DrawDashboardDeploymentButton(isDeployButtonEnabled, isDashboardDeployed); } } private IDrawable GetOpenDashboardLink() { // This LinkWidget needs to be created during OnGUI to make sure the dashboard URL matches the current environment. return new LinkWidget(L10n.Tr("Open Dashboard"), GetDashboardUrl(), new LinkWidget.Options() { // Remove the gap between this link and the "Learn more" link that comes after. // If either of these below options were removed, then there would be a large gap before the "Learn more" link. ShouldWordWrapLinkLabel = false, Alignment = LinkWidget.Alignment.None }); } private string GetDashboardUrl() { string gameName = _featureResourceManager.GetGameName(); string environmentCode = _featureResourceManager.GetLastUsedEnvironment(); string region = _featureResourceManager.GetLastUsedRegion(); return FeatureType.GetDashboardUrl(gameName, environmentCode, region); } private void DrawDashboardDeploymentButton(bool isButtonEnabled, bool isDashboardDeployed) { string buttonText = isDashboardDeployed ? L10n.Tr("Deactivate") : L10n.Tr("Activate"); Color buttonColor = isDashboardDeployed ? SettingsGUIStyles.Buttons.GUIButtonRed.Get() : SettingsGUIStyles.Buttons.GUIButtonGreen.Get(); Action clickFunction = isDashboardDeployed ? (Action)OnClickDashboardDeactivate : (Action)OnClickDashboardActivate; if (EditorGUILayoutElements.Button(buttonText, isButtonEnabled, colorWhenEnabled: buttonColor)) { clickFunction(); } } public FeatureStatus GetFeatureStatus() { FeatureStatus deploymentStatus = _featureDeploymentOrchestrator.GetFeatureStatus(FeatureType); // This ensures that we are not displaying status of Main Stack for another feature that is redeployed in parallel if( deploymentStatus == FeatureStatus.GeneratingTemplates || deploymentStatus == FeatureStatus.UploadingDashboards || deploymentStatus == FeatureStatus.UploadingLayers || deploymentStatus == FeatureStatus.UploadingFunctions || deploymentStatus == FeatureStatus.DeployingResources) { _isFeatureMainStackBeingRedeployed = false; } // Display deployment status for main stack if((_isFeatureBeingProcessed && deploymentStatus == FeatureStatus.Undeployed) || _isFeatureMainStackBeingRedeployed) { FeatureStatus mainStackStatus = _featureDeploymentOrchestrator.GetFeatureStatus(FeatureType.Main); if(mainStackStatus != FeatureStatus.Deployed) { deploymentStatus = mainStackStatus; } } return deploymentStatus; } private string AppendBlockingFeatures(string originalMessage, CanExecuteDeploymentActionResult result) { string features = string.Join(", ", result.BlockingFeatures.Select(f => f.GetDisplayName()).ToList()); return originalMessage + features; } private string DisabledDeploymentReasons(CanExecuteDeploymentActionResult result) { if (result.CanExecuteAction) { return string.Empty; } switch (result.Reason) { case DeploymentActionBlockedReason.CredentialsInvalid: return "Must submit valid credentials before this action is enabled"; case DeploymentActionBlockedReason.DependenciesMustBeCreated: return AppendBlockingFeatures("Must deploy these features first for this action to be enabled: ", result); case DeploymentActionBlockedReason.DependenciesMustBeDeleted: return AppendBlockingFeatures("Must delete these features first for this action to be enabled: ", result); case DeploymentActionBlockedReason.DependenciesStatusIsInvalid: return AppendBlockingFeatures("A feature this action depends on has an invalid status: ", result); case DeploymentActionBlockedReason.FeatureMustBeCreated: return "This feature must be created first for this action to be enabled."; case DeploymentActionBlockedReason.FeatureMustBeDeleted: return "This feature must be deleted first for this action to be enabled."; case DeploymentActionBlockedReason.FeatureStatusIsUnknown: return "The status of this feature cannot be determined, this action will be disabled until status is retrievable."; case DeploymentActionBlockedReason.OngoingDeployments: if (!result.BlockingFeatures.Contains(this.FeatureType)) { return AppendBlockingFeatures("This action is disabled while the following features are updating: ", result); } return "This action is disabled while any update is in progress for this feature."; case DeploymentActionBlockedReason.MainStackNotReady: return "This action is disabled while the Main stack is updating and not in a ready state"; default: return "Action is disabled for an unknown reason."; } } private void DrawFeatureDeployment() { // State FeatureStatus deploymentStatus = GetFeatureStatus(); CanExecuteDeploymentActionResult canCreate = _featureDeploymentOrchestrator.CanCreateFeature(FeatureType); CanExecuteDeploymentActionResult canRedeploy = _featureDeploymentOrchestrator.CanRedeployFeature(FeatureType); CanExecuteDeploymentActionResult canDelete = _featureDeploymentOrchestrator.CanDeleteFeature(FeatureType); // Deployment status if (_gameKitEditorManager.CredentialsSubmitted) { EditorGUILayoutElements.CustomField(L10n.Tr("Deployment status"), () => { EditorGUILayoutElements.DeploymentStatusIcon(deploymentStatus); GUILayout.Label(deploymentStatus.GetDisplayName(), CommonGUIStyles.DeploymentStatusText); if(EditorGUILayoutElements.DeploymentRefreshIconButton(_isRefreshing)) { OnClickFeatureRefresh(); } GUILayout.FlexibleSpace(); }, guiStyle: CommonGUIStyles.DeploymentStatus, indentationLevel: 0); } else { EditorGUILayoutElements.CustomField(L10n.Tr("Deployment status"), () => { EditorGUILayout.LabelField(L10n.Tr("No environment selected.")); }, indentationLevel: 0); } // AWS resource actions using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel(L10n.Tr("AWS resource actions"), indentationLevel: 0); EditorGUILayoutElements.KeepPreviousPrefixLabelEnabled(); if (EditorGUILayoutElements.Button(L10n.Tr("Create"), isEnabled: canCreate.CanExecuteAction && _gameKitEditorManager.CredentialsSubmitted, tooltip: DisabledDeploymentReasons(canCreate), colorWhenEnabled: SettingsGUIStyles.Buttons.GUIButtonGreen.Get())) { _isFeatureBeingProcessed = true; OnClickFeatureCreate(); } if (EditorGUILayoutElements.Button(L10n.Tr("Redeploy"), isEnabled: canRedeploy.CanExecuteAction && _gameKitEditorManager.CredentialsSubmitted, tooltip: DisabledDeploymentReasons(canRedeploy))) { _isFeatureMainStackBeingRedeployed = true; OnClickFeatureRedeploy(); } if (EditorGUILayoutElements.Button(L10n.Tr("Delete"), isEnabled: canDelete.CanExecuteAction && _gameKitEditorManager.CredentialsSubmitted, tooltip: DisabledDeploymentReasons(canDelete), colorWhenEnabled: SettingsGUIStyles.Buttons.GUIButtonRed.Get())) { _isFeatureBeingProcessed = true; OnClickFeatureDelete(); } } } private void DrawFeatureDescription() { using (new EditorGUILayout.VerticalScope()) { EditorGUILayoutElements.HelpBoxWithReadMore($"{FeatureType.GetVerboseDescription()} {L10n.Tr("Uses AWS services")}: {FeatureType.GetResourcesUIString()}", FeatureType.GetDocumentationUrl()); } } #region All Features summary public void DrawFeatureSummary() { // State FeatureStatus deploymentStatus = GetFeatureStatus(); CanExecuteDeploymentActionResult canCreate = _featureDeploymentOrchestrator.CanCreateFeature(FeatureType); CanExecuteDeploymentActionResult canRedeploy = _featureDeploymentOrchestrator.CanRedeployFeature(FeatureType); CanExecuteDeploymentActionResult canDelete = _featureDeploymentOrchestrator.CanDeleteFeature(FeatureType); using (new EditorGUILayout.HorizontalScope()) { // Deployment status if (_gameKitEditorManager.CredentialsSubmitted) { EditorGUILayoutElements.CustomField(L10n.Tr(FeatureType.GetDisplayName()), () => { EditorGUILayoutElements.DeploymentStatusIcon(deploymentStatus); GUILayout.Label(deploymentStatus.GetDisplayName()); GUILayout.FlexibleSpace(); }, indentationLevel: 0); } else { EditorGUILayoutElements.CustomField(L10n.Tr(FeatureType.GetDisplayName()), () => { EditorGUILayout.LabelField(L10n.Tr("No environment selected.")); }, indentationLevel: 0); } // AWS resource actions if (EditorGUILayoutElements.SmallButton(L10n.Tr("Create"), isEnabled: canCreate.CanExecuteAction && _gameKitEditorManager.CredentialsSubmitted, colorWhenEnabled: SettingsGUIStyles.Buttons.GUIButtonGreen.Get(), tooltip: DisabledDeploymentReasons(canCreate))) { _isFeatureBeingProcessed = true; OnClickFeatureCreate(); } if (EditorGUILayoutElements.SmallButton(L10n.Tr("Redeploy"), isEnabled: canRedeploy.CanExecuteAction && _gameKitEditorManager.CredentialsSubmitted, tooltip: DisabledDeploymentReasons(canRedeploy))) { _isFeatureMainStackBeingRedeployed = true; OnClickFeatureRedeploy(); } if (EditorGUILayoutElements.SmallButton(L10n.Tr("Delete"), isEnabled: canDelete.CanExecuteAction && _gameKitEditorManager.CredentialsSubmitted, colorWhenEnabled: SettingsGUIStyles.Buttons.GUIButtonRed.Get(), tooltip: DisabledDeploymentReasons(canDelete))) { _isFeatureBeingProcessed = true; OnClickFeatureDelete(); } } } #endregion #region Click Functions private void OnClickDashboardActivate() { _isDashboardEnabled.CurrentValue = true; OnToggleDashboard(); } private void OnClickDashboardDeactivate() { _isDashboardEnabled.CurrentValue = false; OnToggleDashboard(); } private void OnToggleDashboard() { if (_featureDeploymentOrchestrator.CanCreateFeature(FeatureType).CanExecuteAction) { OnClickFeatureCreate(); return; } if (_featureDeploymentOrchestrator.CanRedeployFeature(FeatureType).CanExecuteAction) { OnClickFeatureRedeploy(); return; } } /// <summary> /// Upon deployment or redeployment will save any enabled and non empty secret values, such as secret IDs, to AWS Secrets Manager /// </summary> protected void SaveSecretSettingsToCloud() { GUI.FocusControl(null); // Used to ensure that no secret ID inputs are selected. Clearing out the value of a selected field will not refresh it in the GUI if selected. foreach (SecretSetting featureSecret in FeatureSecrets) { if (!string.IsNullOrEmpty(featureSecret.SecretValue)) { if (_coreWrapper.GameKitAccountSaveSecret(featureSecret.SecretIdentifier, featureSecret.SecretValue) == GameKitErrors.GAMEKIT_SUCCESS) { featureSecret.IsStoredInCloud = true; featureSecret.SecretValue = string.Empty; } else { featureSecret.IsStoredInCloud = false; } } } } private void OnClickFeatureCreate() { SaveFeatureSettings(); SaveSecretSettingsToCloud(); _featureDeploymentOrchestrator.CreateFeature(FeatureType, (DeploymentResponseResult response) => { if (response.ResultCode == GameKitErrors.GAMEKIT_SUCCESS) { _gameKitManager.CopyAndReloadConfigFile(_featureResourceManager.GetGameName(), _featureResourceManager.GetLastUsedEnvironment()); } else { // Any errors are already logged by CreateFeature(). } _isFeatureBeingProcessed = false; }); } private void OnClickFeatureRedeploy() { SaveFeatureSettings(); SaveSecretSettingsToCloud(); _featureDeploymentOrchestrator.RedeployFeature(FeatureType, (DeploymentResponseResult response) => { if (response.ResultCode == GameKitErrors.GAMEKIT_SUCCESS) { _gameKitManager.CopyAndReloadConfigFile(_featureResourceManager.GetGameName(), _featureResourceManager.GetLastUsedEnvironment()); } else { // Any errors are already logged by RedeployFeature(). } // Reset the value when the feature stack deployment completes in either success or failure _isFeatureMainStackBeingRedeployed = false; }); } private void OnClickFeatureRefresh() { _isRefreshing = true; _featureDeploymentOrchestrator.RefreshFeatureStatuses((result => { // This API always returns GAMEKIT_SUCCESS _isRefreshing = false; _featureResourceManager.InitializeSettings(true); })); } private void OnClickFeatureDelete() { _resourceList = new List<string>(); _featureDeploymentOrchestrator.DescribeFeatureResources(FeatureType, (MultiResourceInfoCallbackResult result) => { for (int i = 0; i < result.LogicalResourceId.Length; i++) { _resourceList.Add(result.ResourceType[i] + " resource with id " + result.LogicalResourceId[i] + " in " + result.ResourceStatus[i] + " status.\n"); } // open UI to list the resources, confirm deletion with all the interactions there. DeleteFeatureWindow.ShowWindow(FeatureTypeConverter.GetDisplayName(FeatureType), _resourceList, ()=> { _featureDeploymentOrchestrator.DeleteFeature(FeatureType, (DeploymentResponseResult response) => { if (response.ResultCode == GameKitErrors.GAMEKIT_SUCCESS) { _isDashboardEnabled.CurrentValue = false; SaveFeatureSettings(); _gameKitManager.CopyAndReloadConfigFile(_featureResourceManager.GetGameName(), _featureResourceManager.GetLastUsedEnvironment()); } _isFeatureBeingProcessed = false; }); _isRefreshing = true; _featureDeploymentOrchestrator.RefreshFeatureStatuses((result => { // This API always returns GAMEKIT_SUCCESS _isRefreshing = false; _featureResourceManager.InitializeSettings(true); })); }); }); } #endregion /// <summary> /// Load all of this feature's settings from the saveInfo.yml file.<br/><br/> /// /// Set all of the feature's settings in memory to their value saved in the saveInfo.yml file (if the persisted values exist), otherwise leave them with their default values. /// </summary> private void LoadFeatureSettings(bool resetDefaultIfNotPersisted) { if (!_gameKitEditorManager.CredentialsSubmitted) { // There's no saveInfo.yml file to load. // Use the default settings for this feature. return; } foreach (IFeatureSetting featureSetting in AllFeatureSettings) { if (_featureResourceManager.TryGetFeatureVariable(FeatureType, featureSetting.VariableName, out string persistedValue)) { featureSetting.SetCurrentValueFromString(persistedValue); } else { // Use the default settings. // The featureSetting.CurrentValue was already set to the default value during the FeatureSetting's class constructor. // Reset explicitly to default if flag is set if (resetDefaultIfNotPersisted) { featureSetting.SetCurrentValueFromString(featureSetting.DefaultValueString); } } } } /// <summary> /// Save this feature's settings to the saveInfo.yml file. /// </summary> private void SaveFeatureSettings() { _featureResourceManager.SetFeatureVariables( AllFeatureSettings.Select(featureSetting => Tuple.Create(FeatureType, featureSetting.VariableName, featureSetting.CurrentValueString)), () => { }); } protected SerializedProperty GetFeatureSettingProperty(string settingName) { SerializedProperty settingProperty = _serializedProperty.FindPropertyRelative(settingName); return settingProperty.FindPropertyRelative(CURRENT_VALUE); } } }
695
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // System using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Windows.Settings { [Serializable] public abstract class GameKitExampleUI : IDrawable { public abstract string ApiName { get; } /// <summary> /// Set true by a feature examples when a response has been received for the first time. When true a response foldout will appear in the UI. Should be used in tandem with the <see cref="DrawOutput"/> method. /// </summary> public virtual bool ResponseReceived { get; set; } = false; /// <summary> /// Used to determine the state of the Response dropdown. Should be used in tandem with the <see cref="DrawOutput"/> method. /// </summary> public bool IsResponseDisplayed = false; public uint ResultCode { get => _resultCode; set { // External callers should be updating the result code after the API has been called; // use this opportunity to "complete" our request. _resultCode = value; _requestInProgress = false; ResponseReceived = true; IsResponseDisplayed = true; } } /// <summary> /// When true, a description of the example will be shown above the input section. /// </summary> protected virtual bool _shouldDisplayDescription { get; } = false; /// <summary> /// When true, a response section will show under the result code. Uses IsResponseDisplayed to determine handling the dropdown. /// </summary> protected virtual bool _shouldDisplayResponse { get; } = false; /// <summary> /// When true, a result section will be shown until the Call API button. /// </summary> protected virtual bool _shouldDisplayResult { get; } = true; // Allows us to use property fields for 'free' data bindings with the Undo system protected SerializedProperty _serializedProperty; private Action _onCallApi; // Purposefully non-serialized - we do not want to snapshot request status, as it could lead to a soft lock // in case the user closes the editor or recompiles when a request is in progress and it is never completed private bool _requestInProgress = false; [SerializeField] private bool _isExampleDisplayed = true; private uint _resultCode; public void Initialize(Action onCallApi, SerializedProperty serializedProperty) { _onCallApi = onCallApi; _serializedProperty = serializedProperty; } public void OnGUI() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleContainer)) { _isExampleDisplayed = EditorGUILayout.Foldout(_isExampleDisplayed, ApiName, SettingsGUIStyles.Page.FoldoutTitle); if (_isExampleDisplayed) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleFoldoutContainer)) { if (_shouldDisplayDescription) { DrawDescription(); EditorGUILayout.Space(5); } using (new EditorGUI.DisabledScope(_requestInProgress)) { DrawInput(); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel("Action", 0); if (GUILayout.Button(ApiName, SettingsGUIStyles.Buttons.CallExampleAPIButton, GUILayout.Width(SettingsGUIStyles.Buttons.CallExampleAPIButton .CalcSize(new GUIContent(ApiName)).x))) { // Mark request as "in progress" _resultCode = 0; _requestInProgress = true; // Hide the results from the last call ResponseReceived = false; IsResponseDisplayed = false; _onCallApi(); } } } if (_shouldDisplayResult) { using (new EditorGUI.DisabledGroupScope(true)) { EditorGUILayoutElements.LabelField(L10n.Tr("Result Code"), _requestInProgress ? L10n.Tr("In Progress...") : ResponseReceived ? GameKitErrorConverter.GetErrorName(_resultCode) : string.Empty, 0); } } if (_shouldDisplayResponse) { if (ResponseReceived) { IsResponseDisplayed = EditorGUILayout.Foldout(IsResponseDisplayed, L10n.Tr("Response"), SettingsGUIStyles.Page.FoldoutTitle); if (IsResponseDisplayed) { using (new EditorGUI.DisabledScope(false)) { using (new EditorGUILayout.VerticalScope()) { DrawOutput(); } } } } else { using (new EditorGUI.DisabledScope(true)) { EditorGUILayoutElements.LabelField(L10n.Tr("Response"), string.Empty, 0); } } } } } } } protected virtual void DrawDescription() { } protected virtual void DrawInput() { } protected virtual void DrawOutput() { } protected void PropertyField(string propertyPath, string label) { EditorGUILayoutElements.PropertyField(label, _serializedProperty.FindPropertyRelative(propertyPath), 0); } protected void PropertyField(string propertyPath) { EditorGUILayout.PropertyField(_serializedProperty.FindPropertyRelative(propertyPath), GUIContent.none); } } }
176
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor.IMGUI.Controls; namespace AWS.GameKit.Editor.Windows.Settings { public sealed class NavigationTreeItem : TreeViewItem { public Page Page { get; } public NavigationTreeItem(int id, int depth, Page page) : base(id, depth) { Page = page; displayName = page.DisplayName; } } }
20
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.Collections.Generic; // Unity using UnityEditor.IMGUI.Controls; using UnityEngine; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// A GUI element which displays a navigable "table of contents" for the AWS GameKit Settings window in a collapsible tree format. /// </summary> public sealed class NavigationTreeWidget : TreeView { public delegate void OnSingleClickedPage(Page selectedPage); private readonly OnSingleClickedPage _onSingleClickedPageCallback; private TreeViewItem _rootItem; private List<TreeViewItem> _treeViewItems; private readonly Dictionary<Page, int> _pageToItemIdMap = new Dictionary<Page, int>(); /// <summary> /// Create a new NavigationTreeWidget. /// </summary> /// <param name="allPages">All of the pages that can be navigated to.</param> /// <param name="treeViewState">The state to restore from. For example, which item was last selected, which items are collapsed/expanded, etc.</param> /// <param name="isBeingRestored">True if the treeViewState parameter is restoring the tree view from a saved state. False if the treeViewState is a new/default object.</param> /// <param name="onSingleClickedPageCallback">A callback function to invoke each time an item is single clicked.</param> public NavigationTreeWidget(AllPages allPages, TreeViewState treeViewState, bool isBeingRestored, OnSingleClickedPage onSingleClickedPageCallback) : base(treeViewState) { _onSingleClickedPageCallback = onSingleClickedPageCallback; BuildTreeViewItems(allPages); Reload(); if (isBeingRestored) { // Restore the last selected element IList<int> selectedIds = GetSelection(); SetSelection(selectedIds, TreeViewSelectionOptions.FireSelectionChanged); if (selectedIds.Count > 0) { // There should be exactly one item selected because CanMultiSelect() returns false, so select that item here: SingleClickedItem(selectedIds[0]); } } else { // Set the default initial view ExpandAll(); // Select the first item int startingPageId = 1; ClickItem(startingPageId); } } /// <summary> /// Simulate a mouse click on the page's item in the tree view. /// </summary> public void ClickItem(Page page) { int itemId; if (!_pageToItemIdMap.TryGetValue(page, out itemId)) { Debug.LogWarning($"There is no TreeViewItem corresponding to the pageType: {page}. Selecting the first page instead."); itemId = 1; } ClickItem(itemId); } protected override TreeViewItem BuildRoot() { SetupParentsAndChildrenFromDepths(_rootItem, _treeViewItems); return _rootItem; } protected override bool CanMultiSelect(TreeViewItem item) { return false; } /// <summary> /// Draw the row's text on the screen. This method is called once per visible row. /// </summary> protected override void RowGUI(RowGUIArgs args) { rowHeight = SettingsGUIStyles.NavigationTree.RowHeight; float indent = GetContentIndent(args.item); GUIStyle style = new GUIStyle(SettingsGUIStyles.NavigationTree.RowText) { contentOffset = new Vector2(indent, 0) }; GUI.Label(args.rowRect, args.label, style); } /// <summary> /// This callback function is invoked whenever an item is clicked in the tree view. /// </summary> protected override void SingleClickedItem(int selectedId) { base.SingleClickedItem(selectedId); // Invoke callback delegate with the clicked-on page NavigationTreeItem selectedItem = (NavigationTreeItem)FindItem(selectedId, _rootItem); _onSingleClickedPageCallback(selectedItem.Page); } /// <summary> /// Simulate a mouse click on the specified item in the tree view. /// </summary> private void ClickItem(int itemId) { // Highlight the clicked-on row FrameItem(itemId); SetSelection(new List<int> { itemId }, TreeViewSelectionOptions.FireSelectionChanged); // Invoke the callback delegate SingleClickedItem(itemId); } /// <summary> /// Define the order in which the pages are displayed in the collapsible navigation tree. /// </summary> private void BuildTreeViewItems(AllPages allPages) { int id = 0; _rootItem = new TreeViewItem { id = id, depth = -1, displayName = "Root" }; _treeViewItems = new List<TreeViewItem>() { // Before features: new NavigationTreeItem(++id, 0, allPages.EnvironmentAndCredentialsPage), new NavigationTreeItem(++id, 0, allPages.AllFeaturesPage), // Features: new NavigationTreeItem(++id, 1, allPages.IdentityAndAuthenticationPage), new NavigationTreeItem(++id, 1, allPages.GameStateCloudSavingPage), new NavigationTreeItem(++id, 1, allPages.AchievementsPage), new NavigationTreeItem(++id, 1, allPages.UserGameplayDataPage), // After features: new NavigationTreeItem(++id, 0, allPages.LogPage), }; foreach (TreeViewItem item in _treeViewItems) { NavigationTreeItem navigationItem = (NavigationTreeItem)item; _pageToItemIdMap.Add(navigationItem.Page, navigationItem.id); } } } }
162
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// The base class for all pages displayed in the AWS GameKit Settings window. /// </summary> [Serializable] public abstract class Page { /// <summary> /// The name to display for this page in the navigation tree, the page title, and elsewhere. /// </summary> public abstract string DisplayName { get; } /// <summary> /// Change the currently selected tab to the named tab. /// </summary> /// <remarks> /// If the named tab does not exist, then an Error will be logged and the page's currently selected tab will not change.<br/><br/> /// /// When overriding this method, do not call <c>base.SelectTab(tabName)</c>. /// </remarks> /// <param name="tabName">The name of the tab to select.</param> public virtual void SelectTab(string tabName) { Logging.LogError($"There is no tab named \"{tabName}\" on the page \"{GetType().Name}\". The page does not have any tabs."); } /// <summary> /// This method is called each time the page is switched to from another page. /// /// This method does nothing by default. It is not necessary to call `base.OnNavigatedTo()` when overriding this method. /// </summary> public virtual void OnNavigatedTo() { // empty call } /// <summary> /// This method is called each time the page is switched out with another page. /// /// This method does nothing by default. It is not necessary to call `base.OnNavigatedFrom()` when overriding this method. /// </summary> public virtual void OnNavigatedFrom() { // empty call } /// <summary> /// Draw the page's title and content. /// </summary> public void OnGUI() { DrawTitle(); GUILayout.Space(SettingsGUIStyles.Page.SpaceAfterTitle); DrawContent(); } /// <summary> /// Get the title of this page. /// /// By default the title is "{Environment} > {Region} > {GetTitleSuffix()}". /// </summary> protected virtual IList<string> GetTitle() { List<string> titleParts = new List<string>() { "Environment", "Region" }; titleParts.AddRange(GetTitleSuffix()); return titleParts; } /// <summary> /// Get the portion of this page's title that comes after the "{Environment} > {Region}" prefix. /// /// By default returns this page's DisplayName. /// </summary> protected virtual IList<string> GetTitleSuffix() { return new List<string>() { DisplayName }; } /// <summary> /// Draw the page's content, which is everything below the title. /// </summary> protected abstract void DrawContent(); protected virtual void DrawTitle() { GUIStyle titleStyle = SettingsGUIStyles.Page.Title; EditorGUILayout.LabelField(DisplayName, titleStyle); } } }
109
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// A GUI element which displays a page and handles transition logic when changing to a different page. /// </summary> public class PageContainerWidget { public Page CurrentPage { get; private set; } public void OnGUI() { if (CurrentPage != null) { CurrentPage.OnGUI(); } } public void ChangeTo(Page nextPage) { if (CurrentPage == nextPage) { return; } if (CurrentPage != null) { CurrentPage.OnNavigatedFrom(); } CurrentPage = nextPage; nextPage.OnNavigatedTo(); } public void CloseWindow() { if (CurrentPage != null) { CurrentPage.OnNavigatedFrom(); } } } }
46
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// This enum contains every page displayed in the AWS GameKit Settings window. /// </summary> public enum PageType { EnvironmentAndCredentialsPage, AllFeaturesPage, IdentityAndAuthenticationPage, GameStateCloudSavingPage, AchievementsPage, UserGameplayDataPage, LogPage, } }
20
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor; // GameKit using AWS.GameKit.Common; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// Creates the SettingsWindow and provides the rest of AWS GameKit with an interface to access the SettingsWindow. /// </summary> public class SettingsController { private readonly SettingsModel _model; private readonly SettingsDependencyContainer _dependencies; public SettingsController(SettingsDependencyContainer dependencies) { _dependencies = dependencies; // We Initialize() the model once all of its dependencies have finished bootstrapping, // which happens in the OnSettingsWindowEnabled() callback below. _model = SettingsModel.LoadFromDisk(GameKitPaths.Get().ASSETS_SETTINGS_WINDOW_STATE_RELATIVE_PATH); SettingsWindow.Enabled += OnSettingsWindowEnabled; } /// <summary> /// Give focus to the existing window instance, or create one if it doesn't exist. /// </summary> /// <returns>The existing or new window instance.</returns> public SettingsWindow GetOrCreateSettingsWindow() { return EditorWindow.GetWindow<SettingsWindow>(); } private void OnSettingsWindowEnabled(SettingsWindow enabledSettingsWindow) { _model.Initialize(_dependencies); enabledSettingsWindow.Initialize(_model); } } }
48
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEngine.Events; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Editor.AchievementsAdmin; using AWS.GameKit.Editor.Core; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Features.GameKitAchievements; using AWS.GameKit.Runtime.Features.GameKitGameSaving; using AWS.GameKit.Runtime.Features.GameKitIdentity; using AWS.GameKit.Runtime.Features.GameKitUserGameplayData; namespace AWS.GameKit.Editor.Windows.Settings { public struct SettingsDependencyContainer { // Editor public GameKitEditorManager GameKitEditorManager; public CredentialsManager CredentialsManager; // Runtime public GameKitManager GameKitManager; public ICoreWrapperProvider CoreWrapper; public IFileManager FileManager; // Feature management public FeatureResourceManager FeatureResourceManager; public FeatureDeploymentOrchestrator FeatureDeploymentOrchestrator; // Features public IAchievementsProvider Achievements; public IAchievementsAdminProvider AchievementsAdmin; public IGameSavingProvider GameSaving; public IIdentityProvider Identity; public IUserGameplayDataProvider UserGameplayData; // User State public UserInfo UserInfo; // Events public UnityEvent OnEnvironmentOrRegionChange; } }
48
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Utils; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// GUIStyles for the AWS GameKit Settings window. /// </summary> public static class SettingsGUIStyles { public static class Window { private const float _MIN_WIDTH = 800f; private const float _MIN_HEIGHT = 200f; public static readonly Vector2 MinSize = new Vector2(_MIN_WIDTH, _MIN_HEIGHT); private const float _INITIAL_WIDTH = _MIN_WIDTH; private const float _INITIAL_HEIGHT = 600f; public static readonly Vector2 InitialSize = new Vector2(_INITIAL_WIDTH, _INITIAL_HEIGHT); } public static class NavigationTree { public const float FIXED_WIDTH = 220f; public static readonly GUIStyle VerticalLayout = new GUIStyle() { fixedWidth = FIXED_WIDTH, margin = new RectOffset(0, 0, 8, 8) }; public static readonly float RowHeight = EditorGUIUtility.singleLineHeight; public static readonly GUIStyle RowText = new GUIStyle(EditorStyles.label) { // empty - alias for GUI.skin.label }; } public static class PageContainer { public static readonly GUIStyle VerticalLayout = new GUIStyle() { margin = new RectOffset(8, 8, 6, 6) }; } public static class Page { public static readonly GUIStyle FoldoutTitle = new GUIStyle(EditorStyles.foldout) { fontStyle = FontStyle.Bold }; public static readonly GUIStyle FoldoutBox = new GUIStyle() { margin = new RectOffset(10, 0, 0, 0) }; public static readonly GUIStyle VerticalLayout = new GUIStyle() { fixedWidth = 158 }; public static readonly GUIStyle PrefixLabelSubtext = new GUIStyle(EditorStyles.label) { fontSize = 10, padding = new RectOffset(18, 0, 0, 0), wordWrap = true }; public static readonly GUIStyle TextAreaSubtext = new GUIStyle(EditorStyles.label) { fontSize = 10, wordWrap = true }; public static readonly GUIStyle Paragraph = new GUIStyle(EditorStyles.label) { margin = new RectOffset(0, 0, 10, 10), richText = true, wordWrap = true }; public static readonly GUIStyle EnvDetails = new GUIStyle(EditorStyles.label) { margin = new RectOffset(0, 0, 0, 0), fontSize = 10, alignment = TextAnchor.UpperRight }; public static readonly GUIStyle CustomHelpBoxText = new GUIStyle(EditorStyles.label) { fontSize = 10, richText = true, wordWrap = true, padding = new RectOffset(0,0, 3,0) }; public static readonly GUIStyle Title = new GUIStyle(EditorStyles.label) { fontStyle = FontStyle.Bold, fontSize = GUI.skin.label.fontSize + 4, wordWrap = true }; public static readonly GUIStyle BannerBox = new GUIStyle(EditorStyles.helpBox) { margin = new RectOffset(0, 0, 0, 5) }; public static readonly GUIStyle BannerBoxLabel = new GUIStyle(Paragraph) { padding = new RectOffset(5, 0, 0, 0) }; public static readonly float SpaceAfterTitle = 4f; } public class Buttons { /// <summary> /// This is the minimum width all normal sized buttons should have to maintain a consistent look in the UI. /// </summary> public const float MIN_WIDTH_NORMAL = 100; /// <summary> /// This is the minimum width all small sized buttons should have to maintain a consistent look in the UI. /// </summary> public const float MIN_WIDTH_SMALL = 50; /// <summary> /// This is the left and right padding all normal sized buttons should have so the text doesn't look crowded if it fills up the button's whole width. /// </summary> public const int HORIZONTAL_PADDING_NORMAL = 12; /// <summary> /// This is the left and right padding all small sized buttons should have so the text doesn't look crowded if it fills up the button's whole width. /// </summary> public const int HORIZONTAL_PADDING_SMALL = 8; public static readonly GUILayoutOption MinWidth = GUILayout.MinWidth(MIN_WIDTH_NORMAL); public static readonly IGettable<Color> GUIButtonGreen = new EditorThemeAware<Color>( new Color(0.25f, 0.85f, 0.25f), new Color(0, 0.50f, 0)); public static readonly IGettable<Color> GUIButtonRed = new EditorThemeAware<Color>( new Color(1.0f, 0.25f, 0.25f), new Color(0.75f, 0, 0)); public static readonly GUIStyleState WhiteTextButtonNormal = new GUIStyleState() { background = GUI.skin.button.normal.background, scaledBackgrounds = GUI.skin.button.normal.scaledBackgrounds, textColor = Color.white }; public static readonly GUIStyleState WhiteTextButtonHovered = new GUIStyleState() { background = GUI.skin.button.hover.background, scaledBackgrounds = GUI.skin.button.hover.scaledBackgrounds, textColor = Color.white }; public static readonly GUIStyleState WhiteTextButtonActive = new GUIStyleState() { background = GUI.skin.button.active.background, scaledBackgrounds = GUI.skin.button.active.scaledBackgrounds, textColor = Color.white }; public static readonly GUIStyle WhiteTextButton = new GUIStyle(GUI.skin.button) { active = WhiteTextButtonActive, hover = WhiteTextButtonHovered, normal = WhiteTextButtonNormal, onFocused = WhiteTextButtonActive }; public static readonly GUIStyle ColoredButtonNormal = new GUIStyle(WhiteTextButton) { padding = new RectOffset(HORIZONTAL_PADDING_NORMAL, HORIZONTAL_PADDING_NORMAL, WhiteTextButton.padding.top, WhiteTextButton.padding.bottom), stretchWidth = false }; public static readonly GUIStyle GreyButtonNormal = new GUIStyle(GUI.skin.button) { padding = new RectOffset(HORIZONTAL_PADDING_NORMAL, HORIZONTAL_PADDING_NORMAL, GUI.skin.button.padding.top, GUI.skin.button.padding.bottom), stretchWidth = false }; public static readonly GUIStyle ColoredButtonSmall = new GUIStyle(WhiteTextButton) { padding = new RectOffset(HORIZONTAL_PADDING_SMALL, HORIZONTAL_PADDING_SMALL, WhiteTextButton.padding.top, WhiteTextButton.padding.bottom), stretchWidth = false }; public static readonly GUIStyle GreyButtonSmall = new GUIStyle(GUI.skin.button) { padding = new RectOffset(HORIZONTAL_PADDING_SMALL, HORIZONTAL_PADDING_SMALL, GUI.skin.button.padding.top, GUI.skin.button.padding.bottom), stretchWidth = false }; public static readonly GUIStyle CreateAccountButton = new GUIStyle(WhiteTextButton) { margin = new RectOffset(0, 0, 10, 10), padding = new RectOffset(20, 20, 3, 3), stretchWidth = false }; public static readonly GUIStyle SubmitCredentialsButton = new GUIStyle(GUI.skin.button) { stretchWidth = true, margin = new RectOffset(160, 10, GUI.skin.button.margin.top, GUI.skin.button.margin.bottom), fixedWidth = MIN_WIDTH_NORMAL }; public static readonly GUIStyle LocateConfigurationButton = new GUIStyle(GUI.skin.button) { richText = true, padding = new RectOffset(8, 8, GUI.skin.button.margin.top, GUI.skin.button.margin.bottom), alignment = TextAnchor.MiddleCenter }; public static readonly GUIStyle ChangeEnvironmentAndCredentialsButton = new GUIStyle(GUI.skin.button) { margin = new RectOffset(GUI.skin.button.margin.left, GUI.skin.button.margin.right, 10, GUI.skin.button.margin.bottom), }; public static readonly GUIStyle CallExampleAPIButton = new GUIStyle(GUI.skin.button) { margin = new RectOffset(5, GUI.skin.button.margin.right, GUI.skin.button.margin.top, GUI.skin.button.margin.bottom), padding = new RectOffset(8, 8, GUI.skin.button.margin.top, GUI.skin.button.margin.bottom) }; } public static class Tooltip { public static readonly GUIStyle Text = new GUIStyle(GUI.skin.box) { alignment = TextAnchor.UpperLeft }; } public static class EnvironmentAndCredentialsPage { public static readonly GUIStyle GetUserCredentialsLinkLayout = new GUIStyle() { margin = new RectOffset(160, 0, -5, 0) }; public static readonly GUIStyle CustomEnvironmentVerticalLayout = new GUIStyle() { margin = new RectOffset(175, 0, 0, 0), }; public static readonly GUIStyle CustomEnvironmentErrorVerticalLayout = new GUIStyle() { margin = new RectOffset(175, 0, 0, 10), }; public static readonly GUIStyle AccountCredentialsHelpBoxesVerticalLayout = new GUIStyle() { margin = new RectOffset(EditorStyles.textField.margin.left, EditorStyles.textField.margin.right, 5, 10) }; public static readonly float SpaceAfterAccountIdHelpBox = 10f; }; public static class FeaturePage { public static readonly GUIStyle Description = new GUIStyle(GUI.skin.label) { fontSize = GUI.skin.label.fontSize + 2, wordWrap = true }; public static readonly GUIStyle TabSelector = new GUIStyle("LargeButton") { margin = new RectOffset(0, 0, 8, 8) }; } public static class FeatureExamplesTab { public static float ResponsePrefixLabelWidth = 145; public static readonly GUIStyle ExampleContainer = new GUIStyle(EditorStyles.helpBox) { margin = new RectOffset(0, 0, 0, 5) }; public static readonly GUIStyle ExampleFoldoutContainer = new GUIStyle() { margin = new RectOffset(10, 0, 0, 0) }; public static readonly GUIStyle ExampleResponseInputAligned = new GUIStyle() { margin = new RectOffset(157, 0, 0, 0) }; public static readonly GUIStyle ExampleDictionaryInputAligned = new GUIStyle() { margin = new RectOffset(7, 0, 0, 0) }; public static readonly GUIStyle DictionaryKeyValues = new GUIStyle() { alignment = TextAnchor.MiddleLeft, stretchWidth = false, wordWrap = true }; } public static class Icons { public static readonly Texture InfoIcon = EditorGUIUtility.IconContent("console.infoicon.sml").image; public static readonly Texture WarnIcon = EditorGUIUtility.IconContent("console.warnicon.sml").image; public static readonly Texture ErrorIcon = EditorGUIUtility.IconContent("console.erroricon.sml").image; public static readonly Vector2 InsideButtonIconSize = new Vector2( CommonGUIStyles.INLINE_ICON_SIZE, CommonGUIStyles.INLINE_ICON_SIZE); public static readonly GUIStyle InlineIcons = new GUIStyle(GUIStyle.none) { fixedWidth = CommonGUIStyles.INLINE_ICON_SIZE, fixedHeight = CommonGUIStyles.INLINE_ICON_SIZE, contentOffset = new Vector2(0 ,4) }; public static readonly GUIStyle NormalSize = new GUIStyle() { fixedWidth = 18, fixedHeight = 18, margin = new RectOffset(5, 23, 5, 5) }; } public static class LogPage { public static readonly IGettable<Color> LogDarkColor = new EditorThemeAware<Color>( new Color(0.22f, 0.22f, 0.22f), new Color(0.75f, 0.75f, 0.75f)); public static readonly IGettable<Color> LogLightColor = new EditorThemeAware<Color>( new Color(0.25f, 0.25f, 0.25f), new Color(0.8f, 0.8f, 0.8f)); public static readonly IGettable<Color> LogErrorTextColor = new EditorThemeAware<Color>( new Color(0.9f, 0.2f, 0.2f), new Color(1, 0.1f, 0.1f)); public static readonly IGettable<Color> LogWarningTextColor = new EditorThemeAware<Color>( new Color(0.75f, 0.75f, 0), new Color(0.95f, 0.85f, 0.5f)); public static readonly IGettable<Color> LogInfoTextColor = new EditorThemeAware<Color>( new Color(0.9f, 0.9f, 0.9f), new Color(0, 0, 0)); public static readonly Texture2D DarkBackground = GUIEditorUtils.CreateBackground(SettingsGUIStyles.LogPage.LogDarkColor.Get()); public static readonly Texture2D LightBackground = GUIEditorUtils.CreateBackground(SettingsGUIStyles.LogPage.LogLightColor.Get()); public static readonly GUIStyle LogSection = new GUIStyle(EditorStyles.helpBox) { stretchHeight = true, margin = new RectOffset(0, 0, 0, 2) }; public static readonly GUIStyle LogBox = new GUIStyle(Page.VerticalLayout) { margin = new RectOffset(10, 10, 10, 15), fixedWidth = 0 }; public static readonly GUIStyle LogEntry = new GUIStyle(EditorStyles.label) { padding = new RectOffset(10, 10, 10, 10), margin = new RectOffset(0, 0, 0, 0), richText = true }; public static readonly GUIStyle ButtonLeft = new GUIStyle(GUI.skin.button) { margin = new RectOffset(GUI.skin.button.margin.left, 10, GUI.skin.button.margin.top, GUI.skin.button.margin.bottom) }; public static readonly GUIStyle ButtonRight = new GUIStyle(GUI.skin.button) { margin = new RectOffset(10, GUI.skin.button.margin.right, GUI.skin.button.margin.top, GUI.skin.button.margin.bottom) }; public static readonly GUIStyle GlobalSettingsSection = new GUIStyle() { margin = new RectOffset(0, 0, 0, 10), fixedHeight = 65 }; public static readonly GUIStyle LoggingLevel = new GUIStyle(EditorStyles.radioButton) { padding = new RectOffset(20, 20, 0, 0), margin = new RectOffset(0, 0, 5, 0) }; } public static class DeleteWindow { public const float MIN_SIZE_X = 750f; public const float MIN_SIZE_Y = 500f; const int LARGE_PADDING = 25; const int MEDIUM_PADDING = 15; const int SMALL_PADDING = 10; static RectOffset GENERIC_PADDING = new RectOffset(LARGE_PADDING, LARGE_PADDING, SMALL_PADDING, SMALL_PADDING); public static readonly GUIStyle ResourceDescriptionLine = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleLeft, padding = new RectOffset(SMALL_PADDING, SMALL_PADDING, SMALL_PADDING, 0), wordWrap = true, fontSize = 10, normal = new GUIStyleState() { textColor = LogPage.LogInfoTextColor.Get(), background = LogPage.LightBackground, } }; public static readonly GUIStyle GeneralText = new GUIStyle(EditorStyles.label) { margin = GENERIC_PADDING, wordWrap = true, }; public static readonly GUIStyle ResourceList = new GUIStyle() { margin = new RectOffset(LARGE_PADDING, MEDIUM_PADDING, MEDIUM_PADDING, 0) }; public static readonly GUIStyle FloatRight = new GUIStyle(EditorStyles.label) { margin = GENERIC_PADDING, wordWrap = true, alignment = TextAnchor.MiddleRight, }; public static readonly GUIStyle GeneralTextField = new GUIStyle(EditorStyles.textField) { margin = GENERIC_PADDING }; public static readonly GUIStyle ButtonMargins = new GUIStyle() { margin = GENERIC_PADDING }; } public static class Achievements { public const float SHORT_INPUT_WIDTH = 162; public const float DESCRIPTION_MIN_HEIGHT = 65; public const float DESCRIPTION_WIDTH = 400; public const int SPACING = 5; // These values are used for the size of each widget when collapsed or expanded public const int COLLAPSED_HEIGHT = 29; public const int EXPANDED_HEIGHT = 460; // Using a style with padding will not work for the header icon. The padding attribute does not account for tooltips public const int HEADER_ICON_HORIZONTAL_PADDING = 35; public const int HEADER_ICON_VERTICAL_PADDING = 3; public const int HEADER_ICON_WIDTH = 15; public const int HEADER_ICON_HEIGHT = 9; public static readonly GUIStyle BodyCollapsed = new GUIStyle(EditorStyles.helpBox) { stretchHeight = false, fixedHeight = COLLAPSED_HEIGHT, padding = new RectOffset(5, 0, 5, 5) }; public static readonly GUIStyle BodyExpanded = new GUIStyle(BodyCollapsed) { fixedHeight = 0, stretchHeight = true, }; public static readonly GUIStyle Header = new GUIStyle(EditorStyles.label) { fontStyle = FontStyle.Bold, padding = new RectOffset(-20, 0, 0, 0), }; public static readonly GUIStyle DeleteButton = new GUIStyle(GUI.skin.button) { padding = new RectOffset(2, 2, 2, 2), margin = new RectOffset(0, 5, 0, 0) }; public static readonly GUIStyle VisibilityLabel = new GUIStyle(CommonGUIStyles.SetIndentationLevel(CommonGUIStyles.InputLabel, 1)); public static readonly GUIStyle Expanded = new GUIStyle() { stretchHeight = true, padding = new RectOffset(0, 0, 10, 10) }; public static readonly GUIStyle Description = new GUIStyle(EditorStyles.textArea) { wordWrap = true, fixedWidth = DESCRIPTION_WIDTH }; public static readonly GUIStyle DescriptionLabel = new GUIStyle(CommonGUIStyles.InputLabel) { stretchHeight = true, alignment = TextAnchor.UpperLeft }; public static readonly GUIStyle ImageBody = new GUIStyle() { fixedWidth = 306 }; public static readonly GUIStyle ImageLabel = new GUIStyle(CommonGUIStyles.SetIndentationLevel(CommonGUIStyles.InputLabel, 1)) { stretchHeight = true, alignment = TextAnchor.UpperLeft }; public static readonly GUIStyle Image = new GUIStyle(EditorStyles.helpBox) { fixedHeight = 50, fixedWidth = 50, alignment = TextAnchor.MiddleCenter }; public static class GetLatestPopupWindow { private const float _MIN_WIDTH = 400f; private const float _MIN_HEIGHT = 100f; public static readonly Vector2 MinSize = new Vector2(_MIN_WIDTH, _MIN_HEIGHT); } } } }
558
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // System using System; // Unity using UnityEditor; using UnityEditor.IMGUI.Controls; // GameKit using AWS.GameKit.Editor.Utils; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// Contains all the data the SettingsWindow needs during construction. /// </summary> [Serializable] public class SettingsModel : PersistentScriptableObject<SettingsModel> { public AllPages AllPages; public SerializedObject SerializedObject; /// <summary> /// True if the AWS GameKit Settings window has been opened at least once in this project during any Unity session. /// </summary> public bool SettingsWindowHasEverBeenOpened; /// <summary> /// The currently selected navigation tree item and which items are collapsed/expanded. /// </summary> public TreeViewState NavigationTreeState; public void Initialize(SettingsDependencyContainer dependencies) { SerializedObject = new UnityEditor.SerializedObject(this); AllPages.Initialize(dependencies, SerializedObject.FindProperty(nameof(AllPages))); } } }
44
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEngine; // GameKit using AWS.GameKit.Editor.FileStructure; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Utils; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// Displays the Settings window and receives its UI events. /// </summary> public class SettingsWindow : EditorWindow { private const string WINDOW_TITLE = "AWS GameKit Settings"; private enum InitializationLevel { // Initialize() has not been called. // The GUI is empty and most public method calls are ignored (ex: OpenPage). Uninitialized, // Initialize() has been called, but some delayed setup will occur during the next OnGUI() call. // The GUI is empty and all public method calls are acted on. PartiallyInitialized, // Initialize() has been called and all setup is complete. // The GUI is drawn and all public method calls are acted on. FullyInitialized } // Data private SettingsModel _model; // State private InitializationLevel _initLevel = InitializationLevel.Uninitialized; // GUI Widgets private readonly PageContainerWidget _pageContainerWidget = new PageContainerWidget(); private NavigationTreeWidget _navigationTreeWidget; // Events public static event OnWindowEnabled Enabled; public delegate void OnWindowEnabled(SettingsWindow enabledSettingsWindow); /// <summary> /// Open the Settings window and navigate to the specified page. /// </summary> public static void OpenPage(PageType pageType) { SettingsWindow window = GetWindow<SettingsWindow>(); window.TryOpenPage(pageType); } /// <summary> /// Open the Settings window and navigate to the specified tab on the specified page. /// </summary> /// <remarks> /// If the specified tab does not exist on the page, then an Error will be logged and the page's currently selected tab will not change. The page will still be opened. /// </remarks> public static void OpenPageToTab(PageType pageType, string tabName) { SettingsWindow window = GetWindow<SettingsWindow>(); window.TryOpenPage(pageType, tabName); } /// <summary> /// Navigate to the specified page if the window is initialized. Then optionally change the selected tab. /// </summary> private void TryOpenPage(PageType pageType, string tabName = null) { if (_initLevel == InitializationLevel.Uninitialized) { return; } Page page = _model.AllPages.GetPage(pageType); // Open the page _navigationTreeWidget.ClickItem(page); // Select the tab if (!string.IsNullOrEmpty(tabName)) { page.SelectTab(tabName); } } private void OnNavigationTreeItemSelected(Page selectedPage) { _pageContainerWidget.ChangeTo(selectedPage); } private void OnEnable() { // Set title string windowTitle = WINDOW_TITLE; Texture windowIcon = EditorResources.Textures.WindowIcon.Get(); titleContent = new GUIContent(windowTitle, windowIcon); Enabled?.Invoke(this); } /// <summary> /// Initialize this window so it can start drawing the GUI and acting on public methods (ex: OpenPage). /// /// This is effectively the window's constructor. /// </summary> public void Initialize(SettingsModel model) { _model = model; bool isFirstTimeWindowHasEverBeenOpened = !_model.SettingsWindowHasEverBeenOpened; if (isFirstTimeWindowHasEverBeenOpened) { // Create new navigation tree _model.NavigationTreeState = new TreeViewState(); _navigationTreeWidget = new NavigationTreeWidget(_model.AllPages, _model.NavigationTreeState, false, OnNavigationTreeItemSelected); // Delay the rest of initialization until the first OnGUI call so the window's position is refreshed. // The position is (x=0, y=0) during the window's very first OnEnable() call ever (across all Unity sessions). // The position refreshes to the "real" value (near the center of the screen) after the first OnGUI() call. _initLevel = InitializationLevel.PartiallyInitialized; } else { // Restore navigation tree from the previous session _navigationTreeWidget = new NavigationTreeWidget(_model.AllPages, _model.NavigationTreeState, true, OnNavigationTreeItemSelected); // Set window bounds minSize = SettingsGUIStyles.Window.MinSize; _initLevel = InitializationLevel.FullyInitialized; } SettingsWindowUpdateController.AssignSettingsWindow(this); } /// <summary> /// Set the window's initial width & height. /// /// This only gets called the very first time the window is opened in this game project across all Unity sessions. /// After the first time, we let Unity automatically re-use the window's last size and position. /// /// This call needs to be delayed until at least one frame after the first OnGUI() call, /// otherwise the content may shift around when the window resizes. /// </summary> private void DelayedInitialize() { EditorWindowHelper.SetWindowSizeAndBounds(this, SettingsGUIStyles.Window.InitialSize, SettingsGUIStyles.Window.MinSize, maxSize); _model.SettingsWindowHasEverBeenOpened = true; _initLevel = InitializationLevel.FullyInitialized; } private void OnDisable() { _pageContainerWidget.CloseWindow(); } private void OnGUI() { if (!IsReadyToDrawGUI()) { if (_initLevel == InitializationLevel.PartiallyInitialized) { DelayedInitialize(); } GUILayout.Space(0f); return; } _model.SerializedObject.Update(); using (new EditorGUILayout.HorizontalScope()) { DrawNavigationTree(); EditorGUILayoutElements.VerticalDivider(); DrawPageContents(); } _model.SerializedObject.ApplyModifiedProperties(); } private bool IsReadyToDrawGUI() { return _initLevel == InitializationLevel.FullyInitialized; } private void DrawNavigationTree() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.NavigationTree.VerticalLayout)) { // The NavigationTreeWidget doesn't interact with EditorGUILayout.VerticalScope(), so we have to: // (1) manually specify the Rect for where to draw the tree: Vector2 topLeft = new Vector2( x: 0f, y: 0f ); Vector2 topLeftWithMargin = new Vector2( x: topLeft.x + SettingsGUIStyles.NavigationTree.VerticalLayout.margin.left, y: topLeft.y + SettingsGUIStyles.NavigationTree.VerticalLayout.margin.top ); Vector2 bottomRight = new Vector2( x: SettingsGUIStyles.NavigationTree.FIXED_WIDTH, y: position.height ); Vector2 bottomRightWithMargin = new Vector2( x: bottomRight.x - SettingsGUIStyles.NavigationTree.VerticalLayout.margin.right, y: bottomRight.y - SettingsGUIStyles.NavigationTree.VerticalLayout.margin.bottom ); Rect boxRect = new Rect(topLeftWithMargin, bottomRightWithMargin); _navigationTreeWidget.OnGUI(boxRect); // (2) add an empty GUI element to make the vertical group non-empty and therefore have a non-zero width: GUILayout.Space(0f); } } private void DrawPageContents() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.PageContainer.VerticalLayout, GUILayout.ExpandWidth(true))) { _pageContainerWidget.OnGUI(); } } } }
238
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Editor.Windows.Settings { public class UserInfo { public string UserName { get; set; } public string UserId { get; set; } public bool IsLoggedIn => !string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(UserId); } }
14
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Utils; using AWS.GameKit.Runtime.Features.GameKitIdentity; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// A GUI element which allows a user to log in to or log out from their GameKit Identity feature within the editor. /// </summary> [Serializable] public class UserLoginWidget : IDrawable { private Action _logoutDelegate; private IIdentityProvider _identity; private UserInfo _userInfo; private LinkWidget _createUserLink; private SerializedProperty _serializedProperty; [SerializeField] private string _userName; private string _password; private string _errorMessage; private bool _isRequestInProgress; public void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty, Action logoutDelegateMethod) { _identity = dependencies.Identity; _userInfo = dependencies.UserInfo; _serializedProperty = serializedProperty; _logoutDelegate = logoutDelegateMethod; _createUserLink = new LinkWidget(L10n.Tr("Register a new player in the Identity testing tab."), OpenIdentityTestingTab, new LinkWidget.Options { Alignment = LinkWidget.Alignment.Left, ShouldDrawExternalIcon = false }); } public void OnGUI() { if (_userInfo.IsLoggedIn) { DrawLogout(); } else { DrawLogin(); } } private void DrawLogout() { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.Description(L10n.Tr("Logged in as ") + $"<b>{_userInfo.UserName}</b>.", 0, TextAnchor.LowerLeft); GUILayout.FlexibleSpace(); if (EditorGUILayoutElements.Button(L10n.Tr("Log out"), isEnabled: !_isRequestInProgress)) { CallLogout(); } } } private void DrawLogin() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleContainer)) { EditorGUILayoutElements.Description(L10n.Tr("<b>Log in as a player:</b>"), 0); using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleFoldoutContainer)) { EditorGUILayoutElements.PropertyField("User Name", _serializedProperty.FindPropertyRelative(nameof(_userName)), 0); _password = EditorGUILayoutElements.PasswordField("Password", _password, 0); GUILayout.Space(2f); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.EmptyPrefixLabel(); string buttonText = _isRequestInProgress ? L10n.Tr("Loading...") : L10n.Tr("Log in"); if (EditorGUILayoutElements.Button(buttonText, isEnabled: !_isRequestInProgress)) { CallLogin(); } _createUserLink.OnGUI(); } GUILayout.Space(2f); DrawErrorText(); } } } private void DrawErrorText() { if (!string.IsNullOrEmpty(_errorMessage)) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.EmptyPrefixLabel(); EditorGUILayoutElements.ErrorText(_errorMessage, 0); } } } private void OpenIdentityTestingTab() { SettingsWindow.OpenPageToTab(PageType.IdentityAndAuthenticationPage, FeaturePage.TestingTabName); } private void CallLogin() { UserLogin userLogin = new UserLogin { UserName = _userName, Password = _password }; _errorMessage = string.Empty; _isRequestInProgress = true; _identity.Login(userLogin, (uint resultCode) => { _isRequestInProgress = false; if (resultCode != GameKitErrors.GAMEKIT_SUCCESS) { _errorMessage = $"Failed to log in - {GameKitErrorConverter.GetErrorName(resultCode)}"; Debug.LogError(_errorMessage); } else { _userInfo.UserName = _userName; _identity.GetUser((GetUserResult result) => { _userInfo.UserId = result.Response.UserId; if (result.ResultCode != GameKitErrors.GAMEKIT_SUCCESS) { Debug.LogError($"Identity.GetUser() completed with result code {result.ResultCode} and response {result.Response}. Calls made that require the logged in user's Id will fail."); return; } Debug.Log($"Identity.GetUser() completed successfully with the following response: {result.Response}"); }); } }); } private void CallLogout() { _isRequestInProgress = true; _identity.Logout((uint resultCode) => { _isRequestInProgress = false; if (resultCode != GameKitErrors.GAMEKIT_SUCCESS) { Debug.Log($"Failed to log out; removing session anyways - {GameKitErrorConverter.GetErrorName(resultCode)}"); } _userName = string.Empty; _password = string.Empty; _userInfo.UserName = string.Empty; _userInfo.UserId = string.Empty; // Used to clean up a feature after logout _logoutDelegate.Invoke(); }); } } }
190
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; // Unity using UnityEditor; using UnityEngine; using UnityEngine.Networking; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.AchievementsAdmin; using AWS.GameKit.Editor.Core; using AWS.GameKit.Editor.FileStructure; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Utils; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Features.GameKitAchievements; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; // Third Party using Newtonsoft.Json; using AchievementListResult = AWS.GameKit.Editor.AchievementsAdmin.AchievementListResult; using ListAchievementsDesc = AWS.GameKit.Editor.AchievementsAdmin.ListAchievementsDesc; namespace AWS.GameKit.Editor.Windows.Settings.Pages.Achievements { [Serializable] public class AchievementsDataTab : IDrawable { private const string SINGLE_SPACE = " "; private const string TEMPLATE_FILE_NAME = "achievements_template"; private const string DEFAULT_EXPORT_FILE_NAME = "GameKitAchievementsExport"; private const string TOOLTIP_MUST_FINISH_SYNCING_WITH_BACKEND = "Must finish syncing data with the cloud backend"; private const string TOOLTIP_MUST_FINISH_DEPLOYING = "The Achievements feature must finish deploying"; private const string TOOLTIP_ACHIEVEMENTS_MUST_SUCCESSFULLY_DEPLOY_PREFIX = "The Achievements feature must be successfully deployed"; private const string TOOLTIP_ACHIEVEMENTS_MUST_SUCCESSFULLY_DEPLOY_SUFFIX = "The feature's last deployment ended in an error."; private const string TOOLTIP_ACHIEVEMENTS_MUST_BE_CREATED = "The Achievements feature must be created"; private const string LOCKED_ICON_TYPE = "locked"; private const string UNLOCKED_ICON_TYPE = "unlocked"; private const float BUTTON_MINIMUM_SIZE = 50.0f; private readonly string TEMPLATE_FILE_ERROR = $"Error opening {TEMPLATE_FILE_NAME} file"; private readonly string IACHIEVEMENTS_ADMIN_PROVIDER_FILE_PATH = Path.Combine("Assets", "AWS GameKit", "Editor", "Scripts", "AchievementsAdmin", nameof(IAchievementsAdminProvider) + ".cs"); [SerializeField] private Vector2 _scrollPosition; [SerializeField] private Vector2 _achievementsScrollPosition; [SerializeField] private SerializablePropertyOrderedDictionary<string, AchievementWidget> _localAchievements; [SerializeField] private string _achievementIconsBaseUrl = string.Empty; [SerializeField] private bool _isShowingCloudSyncErrorBanner = false; [SerializeField] private bool _isDeletingAchievementsFromCloud = false; [SerializeField] private bool _isUploadingAchievementsToCloud = false; [SerializeField] private bool _isDownloadingAchievementsFromCloud = false; private bool _isDataBeingSyncedWithCloudBackend = false; private bool _isDeploying = false; private bool _isDeployed = false; private FeatureStatusSummary _featureStatus; private LinkWidget _getTemplateLink; // Dependencies private IAchievementsAdminProvider _achievementsAdmin; private FeatureDeploymentOrchestrator _featureDeploymentOrchestrator; private SerializedProperty _serializedProperty; private SerializedProperty _localAchievementsSerializedProperty; private GameKitEditorManager _gameKitEditorManager; private IFileManager _fileManager; public void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { // Dependencies _achievementsAdmin = dependencies.AchievementsAdmin; _featureDeploymentOrchestrator = dependencies.FeatureDeploymentOrchestrator; _serializedProperty = serializedProperty; _localAchievementsSerializedProperty = _serializedProperty.FindPropertyRelative($"{nameof(_localAchievements)}"); _gameKitEditorManager = dependencies.GameKitEditorManager; _fileManager = dependencies.FileManager; // State _localAchievements ??= new SerializablePropertyOrderedDictionary<string, AchievementWidget>(); _localAchievements.Initialize(_localAchievementsSerializedProperty); UpdateDeploymentState(); // Links _getTemplateLink = new LinkWidget(L10n.Tr("Get template"), OnClickGetTemplate, new LinkWidget.Options() { Tooltip = L10n.Tr("Open a JSON template in your text editor.") }); // Register with relevant events dependencies.OnEnvironmentOrRegionChange.AddListener(OnEnvironmentOrRegionChange); } #region GUI public void OnGUI() { // Must be called before DrawAddAchievementButton() and DrawAchievements() _localAchievements.FrameDelayedInitializeNewElements(); UpdateDeploymentState(); _isDataBeingSyncedWithCloudBackend = _isUploadingAchievementsToCloud || _isDeletingAchievementsFromCloud || _isDownloadingAchievementsFromCloud; using (EditorGUILayout.ScrollViewScope scrollView = new EditorGUILayout.ScrollViewScope(_scrollPosition)) { _scrollPosition = scrollView.scrollPosition; EditorGUILayoutElements.Description(L10n.Tr("Manage your game's achievement definitions and sync them to the backend."), indentationLevel: 0); EditorGUILayoutElements.SectionDivider(); if (_isShowingCloudSyncErrorBanner) { } using (new EditorGUI.DisabledScope(ShouldDisableGUI())) { using (new EditorGUILayout.HorizontalScope()) { DrawAddAchievementButton(); GUILayout.FlexibleSpace(); DrawCollapseButton(); DrawSortButton(); } DrawAchievements(); EditorGUILayoutElements.SectionDivider(); DrawLocalManagementFooter(); EditorGUILayoutElements.SectionDivider(); DrawCloudSyncFooter(); } } if (ShouldDisableGUI()) { EditorGUILayoutElements.DrawToolTip(L10n.Tr("To enable, please deploy the Achievements\nfeature using the Create button on Deployment tab.")); if (_localAchievements.Count > 0) { // If achievements is no longer deployed (or has not been) then clear any local achievements so that they are not propagated to another stack by mistake. _localAchievements.Clear(); } } } private void OnEnvironmentOrRegionChange() { _localAchievements.Clear(); } private void UpdateDeploymentState() { FeatureStatusSummary previousStatus = _featureStatus; _featureStatus = _featureDeploymentOrchestrator.GetFeatureStatusSummary(FeatureType.Achievements); _isDeploying = _featureDeploymentOrchestrator.IsFeatureDeploymentInProgress(FeatureType.Achievements); _isDeployed = _featureStatus == FeatureStatusSummary.Deployed; // If we are changing from an unknown state to knowing that achievements is deployed, then refresh the achievements. if (previousStatus == FeatureStatusSummary.Unknown && _isDeployed && !_isDeploying) { RefreshAchievementIconBaseUrl(); // Update the status of all achievements, add any missing, and remove any deleted SynchronizeAchievementsWithCloud(false); } } private bool ShouldDisableGUI() { return ((_featureStatus != FeatureStatusSummary.Unknown) && (!_isDeployed || _isDeploying)) || !_gameKitEditorManager.CredentialsSubmitted; } private void DrawAddAchievementButton() { bool isEnabled = AreLocalActionButtonsEnabled( enabledTooltip: L10n.Tr("Add a new local achievement."), actionDescription: L10n.Tr("a new local achievement can be added"), out string tooltip); // Wrap in single spaces so there's a space between "+" and "Add achievement". string text = SINGLE_SPACE + L10n.Tr("Add achievement") + SINGLE_SPACE; Texture image = EditorResources.Textures.SettingsWindow.PlusIcon.Get(); Vector2 imageSize = SettingsGUIStyles.Icons.InsideButtonIconSize; Color colorWhenEnabled = SettingsGUIStyles.Buttons.GUIButtonGreen.Get(); if (EditorGUILayoutElements.Button(text, isEnabled, tooltip, colorWhenEnabled, image, imageSize)) { OnClickAddAchievement(); } } private void DrawCollapseButton() { // Wrap in single spaces so there's a space between the icon and text. string text = SINGLE_SPACE + L10n.Tr("Collapse all") + SINGLE_SPACE; Texture image = EditorGUIUtility.IconContent("d_PlayButton@2x").image; Vector2 imageSize = SettingsGUIStyles.Icons.InsideButtonIconSize; if (EditorGUILayoutElements.Button(text, true, L10n.Tr("Click to collapse all achievements."), null, image, imageSize, BUTTON_MINIMUM_SIZE)) { foreach(AchievementWidget achievement in _localAchievements.Values) { achievement.CollapseWidget(); } } } private void DrawSortButton() { // Wrap in single spaces so there's a space between the icon and text. string text = SINGLE_SPACE + L10n.Tr("Apply sort") + SINGLE_SPACE; Texture image = EditorResources.Textures.FeatureStatusRefresh.Get(); Vector2 imageSize = SettingsGUIStyles.Icons.InsideButtonIconSize; if (EditorGUILayoutElements.Button(text, true, L10n.Tr("Click to sort achievements by their Sort Order followed by Title."), null, image, imageSize, BUTTON_MINIMUM_SIZE)) { // If an achievement's attribute (ex: Title) is selected when "Apply sort" is clicked, then after // achievements are sorted the selected attribute still holds the value of the previous achievement // in that position. It's value changes to the correct value once focus is dropped from that attribute. // We prevent this issue by dropping focus before achievements are sorted. GUI.FocusControl(null); _localAchievements.Sort((IEnumerable<KeyValuePair<string, AchievementWidget>> achievements) => { return achievements .OrderBy( achievement => achievement.Value.SortOrder ) .ThenBy( achievement => achievement.Value.Title ); } ); } } private void DrawAchievements() { bool achievementsAreEditable = AreLocalActionButtonsEnabled(string.Empty, string.Empty, out string unusedValue); using (EditorGUILayout.ScrollViewScope scrollView = new EditorGUILayout.ScrollViewScope(_achievementsScrollPosition)) { _achievementsScrollPosition = scrollView.scrollPosition; foreach (AchievementWidget achievement in _localAchievements.Values) { achievement.OnGUI(isEditable: achievementsAreEditable); } } } private void DrawLocalManagementFooter() { EditorGUILayoutElements.SectionHeaderWithDescription( title: L10n.Tr("Local achievement management"), description: L10n.Tr("Quickly configure and manage your Achievements locally using JSON") ); using (new EditorGUILayout.HorizontalScope()) { _getTemplateLink.OnGUI(); // Right-align the buttons GUILayout.FlexibleSpace(); DrawExportButton(); DrawImportButton(); } } private void DrawExportButton() { bool isEnabled = AreLocalActionButtonsEnabled( enabledTooltip: L10n.Tr("Export your local achievements to a JSON file."), actionDescription: L10n.Tr("local achievements can be exported to a JSON file"), out string tooltip); Color green = SettingsGUIStyles.Buttons.GUIButtonGreen.Get(); if (EditorGUILayoutElements.Button(L10n.Tr("Export to local file"), isEnabled, tooltip, green)) { OnClickExport(); } } private void DrawImportButton() { bool isEnabled = AreLocalActionButtonsEnabled( enabledTooltip: L10n.Tr("Add achievements from a JSON file to your local achievements, overwriting any achievements with the same ID."), actionDescription: L10n.Tr("achievements can be imported from a JSON file"), out string tooltip); if (EditorGUILayoutElements.Button(L10n.Tr("Import from local file"), isEnabled, tooltip)) { OnClickImport(); } } private void DrawCloudSyncFooter() { EditorGUILayoutElements.SectionHeaderWithDescription( title: L10n.Tr("Cloud Sync"), description: L10n.Tr("To upload new achievement data to the cloud, choose Save Data. To download saved achievement data to your local machine, choose Get Latest.") ); using (new EditorGUILayout.HorizontalScope()) { // Right-align the buttons GUILayout.FlexibleSpace(); DrawSaveDataButton(); DrawGetLatestButton(); } } private void DrawSaveDataButton() { bool isEnabled = AreCloudActionButtonsEnabled( enabledTooltip: L10n.Tr("Make the cloud match your local achievements."), actionDescription: L10n.Tr("achievements can be saved to your cloud backend"), out string tooltip); string buttonText = _isUploadingAchievementsToCloud || _isDeletingAchievementsFromCloud ? L10n.Tr("Saving...") : L10n.Tr("Save data"); Color green = SettingsGUIStyles.Buttons.GUIButtonGreen.Get(); if (EditorGUILayoutElements.Button(buttonText, isEnabled, tooltip, green)) { OnClickSaveData(); } } private void DrawGetLatestButton() { bool isEnabled = AreCloudActionButtonsEnabled( enabledTooltip: L10n.Tr("Replace your local achievements with ones from the cloud, or merge in cloud achievements without overwriting any local ones."), actionDescription: L10n.Tr("achievements can be downloaded from your cloud backend"), out string tooltip); string buttonText = _isDownloadingAchievementsFromCloud ? L10n.Tr("Downloading...") : L10n.Tr("Get latest"); if (EditorGUILayoutElements.Button(buttonText, isEnabled, tooltip)) { OnClickGetLatest(); } } /// <summary> /// Return true if buttons that trigger local operations (i.e. no cloud operations) are enabled, false if disabled. /// </summary> /// <param name="enabledTooltip">The tooltip the button should display when it is enabled.</param> /// <param name="actionDescription">A description of what action the button takes. Is used for the disabled tooltip.</param> /// <param name="tooltip">When this method returns, contains the tooltip that should be displayed for this button. This parameter is passed in uninitialized.</param> /// <returns>True if the button should be enabled, false if disabled.</returns> private bool AreLocalActionButtonsEnabled(string enabledTooltip, string actionDescription, out string tooltip) { bool isEnabled = !_isDataBeingSyncedWithCloudBackend; tooltip = isEnabled ? enabledTooltip : L10n.Tr($"{TOOLTIP_MUST_FINISH_SYNCING_WITH_BACKEND} before {actionDescription}."); return isEnabled; } /// <summary> /// Return true if buttons that trigger cloud operations are enabled, false if disabled. /// </summary> /// <param name="enabledTooltip">The tooltip the button should display when it is enabled.</param> /// <param name="actionDescription">A description of what action the button takes. Is used for the disabled tooltip.</param> /// <param name="tooltip">When this method returns, contains the tooltip that should be displayed for this button. This parameter is passed in uninitialized.</param> /// <returns>True if the button should be enabled, false if disabled.</returns> private bool AreCloudActionButtonsEnabled(string enabledTooltip, string actionDescription, out string tooltip) { bool isEnabled = _isDeployed && !_isDeploying && !_isDataBeingSyncedWithCloudBackend; tooltip = enabledTooltip; if (!isEnabled) { if (_isDataBeingSyncedWithCloudBackend) { tooltip = L10n.Tr($"{TOOLTIP_MUST_FINISH_SYNCING_WITH_BACKEND} before {actionDescription}."); } else if (_isDeploying) { tooltip = L10n.Tr($"{TOOLTIP_MUST_FINISH_DEPLOYING} before {actionDescription}."); } else { switch (_featureStatus) { case FeatureStatusSummary.Running: tooltip = L10n.Tr($"{TOOLTIP_MUST_FINISH_DEPLOYING} before {actionDescription}."); break; case FeatureStatusSummary.Error: tooltip = L10n.Tr($"{TOOLTIP_ACHIEVEMENTS_MUST_SUCCESSFULLY_DEPLOY_PREFIX} before {actionDescription}. {TOOLTIP_ACHIEVEMENTS_MUST_SUCCESSFULLY_DEPLOY_SUFFIX}"); break; case FeatureStatusSummary.Undeployed: // fall-through case FeatureStatusSummary.Unknown: // fall-through default: tooltip = L10n.Tr($"{TOOLTIP_ACHIEVEMENTS_MUST_BE_CREATED} before {actionDescription}."); break; } } } return isEnabled; } #endregion #region Click Functions private void OnClickAddAchievement() { string guid = System.Guid.NewGuid().ToString().Replace('-','_'); int sortOrder = AchievementWidget.SORT_MIN; if (_localAchievements.Values.Any()) { sortOrder = _localAchievements.Values.Max(existingAchievement => existingAchievement.SortOrder) + 1; } AchievementWidget achievement = new AchievementWidget() { Id = guid, Title = $"New Achievement {guid}", SortOrder = sortOrder }; AddLocalAchievement(achievement); } private void OnClickGetTemplate() { string templatePath = ExportListOfAchievements(new List<Achievement>() { new Achievement() }, L10n.Tr("Select or enter the filename to save the template to"), TEMPLATE_FILE_NAME); if (string.IsNullOrEmpty(templatePath)) { // this case will happen if the user hits cancel on the SaveFilePanel, this is a normal case return; } if (File.Exists(templatePath)) { try { if (Process.Start(templatePath) == null) { Logging.LogError(L10n.Tr(TEMPLATE_FILE_ERROR)); } } catch (Exception e) { Logging.LogError(L10n.Tr($"{TEMPLATE_FILE_ERROR}: {e}")); } } else { Logging.LogError(L10n.Tr($"{templatePath} file not found")); } } private void OnClickExport() { // convert the list of AchievementWidgets to a list of Achievements while ignoring any that are marked for deletion List<Achievement> listOfAchievements = ( from achievementWidget in _localAchievements.Values where achievementWidget.IsMarkedForDeletion == false select (Achievement)achievementWidget ).ToList(); if (listOfAchievements.Count == 0) { Logging.LogInfo(L10n.Tr("There are no achievements to export.")); return; } ExportListOfAchievements(listOfAchievements, L10n.Tr("Select or enter a filename to export achievements to"), DEFAULT_EXPORT_FILE_NAME); } private void OnClickImport() { // Ask for the file to open string file = EditorUtility.OpenFilePanel(L10n.Tr("Select a file to import achievements from"), string.Empty, "json"); if (string.IsNullOrEmpty(file)) { // this case will happen if the user hits cancel on the OpenFilePanel, this is a normal case return; } // read in the file as a string string toImport = File.ReadAllText(file); if (string.IsNullOrEmpty(toImport)) { Logging.LogWarning(L10n.Tr($"File {file} was empty")); return; } // convert the imported json to a list of achievements List<Achievement> listOfAchievements; try { listOfAchievements = JsonConvert.DeserializeObject<List<Achievement>>(toImport); } catch (Exception e) { Logging.LogError(L10n.Tr($"Unable to deserialize the JSON file {file} into a list of achievements. Please check the file for JSON syntax errors.: {e}")); return; } // Add or update achievements uint newAchievements = 0; uint updatedAchievements = 0; uint restoredAchievements = 0; listOfAchievements.ForEach(a => AddLocalAchievement(a, ref newAchievements, ref updatedAchievements, ref restoredAchievements)); Logging.LogInfo(L10n.Tr($"{listOfAchievements.Count} achievement(s) imported from {file}, adding {newAchievements} new achievement(s), overwriting {updatedAchievements} existing achievement(s), and restored {restoredAchievements} achievement(s).")); // update the sync status SynchronizeAchievementsWithCloud(false); } /// <summary> /// Upload all of the user's local achievements to the cloud, and delete achievements from the cloud which were locally marked for deletion. /// </summary> private void OnClickSaveData() { _isShowingCloudSyncErrorBanner = false; DeleteAllMarkedAchievements(); UploadAllLocalAchievements(); } /// <summary> /// Delete all the marked achievements from the cloud and locally. /// </summary> private void DeleteAllMarkedAchievements() { AchievementWidget[] achievementsToDelete = _localAchievements.Values .Where( achievement => !string.IsNullOrEmpty(achievement.Id) && achievement.IsMarkedForDeletion ) .ToArray(); string[] achievementIdsToDelete = achievementsToDelete .Select( achievement => achievement.Id ) .ToArray(); if (achievementsToDelete.Length == 0) { Logging.LogInfo($"There are no local achievements marked for deletion. No achievements have been deleted from the cloud."); return; } string achievementTitles = StringHelper.MakeCommaSeparatedList(achievementsToDelete .Select( achievement => achievement.Title )); Logging.LogInfo($"Deleting {achievementsToDelete.Length} achievement(s) from the cloud: {achievementTitles}"); _isDeletingAchievementsFromCloud = true; DeleteAchievementsDesc deleteAchievementsRequest = new DeleteAchievementsDesc() { AchievementIdentifiers = achievementIdsToDelete, BatchSize = (uint)achievementIdsToDelete.Length }; _achievementsAdmin.DeleteAchievementsForGame(deleteAchievementsRequest, (uint resultCode) => { if (resultCode == GameKitErrors.GAMEKIT_SUCCESS) { foreach (AchievementWidget achievement in achievementsToDelete) { _localAchievements.Remove(achievement.Id); } Logging.LogInfo($"Finished deleting {achievementsToDelete.Length} achievement(s) from the cloud."); } else { string errorMessage = $"Failed to delete the following achievement(s) from your game: {achievementTitles}."; string apiName = nameof(IAchievementsAdminProvider.DeleteAchievementsForGame); HandleFailedCloudApiCall(resultCode, errorMessage, apiName); } _isDeletingAchievementsFromCloud = false; }); } /// <summary> /// Upload all local achievements to the cloud which are not marked for deletion. /// </summary> private void UploadAllLocalAchievements() { AchievementWidget[] achievementsToAdd = _localAchievements.Values .Where( achievement => !string.IsNullOrEmpty(achievement.Id) && !achievement.IsMarkedForDeletion && achievement.SyncStatus != SyncStatus.Synchronized ) .ToArray(); AdminAchievement[] adminAchievementsToAdd = achievementsToAdd .Select( achievement => (AdminAchievement)achievement ) .ToArray(); if (achievementsToAdd.Length == 0) { Logging.LogInfo($"There are no local achievements defined. No local achievements have been uploaded to the cloud."); return; } string achievementTitles = StringHelper.MakeCommaSeparatedList(achievementsToAdd .Select( achievement => achievement.Title )); Logging.LogInfo($"Saving {achievementsToAdd.Length} achievements to the cloud: {achievementTitles}"); _isUploadingAchievementsToCloud = true; AddAchievementDesc addAchievementsRequest = new AddAchievementDesc() { Achievements = adminAchievementsToAdd, BatchSize = (uint)achievementsToAdd.Length }; _achievementsAdmin.AddAchievementsForGame(addAchievementsRequest, (uint resultCode) => { if (resultCode == GameKitErrors.GAMEKIT_SUCCESS) { SynchronizeAchievementsWithCloud(false, true); Logging.LogInfo($"Finished saving {achievementsToAdd.Length} achievements to the cloud."); } else { string errorMessage = $"Failed to upload the following achievements for your game: {achievementTitles}."; string apiName = nameof(IAchievementsAdminProvider.AddAchievementsForGame); HandleFailedCloudApiCall(resultCode, errorMessage, apiName); } _isUploadingAchievementsToCloud = false; }); } private void OnClickGetLatest() { GetLatestPopupWindow.CreatePopupWindow( onClickAddMissing: () => { SynchronizeAchievementsWithCloud(false); }, onClickReplaceAll: () => { SynchronizeAchievementsWithCloud(true); } ); } private void SynchronizeAchievementsWithCloud(bool shouldReplaceAllLocal, bool replaceIconPaths = false) { // Clear the error because we are attempting a new cloud API call _isShowingCloudSyncErrorBanner = false; _isDownloadingAchievementsFromCloud = true; ListAchievementsDesc listAchievementsRequest = new ListAchievementsDesc() { WaitForAllPages = true }; AdminAchievement[] cloudAchievements = new AdminAchievement[]{ }; Logging.LogInfo($"Downloading achievements from the cloud."); _achievementsAdmin.ListAchievementsForGame(listAchievementsRequest, callback: (AchievementListResult result) => { cloudAchievements = result.Achievements; }, onCompleteCallback: (uint resultCode) => { if (resultCode == GameKitErrors.GAMEKIT_SUCCESS) { if (shouldReplaceAllLocal) { _localAchievements.Clear(); Logging.LogInfo("Deleted all local achievements."); } foreach (AchievementWidget localAchievement in _localAchievements.Values) { // if the achievement has not been explicitly marked as Unsynchronized, meaning it was recently added or edited, then mark as Unknown because we don't know the actual status if (localAchievement.SyncStatus != SyncStatus.Unsynchronized) { localAchievement.SyncStatus = SyncStatus.Unknown; } localAchievement.IsMarkedForDeletion = false; } if (cloudAchievements.Length == 0) { Logging.LogInfo("There are no achievements defined in the cloud for your game."); } else { Logging.LogInfo($"Downloaded {cloudAchievements.Length} achievement(s) from the cloud."); int numAlreadyExistingAchievements = 0; int numCloudOnlyAchievements = 0; for (int i = 0; i < cloudAchievements.Length; ++i) { string lockedIconUrlSuffix; string unlockedIconUrlSuffix; cloudAchievements[i].LockedIcon = UpdateIconPath(cloudAchievements[i].LockedIcon, out lockedIconUrlSuffix); cloudAchievements[i].UnlockedIcon = UpdateIconPath(cloudAchievements[i].UnlockedIcon, out unlockedIconUrlSuffix); if (_localAchievements.ContainsKey(cloudAchievements[i].AchievementId)) { ++numAlreadyExistingAchievements; // Find and assign a reference to the local achievement. AchievementWidget localAchievement = _localAchievements.GetValue(cloudAchievements[i].AchievementId); if (replaceIconPaths) { localAchievement.IconPathLocked = cloudAchievements[i].LockedIcon; localAchievement.IconPathUnlocked = cloudAchievements[i].UnlockedIcon; } if (AchievementWidget.AreSame(localAchievement, cloudAchievements[i])) { localAchievement.SyncStatus = SyncStatus.Synchronized; DownloadIcons(lockedIconUrlSuffix, cloudAchievements[i].LockedIcon, LOCKED_ICON_TYPE, localAchievement); DownloadIcons(unlockedIconUrlSuffix, cloudAchievements[i].UnlockedIcon, UNLOCKED_ICON_TYPE, localAchievement); } else { localAchievement.SyncStatus = SyncStatus.Unsynchronized; } } else { ++numCloudOnlyAchievements; // Convert the AdminAchievement to a AchievementWidget and add it to the list of local achievements. AchievementWidget localAchievement = cloudAchievements[i]; localAchievement.SyncStatus = SyncStatus.Synchronized; DownloadIcons(lockedIconUrlSuffix, localAchievement.IconPathLocked, LOCKED_ICON_TYPE, localAchievement); DownloadIcons(unlockedIconUrlSuffix, localAchievement.IconPathUnlocked, UNLOCKED_ICON_TYPE, localAchievement); AddLocalAchievement(localAchievement); } } if (!shouldReplaceAllLocal) { Logging.LogInfo($"Updated the synchronization status of {numAlreadyExistingAchievements} existing local achievement(s)."); } Logging.LogInfo($"Added {numCloudOnlyAchievements} new local achievement(s) retrieved from the cloud."); } // run through local achievements one last time, any that are still marked as "unknown" status are ones that did not exist on the cloud and are not new/edited, so delete foreach (AchievementWidget localAchievement in _localAchievements.Values) { if (localAchievement.SyncStatus == SyncStatus.Unknown) { localAchievement.IsMarkedForDeletion = true; } } } else { string errorMessage = $"Failed to download achievements from the cloud."; string apiName = nameof(IAchievementsAdminProvider.ListAchievementsForGame); HandleFailedCloudApiCall(resultCode, errorMessage, apiName); } _isDownloadingAchievementsFromCloud = false; } ); } private string UpdateIconPath(string icon, out string iconUrlSuffix) { iconUrlSuffix = string.Empty; if (!string.IsNullOrEmpty(icon)) { try { iconUrlSuffix = icon.Substring(icon.LastIndexOf("icons")); } catch (ArgumentOutOfRangeException) { Logging.LogError($"Icon S3 key not valid: Icon Path = {icon}"); return string.Empty; } return Path.Combine(GameKitPaths.Get().ASSETS_GAMEKIT_ART_PATH, iconUrlSuffix).Replace("\\", "/"); } return string.Empty; } /// <summary> /// Download achievement icons. /// </summary> /// <param name="iconS3Key">S3 key of the icon.</param> /// <param name="downloadPath">Local download path of the icon.</param> /// <param name="iconType">The icon type refers to its purpose, is it locked or unlocked, etc.</param> /// <param name="localAchievement">The widget that the icon is rendered with.</param> private async void DownloadIcons(string iconS3Key, string downloadPath, string iconType, AchievementWidget localAchievement) { if (!string.IsNullOrEmpty(iconS3Key) && !string.IsNullOrEmpty(downloadPath)) { // Delete the current local copy of the icon (and its meta file). The new icon will have a different and unique name. string[] files = _fileManager.ListFiles(GameKitPaths.Get().ASSETS_GAMEKIT_ICONS_PATH, $"{localAchievement.Id}_{iconType}*"); if (files.Length > 0) { foreach(string file in files) { try { _fileManager.DeleteFile(file); } catch (Exception e) { // If we fail to delete a old file on this pass, another attempt will be made the next time this function is called. Logging.LogWarning($"Unable to delete previous icon, {file}, for achievement Id: {localAchievement.Id}, exception: {e}"); } } } string fullUrl = _achievementIconsBaseUrl + iconS3Key; UnityWebRequest request = new UnityWebRequest(fullUrl); request.method = UnityWebRequest.kHttpVerbGET; DownloadHandlerFile fileHandler; try { fileHandler = new DownloadHandlerFile(downloadPath); } catch (Exception e) { Logging.LogException($"Icon {fullUrl} download failed", e); return; } fileHandler.removeFileOnAbort = true; request.downloadHandler = fileHandler; request.timeout = 120; //seconds request.SendWebRequest(); while (!fileHandler.isDone) { await System.Threading.Tasks.Task.Yield(); } if (fileHandler.isDone) { if (request.result == UnityWebRequest.Result.ProtocolError || request.result == UnityWebRequest.Result.ConnectionError) { Logging.LogError($"Icon {fullUrl} download failed with {request.error}"); } else if (!string.IsNullOrEmpty(fileHandler.error)) { Logging.LogError($"Icon {fullUrl} download failed with {fileHandler.error}"); } else { Logging.LogInfo($"Icon {fullUrl} download Successful"); // Force the textures to load by clearing their cache. localAchievement.ClearTextures(); } } } } #endregion #region Popup Windows /// <summary> /// The popup window that shows when the "Get latest" button is clicked. /// </summary> private class GetLatestPopupWindow : EditorWindow { public static void CreatePopupWindow(Action onClickAddMissing, Action onClickReplaceAll) { int choice = EditorUtility.DisplayDialogComplex(L10n.Tr("Get latest achievements"), L10n.Tr("Do you want to add missing cloud achievements to your local achievements, " + "or completely replace all local achievements with what is in the cloud?"), L10n.Tr("Add Missing"), L10n.Tr("Cancel"), L10n.Tr("Replace All Local")); switch (choice) { // Add Missing case 0: onClickAddMissing.Invoke(); break; // Cancel case 1: break; // Replace All Local case 2: onClickReplaceAll.Invoke(); break; } } } #endregion #region Helpers private void AddLocalAchievement(AchievementWidget achievement, ref uint newAchievementRunningCount, ref uint updatedAchievementsRunningCount, ref uint restoredAchievementsRunningCount) { // Check if the achievement already exists if (_localAchievements.ContainsKey(achievement.Id)) { if (_localAchievements.GetValue(achievement.Id).IsMarkedForDeletion == true) { // Restore the achievement to the local list by changing its delete flag back to false. _localAchievements.GetValue(achievement.Id).IsMarkedForDeletion = false; ++restoredAchievementsRunningCount; } if (!AchievementWidget.AreSame(_localAchievements.GetValue(achievement.Id), achievement)) { // copy the values in the new achievement into the current one _localAchievements.GetValue(achievement.Id).CopyNonUniqueValues(achievement); ++updatedAchievementsRunningCount; } } else { // Add as a new achievement _localAchievements.Add(achievement.Id, achievement); ++newAchievementRunningCount; } } private void AddLocalAchievement(AchievementWidget achievement) { uint throwAwayNewCount = 0; uint throwAwayUpdateCount = 0; uint throwAwayRestoredCount = 0; AddLocalAchievement(achievement, ref throwAwayNewCount, ref throwAwayUpdateCount, ref throwAwayRestoredCount); } private string ExportListOfAchievements(List<Achievement> listOfAchievements, string saveFilePanelTitle, string defaultFileName) { // Convert the list of achievements to a human readable JSON file string toExport = JsonConvert.SerializeObject(listOfAchievements, Formatting.Indented); // Ask for the name of the file and its location string file = EditorUtility.SaveFilePanel(saveFilePanelTitle, string.Empty, defaultFileName, "json"); if (string.IsNullOrEmpty(file)) { // this case will happen if the user hits cancel on the SaveFilePanel, this is a normal case return string.Empty; } // output the JSON object to the requested file File.WriteAllText(file, toExport); if (!File.Exists(file)) { Logging.LogError(L10n.Tr($"Error creating file {file}")); return string.Empty; } Logging.LogInfo(L10n.Tr($"{listOfAchievements.Count} achievement(s) exported to {file}")); return file; } private void RefreshAchievementIconBaseUrl() { _achievementsAdmin.GetAchievementIconBaseUrl((StringCallbackResult result) => { if (result.ResultCode == GameKitErrors.GAMEKIT_SUCCESS) { string baseUrl = result.ResponseValue; string credentialsNotSubmittedUrl = "/"; _achievementIconsBaseUrl = baseUrl == credentialsNotSubmittedUrl ? string.Empty : baseUrl; } else { _achievementIconsBaseUrl = string.Empty; string errorMessage = $"Failed to refresh the achievement icon base URL."; string apiName = nameof(IAchievementsAdminProvider.GetAchievementIconBaseUrl); HandleFailedCloudApiCall(result.ResultCode, errorMessage, apiName); } }); } /// <summary> /// Call this method when a cloud-based AWS GameKit API call returns a non-successful result code.<br/><br/> /// /// This method turns on the "Cloud Sync Error" banner and logs a helpful error message. /// </summary> /// <param name="resultCode">The result code from the failed API call (<see cref="GameKitErrors"/>).</param> /// <param name="errorMessage">An explanation of what went wrong. Should include punctuation but no trailing space at the end of the sentence. /// For example, "Failed to delete the following achievements: {achievementTitles}."</param> /// <param name="apiName">The method name of the failed API call. Used <c>nameof()</c> to get this value.</param> private void HandleFailedCloudApiCall(uint resultCode, string errorMessage, string apiName) { _isShowingCloudSyncErrorBanner = true; string friendlyErrorName = GameKitErrorConverter.GetErrorName(resultCode); string hexadecimalErrorCode = GameKitErrors.ToString(resultCode); string sourceCodeFilePath = IACHIEVEMENTS_ADMIN_PROVIDER_FILE_PATH; Logging.LogError($"{errorMessage} " + $"A {friendlyErrorName} ({hexadecimalErrorCode}) error occurred while calling the {apiName}() API. " + $"This error code is explained in the {apiName}() method's documentation in the file \"{sourceCodeFilePath}\""); } #endregion } }
1,061
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Runtime.Features.GameKitAchievements; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Windows.Settings.Pages.Achievements { [Serializable] public class AchievementsExamplesTab : FeatureExamplesTab { public override FeatureType FeatureType => FeatureType.Achievements; private IAchievementsProvider _achievements; [SerializeField] private ListAchievementsExampleUI _listAchievementsExampleUI; [SerializeField] private GetAchievementExampleUI _getAchievementExampleUI; [SerializeField] private UpdateAchievementExampleUI _updateAchievementExampleUI; public override void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { _achievements = dependencies.Achievements; _listAchievementsExampleUI.Initialize(CallListAchievements, serializedProperty.FindPropertyRelative(nameof(_listAchievementsExampleUI))); _getAchievementExampleUI.Initialize(CallGetAchievement, serializedProperty.FindPropertyRelative(nameof(_getAchievementExampleUI))); _updateAchievementExampleUI.Initialize(CallUpdateAchievement, serializedProperty.FindPropertyRelative(nameof(_updateAchievementExampleUI))); base.Initialize(dependencies, serializedProperty); } #region Helper Functions public static void DrawAchievement(Achievement achievement, int indentationLevel = 1) { EditorGUILayoutElements.TextField("Achievement Id", achievement.AchievementId, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Title", achievement.Title, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Current Value", achievement.CurrentValue.ToString(), indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Points", achievement.Points.ToString(), indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Locked Description", achievement.LockedDescription, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Unlocked Description", achievement.UnlockedDescription, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Locked Icon (path)", achievement.LockedIcon, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Unlocked Icon (path)", achievement.UnlockedIcon, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Required Amount", achievement.RequiredAmount.ToString(), indentationLevel, isEnabled: false); EditorGUILayoutElements.CustomField("Visibility", () => { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.ToggleLeft("Invisible to players", achievement.IsSecret, false); EditorGUILayoutElements.ToggleLeft("Cannot be achieved", achievement.IsHidden, false); } }, indentationLevel); EditorGUILayoutElements.ToggleField("Earned", achievement.IsEarned, indentationLevel, false); EditorGUILayoutElements.ToggleField("Newly Earned", achievement.IsNewlyEarned, indentationLevel, false); // Convert ISO-8601 formatted string to local time for improved readability string earnedAt = TimeUtils.ISO8601StringToLocalFormattedString(achievement.EarnedAt); string updatedAt = TimeUtils.ISO8601StringToLocalFormattedString(achievement.UpdatedAt); EditorGUILayoutElements.TextField("Earned At", earnedAt, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Updated At", updatedAt, indentationLevel, isEnabled: false); } public static void DrawAchievements(List<Achievement> achievements, int indentationLevel = 1) { for (int i = 0; i < achievements.Count; i++) { DrawAchievement(achievements[i], indentationLevel); if (i != achievements.Count - 1) { EditorGUILayoutElements.SectionDivider(); } } } #endregion #region Achievements API Calls protected override void DrawExamples() { _listAchievementsExampleUI.OnGUI(); _getAchievementExampleUI.OnGUI(); _updateAchievementExampleUI.OnGUI(); } private void CallListAchievements() { // ListAchievements is instrumented to work with pagination. For the examples, we've chosen to wait for the entire achievements list to load in one API call. ListAchievementsDesc listAchievementsDesc = new ListAchievementsDesc { // A large page size will increase the time between callbacks, as more data has to be read from the database. However, it will also reduce the total number of // networked round-trips to fetch all of the user's data. A small page size will increase the number of networked round-trips, but reduce the latency before any results are returned. // To reduce the overall query latency, pick a larger page size. To reduce the latency for receiving a subset of the results, pick a smaller page size. // PageSize is capped at 100 on the cloud backend. PageSize = 100, // When WaitForAllPages is false, the Action<AchievementListResult> callback you pass into ListAchievementsForPlayer() will be continually invoked // each time a page of data is returned from the cloud backend. When set to true, the GameKit SDK will aggregate all of a user's achievement data // before invoking the callback a single time. In both scenarios, the final Action<uint> onCompleteCallback will be invoked once all achievements have been listed. WaitForAllPages = true }; Debug.Log($"Calling Achievements.ListAchievementsForPlayer() with {listAchievementsDesc}"); _listAchievementsExampleUI.Achievements.Clear(); _achievements.ListAchievementsForPlayer(listAchievementsDesc, (AchievementListResult result) => { // This may be called multiple times; once per page. As we've opted to use WaitForAllPages = true, this should only be called once. Debug.Log($"Achievements.ListAchievementsForPlayer() returned a page of results with {result.Achievements.Length} achievements"); _listAchievementsExampleUI.Achievements.AddRange(result.Achievements); }, (uint result) => { // This is executed when an error has occurred, or once all pages have been fetched. Debug.Log($"Achievements.ListAchievementsForPlayer() completed with result code {GameKitErrorConverter.GetErrorName(result)}"); _listAchievementsExampleUI.ResultCode = result; }); } private void CallGetAchievement() { Debug.Log($"Calling Achievements.GetAchievementForPlayer() for achievement \"{_getAchievementExampleUI.AchievementId}\""); _getAchievementExampleUI.Achievement = new Achievement(); _achievements.GetAchievementForPlayer(_getAchievementExampleUI.AchievementId, (AchievementResult result) => { Debug.Log($"Achievements.GetAchievementForPlayer() completed with result code {GameKitErrorConverter.GetErrorName(result.ResultCode)}"); _getAchievementExampleUI.ResultCode = result.ResultCode; _getAchievementExampleUI.Achievement = result.Achievement; }); } private void CallUpdateAchievement() { UpdateAchievementDesc updateAchievementDesc = new UpdateAchievementDesc { AchievementId = _updateAchievementExampleUI.AchievementId, IncrementBy = (uint) _updateAchievementExampleUI.IncrementBy }; Debug.Log($"Calling Achievements.UpdateAchievementForPlayer() with {updateAchievementDesc}"); _updateAchievementExampleUI.Achievement = new Achievement(); _achievements.UpdateAchievementForPlayer(updateAchievementDesc, (AchievementResult result) => { Debug.Log($"Achievements.UpdateAchievementForPlayer() completed with result code {GameKitErrorConverter.GetErrorName(result.ResultCode)}"); _updateAchievementExampleUI.ResultCode = result.ResultCode; _updateAchievementExampleUI.Achievement = result.Achievement; }); } #endregion } #region Achievements Examples [Serializable] public class ListAchievementsExampleUI : GameKitExampleUI { public override string ApiName => "List Achievements"; protected override bool _shouldDisplayResponse => true; public List<Achievement> Achievements = new List<Achievement>(); protected override void DrawOutput() { AchievementsExamplesTab.DrawAchievements(Achievements); } } [Serializable] public class GetAchievementExampleUI : GameKitExampleUI { public override string ApiName => "Get Achievement"; protected override bool _shouldDisplayResponse => true; public string AchievementId; public Achievement Achievement; protected override void DrawInput() { PropertyField(nameof(AchievementId), "Achievement Id"); } protected override void DrawOutput() { AchievementsExamplesTab.DrawAchievement(Achievement); } } [Serializable] public class UpdateAchievementExampleUI : GameKitExampleUI { public override string ApiName => "Update Achievement"; protected override bool _shouldDisplayResponse => true; public string AchievementId; public int IncrementBy = 1; public Achievement Achievement; protected override void DrawInput() { PropertyField(nameof(AchievementId), "Achievement Id"); PropertyField(nameof(IncrementBy), "Increment By"); } protected override void DrawOutput() { AchievementsExamplesTab.DrawAchievement(Achievement); } } #endregion }
224
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.GUILayoutExtensions; namespace AWS.GameKit.Editor.Windows.Settings.Pages.Achievements { [Serializable] public class AchievementsPage : FeaturePage { public static string AchievementsDataTabName = L10n.Tr("Configure Data"); public override FeatureType FeatureType => FeatureType.Achievements; [SerializeField] private AchievementsSettingsTab _achievementSettingsTab; [SerializeField] private AchievementsExamplesTab _achievementExamplesTab; [SerializeField] private AchievementsDataTab _achievementDataTab; public void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { _achievementSettingsTab.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_achievementSettingsTab))); _achievementExamplesTab.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_achievementExamplesTab))); _achievementDataTab.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_achievementDataTab))); Tab[] tabs = new Tab[] { CreateSettingsTab(_achievementSettingsTab), new Tab(AchievementsDataTabName, _achievementDataTab), CreateExamplesTab(_achievementExamplesTab) }; base.Initialize(tabs, dependencies); } } }
43
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Models; namespace AWS.GameKit.Editor.Windows.Settings.Pages.Achievements { [Serializable] public class AchievementsSettingsTab : FeatureSettingsTab { public override FeatureType FeatureType => FeatureType.Achievements; protected override IEnumerable<IFeatureSetting> FeatureSpecificSettings => new List<IFeatureSetting>() { // No feature specific settings. }; protected override IEnumerable<SecretSetting> FeatureSecrets => new List<SecretSetting>() { // No feature secrets. }; protected override bool ShouldReloadFeatureSettings() => false; protected override bool ShouldDrawSettingsSection() => false; protected override void DrawSettings() { // No settings. } } }
38
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.IO; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Editor.AchievementsAdmin; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.FileStructure; using AWS.GameKit.Editor.Utils; using AWS.GameKit.Runtime.Features.GameKitAchievements; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Windows.Settings.Pages.Achievements { /// <summary> /// Indicates whether an achievement's local and cloud definitions are identical.<br/><br/> /// /// The method <see cref="AchievementWidget.AreSame"/> determines whether two achievements are identical.<br/><br/> /// /// Local and cloud achievements are compared to each other if they have the same <see cref="AchievementWidget.Id"/>, which is the "primary key" for achievement definitions.<br/><br/> /// /// The SyncStatus is refreshed whenever the buttons "Save data" or "Get latest" are clicked. /// </summary> public enum SyncStatus { /// <summary> /// It is unknown whether this local achievement is synchronized with the cloud. /// </summary> Unknown, /// <summary> /// This local achievement is synchronized with the cloud. The cloud and local definitions are identical, as compared by <see cref="AchievementWidget.AreSame"/>. /// </summary> Synchronized, /// <summary> /// This local achievement is unsynchronized with the cloud. The cloud and local definitions are different, or the achievement doesn't exist in the cloud. /// </summary> Unsynchronized } /// <summary> /// A GUI element which renders a single, editable Achievement. /// </summary> [Serializable] public class AchievementWidget : IHasSerializedPropertyOfSelf { private static IFileManager _fileManager = new FileManager(); public SerializedProperty SerializedPropertyOfSelf { get; set; } // UI Slider Min/Max Values // These are not hard limits for your game. You can increase these values if you'd like. These limits only exist to make the UI sliders look nice with a reasonable range of values. internal const int POINTS_MAX = 200; internal const int POINTS_MIN = 1; internal const int STEPS_MAX = 1000; internal const int STEPS_MIN = 1; internal const int SORT_MAX = 200; internal const int SORT_MIN = 1; // UI Fields public string Id = string.Empty; public string Title = string.Empty; public int Points = POINTS_MIN; public string DescriptionLocked = string.Empty; public string DescriptionUnlocked = string.Empty; public string IconPathLocked = string.Empty; public string IconPathUnlocked = string.Empty; public int NumberOfStepsToEarn = STEPS_MIN; public bool IsInvisibleToPlayers = false; public bool CanBeAchieved = true; public int SortOrder = SORT_MIN; public bool IsMarkedForDeletion = false; // When we first create a new achievement, we know its not on the cloud, thus we implicitly know its Unsynchronized public SyncStatus SyncStatus = SyncStatus.Unsynchronized; [SerializeField] private Vector2 _scrollPosition; [SerializeField] private bool _isExpanded = false; // These should explicitly never be serialized, we what the texture to only buffer while Unity is running, but refresh on each start. [NonSerialized] private Texture _lockedTexture = null; [NonSerialized] private Texture _unlockedTexture = null; public static implicit operator AdminAchievement(AchievementWidget achievementWidget) { return new AdminAchievement() { AchievementId = achievementWidget.Id, Title = achievementWidget.Title, LockedDescription = achievementWidget.DescriptionLocked, UnlockedDescription = achievementWidget.DescriptionUnlocked, LockedIcon = achievementWidget.IconPathLocked, UnlockedIcon = achievementWidget.IconPathUnlocked, RequiredAmount = (uint)achievementWidget.NumberOfStepsToEarn, Points = (uint)achievementWidget.Points, OrderNumber = (uint)achievementWidget.SortOrder, IsStateful = achievementWidget.NumberOfStepsToEarn > 1, IsSecret = achievementWidget.IsInvisibleToPlayers, IsHidden = !achievementWidget.CanBeAchieved, }; } public static implicit operator AchievementWidget(AdminAchievement adminAchievement) { return new AchievementWidget() { Id = adminAchievement.AchievementId, Title = adminAchievement.Title, DescriptionLocked = adminAchievement.LockedDescription, DescriptionUnlocked = adminAchievement.UnlockedDescription, IconPathLocked = adminAchievement.LockedIcon, IconPathUnlocked = adminAchievement.UnlockedIcon, NumberOfStepsToEarn = (int)adminAchievement.RequiredAmount, Points = (int)adminAchievement.Points, SortOrder = (int)adminAchievement.OrderNumber, IsInvisibleToPlayers = adminAchievement.IsSecret, CanBeAchieved = !adminAchievement.IsHidden }; } public static implicit operator Achievement(AchievementWidget achievementWidget) { return new Achievement() { AchievementId = achievementWidget.Id, Title = achievementWidget.Title, LockedDescription = achievementWidget.DescriptionLocked, UnlockedDescription = achievementWidget.DescriptionUnlocked, LockedIcon = achievementWidget.IconPathLocked, UnlockedIcon = achievementWidget.IconPathUnlocked, CurrentValue = 0, RequiredAmount = achievementWidget.NumberOfStepsToEarn, Points = achievementWidget.Points, OrderNumber = achievementWidget.SortOrder, IsSecret = achievementWidget.IsInvisibleToPlayers, IsHidden = !achievementWidget.CanBeAchieved, IsEarned = false, IsNewlyEarned = false, EarnedAt = string.Empty, UpdatedAt = string.Empty }; } public static implicit operator AchievementWidget(Achievement achievement) { return new AchievementWidget() { Id = achievement.AchievementId, Title = achievement.Title, DescriptionLocked = achievement.LockedDescription, DescriptionUnlocked = achievement.UnlockedDescription, IconPathLocked = achievement.LockedIcon, IconPathUnlocked = achievement.UnlockedIcon, NumberOfStepsToEarn = achievement.RequiredAmount, Points = achievement.Points, SortOrder = achievement.OrderNumber, IsInvisibleToPlayers = achievement.IsSecret, CanBeAchieved = !achievement.IsHidden }; } /// <summary> /// Return true if the local achievement and cloud achievement are exactly the same. /// </summary> public static bool AreSame(AchievementWidget localAchievement, AchievementWidget cloudAchievement) { return localAchievement.Id == cloudAchievement.Id && localAchievement.Title == cloudAchievement.Title && localAchievement.Points == cloudAchievement.Points && localAchievement.DescriptionLocked == cloudAchievement.DescriptionLocked && localAchievement.DescriptionUnlocked == cloudAchievement.DescriptionUnlocked && localAchievement.IconPathLocked.Equals(cloudAchievement.IconPathLocked) && localAchievement.IconPathUnlocked.Equals(cloudAchievement.IconPathUnlocked) && localAchievement.NumberOfStepsToEarn == cloudAchievement.NumberOfStepsToEarn && localAchievement.IsInvisibleToPlayers == cloudAchievement.IsInvisibleToPlayers && localAchievement.CanBeAchieved == cloudAchievement.CanBeAchieved && localAchievement.SortOrder == cloudAchievement.SortOrder; } /// <summary> /// Copies the values which are safe to copy from another widget into this widget. /// </summary> /// <param name="achievementWidget">Widget to copy from.</param> public void CopyNonUniqueValues(AchievementWidget achievementWidget) { Title = achievementWidget.Title; DescriptionLocked = achievementWidget.DescriptionLocked; DescriptionUnlocked = achievementWidget.DescriptionUnlocked; IconPathLocked = achievementWidget.IconPathLocked; IconPathUnlocked = achievementWidget.IconPathUnlocked; NumberOfStepsToEarn = achievementWidget.NumberOfStepsToEarn; Points = achievementWidget.Points; SortOrder = achievementWidget.SortOrder; IsInvisibleToPlayers = achievementWidget.IsInvisibleToPlayers; CanBeAchieved = achievementWidget.CanBeAchieved; SyncStatus = achievementWidget.SyncStatus; IsMarkedForDeletion = achievementWidget.IsMarkedForDeletion; // The icons will need to be reloaded ClearTextures(); } /// <summary> /// Public method for collapsing an expanded widget. /// </summary> public void CollapseWidget() { _isExpanded = false; } /// <summary> /// Public method for clearing the current icon textures and forcing a reload. /// </summary> public void ClearTextures() { _lockedTexture = null; _unlockedTexture = null; } /// <summary> /// Draw the achievement on the screen. /// </summary> /// <param name="isEditable">True if the achievement's attributes can be edited, false if not.</param> public void OnGUI(bool isEditable) { if (IsMarkedForDeletion || SerializedPropertyOfSelf == null) { // Don't display this achievement return; } using (new EditorGUILayout.VerticalScope(_isExpanded ? SettingsGUIStyles.Achievements.BodyExpanded : SettingsGUIStyles.Achievements.BodyCollapsed)) { using (new EditorGUILayout.HorizontalScope()) { _isExpanded = EditorGUILayout.Foldout(_isExpanded, string.Empty, true, EditorStyles.foldout); GUILayout.Label(Title, SettingsGUIStyles.Achievements.Header); Rect headerTitleRect = GUILayoutUtility.GetLastRect(); GUI.Label(new Rect(headerTitleRect.x - SettingsGUIStyles.Achievements.HEADER_ICON_HORIZONTAL_PADDING, headerTitleRect.y + SettingsGUIStyles.Achievements.HEADER_ICON_VERTICAL_PADDING, SettingsGUIStyles.Achievements.HEADER_ICON_WIDTH, SettingsGUIStyles.Achievements.HEADER_ICON_HEIGHT), GetAchievementHeader(), EditorStyles.label); GUILayout.FlexibleSpace(); Texture deleteTexture = EditorGUIUtility.IconContent("TreeEditor.Trash").image; using (new EditorGUI.DisabledScope(!isEditable)) { if (GUILayout.Button(new GUIContent(deleteTexture, L10n.Tr("Delete this achievement locally. To delete from the cloud, click \"Save data\" after clicking this button.")), SettingsGUIStyles.Achievements.DeleteButton)) { IsMarkedForDeletion = true; } } } if (!_isExpanded) { return; } using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.Achievements.Expanded)) { UpdateSyncStatus(Id, PropertyField(nameof(Id), L10n.Tr("ID (primary key)"), string.Empty, isEnabled: false)); UpdateSyncStatus(Title, PropertyField(nameof(Title), L10n.Tr("Title"), string.Empty, isEditable)); using (new EditorGUILayout.HorizontalScope()) { Points = UpdateSyncStatus(Points, EditorGUILayoutElements.OverrideSlider(L10n.Tr("Points"), Points, POINTS_MIN, POINTS_MAX, isEnabled: isEditable)); } GUILayout.Space(SettingsGUIStyles.Achievements.SPACING); DescriptionLocked = UpdateSyncStatus(DescriptionLocked, DescriptionField(L10n.Tr("Description\n(when locked)"), L10n.Tr("Enter a description for this achievement while it is still locked"), DescriptionLocked, isEditable)); DescriptionUnlocked = UpdateSyncStatus(DescriptionUnlocked, DescriptionField(L10n.Tr("Description\n(when achieved)"), L10n.Tr("Enter a description for this achievement for after it is achieved"), DescriptionUnlocked, isEditable)); _lockedTexture = ImageField(L10n.Tr("Image/icon\n(when locked)"), L10n.Tr("Select image/icon for locked achievement"), _lockedTexture, nameof(IconPathLocked), ref IconPathLocked, isEditable); _unlockedTexture = ImageField(L10n.Tr("Image/icon\n(when achieved)"), L10n.Tr("Select image/icon for achieved achievement"), _unlockedTexture, nameof(IconPathUnlocked), ref IconPathUnlocked, isEditable); using (new EditorGUILayout.HorizontalScope()) { NumberOfStepsToEarn = UpdateSyncStatus(NumberOfStepsToEarn, EditorGUILayoutElements.OverrideSlider(L10n.Tr("No. steps to earn"), NumberOfStepsToEarn, STEPS_MIN, STEPS_MAX, isEnabled: isEditable)); } GUILayout.Space(SettingsGUIStyles.Achievements.SPACING); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel(L10n.Tr("Visibility"), SettingsGUIStyles.Achievements.VisibilityLabel); EditorGUILayoutElements.KeepPreviousPrefixLabelEnabled(); IsInvisibleToPlayers = UpdateSyncStatus(IsInvisibleToPlayers, EditorGUILayoutElements.ToggleLeft(L10n.Tr("Invisible to players"), IsInvisibleToPlayers, isEnabled: isEditable)); CanBeAchieved = UpdateSyncStatus(CanBeAchieved, EditorGUILayoutElements.ToggleLeft(L10n.Tr("Can be achieved"), CanBeAchieved, isEnabled: isEditable)); GUILayout.FlexibleSpace(); } GUILayout.Space(SettingsGUIStyles.Achievements.SPACING); using (new EditorGUILayout.HorizontalScope()) { SortOrder = UpdateSyncStatus(SortOrder, EditorGUILayoutElements.OverrideSlider(L10n.Tr("Sort order"), SortOrder, SORT_MIN, SORT_MAX, isEnabled: isEditable)); } } } } private string PropertyField(string propertyPath, string label, string placeholder = "", bool isEnabled = true, params GUILayoutOption[] options) { SerializedProperty property = SerializedPropertyOfSelf.FindPropertyRelative(propertyPath); if (property == null) { // when adding items quickly, there is a race condition where the property may not exist yet, skip this element for this render loop, it will render on the next loop once the property is available. return string.Empty; } EditorGUILayoutElements.PropertyField(label, property, 1, placeholder, isEnabled, options); GUILayout.Space(SettingsGUIStyles.Achievements.SPACING); return property.stringValue; } private string DescriptionField(string title, string placeholder, string description, bool isEnabled) { GUIContent content = new GUIContent(description); float minWidth, maxWidth; SettingsGUIStyles.Achievements.Description.CalcMinMaxWidth(content, out minWidth, out maxWidth); float calculatedHeight = SettingsGUIStyles.Achievements.Description.CalcHeight(content, maxWidth); float height = Math.Max(calculatedHeight, SettingsGUIStyles.Achievements.DESCRIPTION_MIN_HEIGHT); string value = EditorGUILayoutElements.DescriptionField( title, description, 1, placeholder, isEnabled, SettingsGUIStyles.Achievements.DescriptionLabel, SettingsGUIStyles.Achievements.Description, GUILayout.MinHeight(height) ); GUILayout.Space(SettingsGUIStyles.Achievements.SPACING); return value; } private Texture ImageField(string label, string windowText, Texture currentImage, string nameOfImagePath, ref string imagePath, bool isEnabled) { Texture defaultIcon = EditorGUIUtility.IconContent(L10n.Tr("d_Texture Icon")).image; using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUILayout.HorizontalScope(SettingsGUIStyles.Achievements.ImageBody)) { EditorGUILayout.PrefixLabel(label, SettingsGUIStyles.Achievements.ImageLabel, SettingsGUIStyles.Achievements.ImageLabel); EditorGUILayoutElements.KeepPreviousPrefixLabelEnabled(); EditorGUILayout.LabelField(new GUIContent(currentImage ?? defaultIcon), SettingsGUIStyles.Achievements.Image); if (EditorGUILayoutElements.Button(L10n.Tr("Browse"), isEnabled)) { string file = EditorUtility.OpenFilePanel(windowText, string.Empty, "png,PNG,jpeg,JPEG,jpg,JPG"); if (file.Length > 0) { SerializedPropertyOfSelf.FindPropertyRelative(nameOfImagePath).stringValue = file; SetToUnsynchronized(); currentImage = null; } } } string oldPath = SerializedPropertyOfSelf.FindPropertyRelative(nameOfImagePath).stringValue; imagePath = UpdateSyncStatus(oldPath, PropertyField(nameOfImagePath, string.Empty, L10n.Tr("or enter your icon's path"), isEnabled)); if (!oldPath.Equals(imagePath)) { currentImage = null; } } GUILayout.Space(SettingsGUIStyles.Achievements.SPACING); if (currentImage == null) { if (_fileManager.FileExists(imagePath)) { if (!IsFileAvailable(imagePath)) { // This case occurs if the file is still open from download while we are trying to read it. Keep as null and try again on the next frame. return null; } byte[] imageBytes = _fileManager.ReadAllBytes(imagePath); Texture2D newImage = new Texture2D(1, 1); if (!ImageConversion.LoadImage(newImage, imageBytes, false)) { Logging.LogInfo(L10n.Tr($"Could not load image at {imagePath}")); return defaultIcon; } return newImage; } else if (!string.IsNullOrEmpty(imagePath)) { Logging.LogInfo(L10n.Tr($"File not found at {imagePath}")); return defaultIcon; } else { // this is the case where the achievement has just been created and has no image paths return defaultIcon; } } else { return currentImage; } } private bool IsFileAvailable(string filePath) { try { FileInfo fileInfo = new FileInfo(filePath); using (FileStream stream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.None)) { stream.Close(); } } catch (IOException) { // File is not available. return false; } // File is free. return true; } private GUIContent GetAchievementHeader() { if (SyncStatus == SyncStatus.Unknown) { return new GUIContent(EditorResources.Textures.Colors.Transparent.Get()); } else if (SyncStatus == SyncStatus.Synchronized) { return new GUIContent(EditorResources.Textures.FeatureStatusSuccess.Get(), L10n.Tr("Synced with cloud")); } else // Unsynchronized { return new GUIContent(EditorResources.Textures.Unsynchronized.Get(), L10n.Tr("Not in sync with cloud")); } } private void SetToUnsynchronized() { // SyncStatus is serialized, so we need to change its serialized property, if we just assign it a value instead then it will be overridden when Unity updates its serialized values SerializedPropertyOfSelf.FindPropertyRelative(nameof(SyncStatus)).enumValueIndex = (int)SyncStatus.Unsynchronized; } private T UpdateSyncStatus<T>(T oldValue, T newValue) { if (!EqualityComparer<T>.Default.Equals(oldValue, newValue)) { SetToUnsynchronized(); } return newValue; } } }
490
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; // GameKit using AWS.GameKit.Editor.Core; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Runtime.Core; namespace AWS.GameKit.Editor.Windows.Settings.Pages.AllFeatures { [Serializable] public class AllFeaturesPage : Page { public override string DisplayName => "All Features"; private FeatureResourceManager _featureResourceManager; private GameKitEditorManager _gamekitEditorManager; public void Initialize(SettingsDependencyContainer dependencies) { _featureResourceManager = dependencies.FeatureResourceManager; _gamekitEditorManager = dependencies.GameKitEditorManager; } protected override void DrawContent() { // Headers DrawFeatureHeaders(); EditorGUILayoutElements.SectionDivider(); // Features foreach (var featureSettingsTab in FeatureSettingsTab.FeatureSettingsTabsInstances) { featureSettingsTab.DrawFeatureSummary(); EditorGUILayoutElements.SectionSpacer(); } } private void DrawFeatureHeaders() { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.CustomField(L10n.Tr("Feature: "), () => { EditorGUILayout.LabelField(L10n.Tr("Deployment Status:")); }, indentationLevel: 0); } } protected override void DrawTitle() { bool creds = _gamekitEditorManager.CredentialsSubmitted; string env = creds ? _featureResourceManager.GetLastUsedEnvironment() : ""; string region = creds ? _featureResourceManager.GetLastUsedRegion() : ""; UnityEngine.GUIStyle titleStyle = SettingsGUIStyles.Page.Title; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(DisplayName, titleStyle); if (!_gamekitEditorManager.CredentialsSubmitted) { EditorGUILayout.EndHorizontal(); return; } EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField("Environment: " + env, SettingsGUIStyles.Page.EnvDetails); EditorGUILayout.LabelField("Region: " + region, SettingsGUIStyles.Page.EnvDetails); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } } }
79
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; // Unity using UnityEditor; using UnityEngine; using UnityEngine.Events; // GameKit using AWS.GameKit.Editor.Core; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Utils; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Windows.Settings.Pages.EnvironmentAndCredentials { [Serializable] public class EnvironmentAndCredentialsPage : Page { // All keywords cannot be used in the games title or environment code private static readonly string[] RESERVED_KEYWORDS = { "aws", "amazon", "cognito" }; // UI Strings private static readonly string GAMEKIT_INTRODUCTION = L10n.Tr("If you want to get the full experience of what GameKit offers, go to AWS to create an account, then provide your " + "credentials in the GameKit plugin. Your new AWS account comes with a slate of free usage benefits, including " + "all of the AWS services that GameKit game features use. "); private static readonly string AWS_INTRODUCTION = L10n.Tr("With an AWS account, you can get in-depth, hands-on experience with each GameKit game feature, all for free. You can " + "work with the full GameKit plugin, customize each GameKit feature and add it to your game, create the necessary AWS " + "cloud resources, and then test to see your new GameKit game features in action. Without an AWS account, you can view " + "some areas of the GameKit plugin and explore the GameKit sample materials."); private static readonly string CHANGE_ENVIRONMENT_WARNING = L10n.Tr("You can switch to another environment, change the AWS Region for deployments, or enter new AWS credentials. " + "After changing settings, you must choose Submit. Are you sure that you want to change environment settings?" + "\n\nWARNING: This action will result in any local Achievement configuration data being lost, " + "please upload any local data to the cloud by clicking on \"Save data\" on the Achievements Configure Data tab."); private static readonly string EXISTING_CREDENTIALS_INFO = L10n.Tr("Set credentials for this new environment. Use existing values (carried over from the previous environment) or enter new ones."); private static readonly string LOCATE_EXISTING_CONFIG = L10n.Tr("Locate existing"); private static readonly string CHANGE_ENVIRONMENT_TOOLTIP = L10n.Tr("You can't switch environments while AWS resources are deploying or updating"); private static readonly string CHANGE_ENVIRONMENT_AND_CREDS = L10n.Tr("Change environment + credentials"); private static readonly string CANCEL_ENVIRONMENT_AND_CREDS_CHANGE = L10n.Tr("Cancel environment + credentials change"); // Key that is used for the option that allows for creation of a new environment private const string NEW_CUSTOM_ENV_KEY = ":::"; // This string is shown in place of the user's AWS Account ID when there is an error determining the Account ID, when either the access or secret keys are not syntactically correct, or when there is trouble communicating with AWS. private const string AWS_ACCOUNT_ID_EMPTY = "..."; private const string AWS_ACCOUNT_ID_LOADING = "Loading..."; private static readonly string AWS_ACCOUNT_INVALID_PAIR = L10n.Tr("The AWS credentials entered are not a valid pair."); private static readonly string AWS_ACCOUNT_NOT_VALIDATED = L10n.Tr("The user credentials you provided cannot be validated.\nPlease enter a valid access key pair or create a new one using AWS IAM."); private static readonly string AWS_ACCOUNT_HAS_TOO_MANY_BUCKETS = L10n.Tr("The AWS account provided contains too many S3 buckets. \nPlease delete any unused S3 buckets or request an increase through the AWS console."); private static readonly string INTERNET_CONNECTIVITY_ISSUE = L10n.Tr("Internet is not reachable. Restore internet and reopen the Project Settings window to work with AWS GameKit features."); public override string DisplayName => "Environment & Credentials"; // Aws Environment and region private readonly IDictionary<string, string> _environmentMapping = new Dictionary<string, string>(); private readonly IDictionary<string, string> _regionMapping = new Dictionary<string, string>(); private readonly IList<string> _environmentOptions = new List<string>(); private readonly IList<string> _regionOptions = new List<string>(); // Dependencies private GameKitManager _gameKitManager; private GameKitEditorManager _gameKitEditorManager; private FeatureResourceManager _featureResourceManager; private FeatureDeploymentOrchestrator _featureDeploymentOrchestrator; private CredentialsManager _credentialsManager; private SerializedProperty _serializedProperty; private UnityEvent _onEnvironmentOrRegionChange; // State private bool _isNewProject = true; private bool _showNewEnvironmentNotification = false; [SerializeField] private bool _showNewToAws = false; [SerializeField] private Vector2 _scrollPosition; // UI Fields private string _projectAlias = string.Empty; private string _accessKeyId = string.Empty; private string _secretAccessKey = string.Empty; private string _awsAccountId = AWS_ACCOUNT_ID_EMPTY; private int _currentEnvironment = 0; private int _currentRegion = 3; // Set to "us-west-2" by design private string _customEnvironmentName = string.Empty; private string _customEnvironmentCode = string.Empty; // Error message values private string _projectAliasErrorMessage = string.Empty; private string _customEnvironmentNameErrorMessage = string.Empty; private string _customEnvironmentCodeErrorMessage = string.Empty; private string _accessKeyIdErrorMessage = string.Empty; private string _secretKeyErrorMessage = string.Empty; private string _credentialPairErrorMessage = string.Empty; private const string validLowerCaseAndNumericalPattern = @"^[a-z0-9]+$"; private readonly Regex _validLowerCaseAndNumericalRx = new Regex(validLowerCaseAndNumericalPattern); private const string validAlphaNumericPattern = @"^[A-Za-z0-9]+$"; private readonly Regex _validAlphanumericRx = new Regex(validAlphaNumericPattern); private const string validUpperCaseAndNumericalPattern = @"^[A-Z0-9]+$"; private readonly Regex _validUpperCaseAndNumericalRx = new Regex(validUpperCaseAndNumericalPattern); private LinkWidget _learnAboutFreeTierLinkWidget; private LinkWidget _beyondFreeTierLinkWidget; private LinkWidget _forgotCredentialsLinkWidget; public void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { // Dependencies _gameKitManager = dependencies.GameKitManager; _gameKitEditorManager = dependencies.GameKitEditorManager; _featureResourceManager = dependencies.FeatureResourceManager; _featureDeploymentOrchestrator = dependencies.FeatureDeploymentOrchestrator; _credentialsManager = dependencies.CredentialsManager; _serializedProperty = serializedProperty; _onEnvironmentOrRegionChange = dependencies.OnEnvironmentOrRegionChange; // Populate controls PopulateDefaultEnvironments(); PopulateRegions(); // Try to load and set initial state SetInitialState(); } protected override IList<string> GetTitle() { return new List<string>() { DisplayName }; } protected override void DrawContent() { CreateLinkWidgets(); using (EditorGUILayout.ScrollViewScope scrollView = new EditorGUILayout.ScrollViewScope(_scrollPosition)) { _scrollPosition = scrollView.scrollPosition; DrawNewToAwsSection(); EditorGUILayoutElements.SectionSpacer(); DrawProjectAliasSection(); EditorGUILayoutElements.SectionSpacer(); DrawEnvironmentAndRegionSection(); EditorGUILayoutElements.SectionSpacer(); DrawAwsAccountCredentialsSection(); EditorGUILayoutElements.SectionSpacer(extraPixels: -5); } EditorGUILayoutElements.HorizontalDivider(); EditorGUILayoutElements.SectionSpacer(extraPixels: -5); DrawSubmitCredentialsSection(); } /// <summary> /// Avoid a null-reference exception by creating the links during OnGUI instead of the constructor. /// The exception happens because the EditorStyles used in SettingsGUIStyles (ex: EditorStyles.foldout) are null until the first frame of the GUI. /// </summary> private void CreateLinkWidgets() { LinkWidget.Options options = new LinkWidget.Options() { OverallStyle = SettingsGUIStyles.Page.Paragraph, ContentOffset = new Vector2( x: -3, // Match the left alignment of the surrounding paragraph text. y: -3 // Vertically center the links. ), }; _learnAboutFreeTierLinkWidget = new LinkWidget(L10n.Tr("Learn more about the AWS free tier."), DocumentationURLs.FREE_TIER_INTRO, options); _beyondFreeTierLinkWidget = new LinkWidget(L10n.Tr("Ready to move beyond the free tier?"), L10n.Tr("Learn more about controlling costs with AWS."), DocumentationURLs.FREE_TIER_REFERENCE, options); _forgotCredentialsLinkWidget = new LinkWidget(L10n.Tr("Help me get my user credentials."), DocumentationURLs.SETTING_UP_CREDENTIALS, options); } /// <summary> /// Draws the section containing the New to Aws foldout and all contents within the foldout. /// </summary> private void DrawNewToAwsSection() { Color originalBackgroundColor = GUI.backgroundColor; using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { _showNewToAws = EditorGUILayout.Foldout(_showNewToAws, L10n.Tr(" New to AWS?"), SettingsGUIStyles.Page.FoldoutTitle); if (_showNewToAws) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.Page.FoldoutBox)) { EditorGUILayout.LabelField(GAMEKIT_INTRODUCTION, SettingsGUIStyles.Page.Paragraph); EditorGUILayout.LabelField(AWS_INTRODUCTION, SettingsGUIStyles.Page.Paragraph); GUI.backgroundColor = SettingsGUIStyles.Buttons.GUIButtonGreen.Get(); if (GUILayout.Button(L10n.Tr("Create an account"), SettingsGUIStyles.Buttons.CreateAccountButton)) { Application.OpenURL(DocumentationURLs.CREATE_ACCOUNT); } GUI.backgroundColor = originalBackgroundColor; _learnAboutFreeTierLinkWidget.OnGUI(); _beyondFreeTierLinkWidget.OnGUI(); } } } } /// <summary> /// Draws the section containing the Aws project alias. /// </summary> private void DrawProjectAliasSection() { EditorGUILayoutElements.SectionHeader(L10n.Tr("Create your project in the cloud")); using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.Page.VerticalLayout)) { EditorGUILayoutElements.PrefixLabel(L10n.Tr("AWS project alias")); if (_isNewProject) { EditorGUILayout.LabelField(L10n.Tr("Cannot be changed later"), SettingsGUIStyles.Page.PrefixLabelSubtext); } } using (new EditorGUILayout.VerticalScope()) { using (new EditorGUILayout.HorizontalScope()) { if (_isNewProject) { using (EditorGUI.ChangeCheckScope projectAliasChangeCheck = new EditorGUI.ChangeCheckScope()) { _projectAlias = EditorGUILayout.TextArea(_projectAlias); if (projectAliasChangeCheck.changed) { OnProjectAliasChanged(); } } } else { EditorGUILayout.LabelField(_projectAlias); } } if (_isNewProject) { EditorGUILayout.LabelField( L10n.Tr("The project alias must have 1-12 characters. Valid characters: a-z, 0-9."), SettingsGUIStyles.Page.TextAreaSubtext); } else { if (_gameKitEditorManager.CredentialsSubmitted) { string current_tooltip = _featureDeploymentOrchestrator.IsAnyFeatureUpdating() ? CHANGE_ENVIRONMENT_TOOLTIP : string.Empty; if (EditorGUILayoutElements.Button(CHANGE_ENVIRONMENT_AND_CREDS, tooltip: current_tooltip, isEnabled: !_featureDeploymentOrchestrator.IsAnyFeatureUpdating())) { OnChangeEnvironmentAndCredentials(); } } else { if (EditorGUILayoutElements.Button(CANCEL_ENVIRONMENT_AND_CREDS_CHANGE, isEnabled: !_featureDeploymentOrchestrator.IsAnyFeatureUpdating())) { OnCancelEnvironmentAndCredentialsChange(); } } } if (!IsGameNameValid()) { EditorGUILayout.HelpBox(_projectAliasErrorMessage, MessageType.Error); } } } } /// <summary> /// Draws the section containing the environment and regions dropdown. /// </summary> private void DrawEnvironmentAndRegionSection() { EditorGUILayoutElements.SectionHeader(L10n.Tr("Select an environment")); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel(L10n.Tr("Environment")); EditorGUI.BeginChangeCheck(); using (EditorGUI.ChangeCheckScope environmentChangeCheck = new EditorGUI.ChangeCheckScope()) { using (new EditorGUI.DisabledScope(!AreAwsCredentialInputsEnabled())) { _currentEnvironment = EditorGUILayout.Popup(_currentEnvironment, _environmentOptions.ToArray()); } if (environmentChangeCheck.changed) { OnEnvironmentSelectionChanged(); } } } if (GetSelectedEnvironmentKey() == NEW_CUSTOM_ENV_KEY) { DrawNewEnvironmentSection(); } using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel("Region"); using (new EditorGUI.DisabledScope(!AreAwsCredentialInputsEnabled())) { _currentRegion = EditorGUILayout.Popup(_currentRegion, _regionOptions.ToArray()); } } } /// <summary> /// Draws the section containing the forms to fill out for a new environment. /// </summary> private void DrawNewEnvironmentSection() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.EnvironmentAndCredentialsPage.CustomEnvironmentVerticalLayout)) { EditorGUILayout.LabelField(L10n.Tr("Environment name")); _customEnvironmentName = EditorGUILayout.TextArea(_customEnvironmentName); EditorGUILayout.LabelField(L10n.Tr("The environment name must have 1-16 characters. Valid characters: A-Z, a-z, 0-9, space."), SettingsGUIStyles.Page.TextAreaSubtext); } if (_customEnvironmentName.Length != 0 && !IsEnvironmentNameValid()) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.EnvironmentAndCredentialsPage.CustomEnvironmentErrorVerticalLayout)) { EditorGUILayout.HelpBox(_customEnvironmentNameErrorMessage, MessageType.Error); } } using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.EnvironmentAndCredentialsPage.CustomEnvironmentVerticalLayout)) { EditorGUILayout.LabelField(L10n.Tr("Environment code")); GUI.SetNextControlName("EnvironmentCodeTextField"); _customEnvironmentCode = EditorGUILayout.TextArea(_customEnvironmentCode); EditorGUILayout.LabelField(L10n.Tr("The environment code must have 2-3 characters. Valid characters: a-z, 0-9."), SettingsGUIStyles.Page.TextAreaSubtext); } if (_customEnvironmentCode.Length != 0 && !IsEnvironmentCodeValid()) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.EnvironmentAndCredentialsPage.CustomEnvironmentErrorVerticalLayout)) { EditorGUILayout.HelpBox(_customEnvironmentCodeErrorMessage, MessageType.Error); } } } /// <summary> /// Draws the section containing the forms to fill out for a new environment. /// </summary> private void DrawAwsAccountCredentialsSection() { EditorGUILayoutElements.SectionHeader(L10n.Tr("AWS account credentials")); if (_showNewEnvironmentNotification) { using (new EditorGUILayout.HorizontalScope(SettingsGUIStyles.EnvironmentAndCredentialsPage.AccountCredentialsHelpBoxesVerticalLayout)) { EditorGUILayout.HelpBox(EXISTING_CREDENTIALS_INFO, MessageType.Info); } } using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel(L10n.Tr("Access Key ID")); using (new EditorGUILayout.VerticalScope()) { using (EditorGUI.ChangeCheckScope accessKeyChangeCheck = new EditorGUI.ChangeCheckScope()) { using (new EditorGUI.DisabledScope(!AreAwsCredentialInputsEnabled())) { _accessKeyId = EditorGUILayout.TextField(_accessKeyId); } if (accessKeyChangeCheck.changed) { OnAwsCredentialsChanged(IsAccessKeyValid()); } } if (!string.IsNullOrEmpty(_accessKeyIdErrorMessage)) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.EnvironmentAndCredentialsPage.AccountCredentialsHelpBoxesVerticalLayout)) { EditorGUILayout.HelpBox(_accessKeyIdErrorMessage, MessageType.Error); GUILayout.Space(SettingsGUIStyles.EnvironmentAndCredentialsPage.SpaceAfterAccountIdHelpBox); } } } } using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel(L10n.Tr("Secret Access Key")); using (new EditorGUILayout.VerticalScope()) { using (EditorGUI.ChangeCheckScope secretKeyChangeCheck = new EditorGUI.ChangeCheckScope()) { using (new EditorGUI.DisabledScope(!AreAwsCredentialInputsEnabled())) { _secretAccessKey = EditorGUILayout.PasswordField(_secretAccessKey); } if (secretKeyChangeCheck.changed) { OnAwsCredentialsChanged(IsSecretKeyValid()); } } if (!string.IsNullOrEmpty(_secretKeyErrorMessage)) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.EnvironmentAndCredentialsPage.AccountCredentialsHelpBoxesVerticalLayout)) { EditorGUILayout.HelpBox(_secretKeyErrorMessage, MessageType.Error); GUILayout.Space(SettingsGUIStyles.EnvironmentAndCredentialsPage.SpaceAfterAccountIdHelpBox); } } } } using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel(L10n.Tr("AWS Account ID")); using (new EditorGUILayout.VerticalScope()) { using (new EditorGUI.DisabledScope(!AreAwsCredentialInputsEnabled())) { EditorGUILayout.LabelField(_awsAccountId); } if (!string.IsNullOrEmpty(_credentialPairErrorMessage)) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.EnvironmentAndCredentialsPage.AccountCredentialsHelpBoxesVerticalLayout)) { EditorGUILayout.HelpBox(_credentialPairErrorMessage, MessageType.Error); } } } } } /// <summary> /// Draws the section containing the options and information regarding credential submission. /// </summary> private void DrawSubmitCredentialsSection() { using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUI.DisabledScope(!IsSubmitButtonEnabled())) { if (GUILayout.Button(L10n.Tr("Submit"), SettingsGUIStyles.Buttons.SubmitCredentialsButton)) { OnSubmit(); } } GUILayout.FlexibleSpace(); } using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUILayout.HorizontalScope(SettingsGUIStyles.EnvironmentAndCredentialsPage.GetUserCredentialsLinkLayout)) { _forgotCredentialsLinkWidget.OnGUI(); } } } /// <summary> /// Checks if any user input options under the 'Select an environment' section should be enabled. /// </summary> /// <returns>A boolean value determining if the Environment inputs in the Environment and Credentials settings should be enabled.</returns> private bool AreEnvironmentInputsEnabled() { return !_gameKitEditorManager.CredentialsSubmitted && !string.IsNullOrEmpty(_projectAlias); } /// <summary> /// Checks if any user input options under the 'AWS account credentials' section should be enabled. /// </summary> /// <returns>A boolean value determining if the Aws credentials inputs in the Environment and Credentials settings should be enabled.</returns> private bool AreAwsCredentialInputsEnabled() { return !_gameKitEditorManager.CredentialsSubmitted && !string.IsNullOrEmpty(_projectAlias); } /// <summary> /// Checks if the submit button should be enabled or disabled. /// </summary> /// <returns>A boolean value determining if the submit button in the Environment and Credentials settings should be enabled.</returns> private bool IsSubmitButtonEnabled() { bool isCustomEnvironment = _environmentMapping.Keys.ElementAt(_currentEnvironment) == NEW_CUSTOM_ENV_KEY; if (isCustomEnvironment && (string.IsNullOrEmpty(_customEnvironmentCode) || _customEnvironmentCode.Length < 2 || string.IsNullOrEmpty(_customEnvironmentName) || !IsEnvironmentCodeValid() || !IsEnvironmentNameValid())) { return false; } return !_gameKitEditorManager.CredentialsSubmitted && !string.IsNullOrEmpty(_projectAlias) && IsGameNameValid() && !_awsAccountId.Equals(AWS_ACCOUNT_ID_LOADING) && !_awsAccountId.Equals(AWS_ACCOUNT_ID_EMPTY) && string.IsNullOrEmpty(_credentialPairErrorMessage); } /// <summary> /// Reads from the project name in _featureResourceManager or in the UI to gather and set the rest of the information needed in the Environment and Credentials settings. /// </summary> private void SetInitialState() { if (Application.internetReachability == NetworkReachability.NotReachable) { EditorUtility.DisplayDialog(L10n.Tr("No Internet Connection"), "Must have internet connection to configure AWS GameKit Settings. Close and re-open the settings window after connection is established.", "Ok"); Debug.LogWarning("No internet connection, you won't be able to customize AWS GameKit Settings until connection is established and settings window is re-opened."); return; } if (!string.IsNullOrEmpty(_featureResourceManager.GetAccountInfo().GameName)) { _isNewProject = false; _projectAlias = _featureResourceManager.GetAccountInfo().GameName; PopulateCustomEnvironments(); LoadLastUsedEnvironment(); LoadLastUsedRegion(); if (LoadAndSetAwsCredentials()) { SetValidCredentialsSubmitted(IsAccessKeyValid() && IsSecretKeyValid()); } } } /// <summary> /// Set whether valid credentials have been submitted.<br/><br/> /// /// If they have, inform the GameKitEditorManager and call OnValidCredentialsSubmitted(). /// </summary> /// <param name="areSubmitted">True if valid credentials have been submitted, false if not.</param> private void SetValidCredentialsSubmitted(bool areSubmitted) { _gameKitEditorManager.CredentialsSubmitted = areSubmitted; if (areSubmitted) { OnValidCredentialsSubmitted(); } } /// <summary> /// Attempt to set credentials on the FeatureDeploymentOrchestrator and refresh feature statuses. /// </summary> private void OnValidCredentialsSubmitted() { SetCredentialsDesc desc = new SetCredentialsDesc() { AccountCredentials = _featureResourceManager.GetAccountCredentials(), AccountInfo = _featureResourceManager.GetAccountInfo() }; if (_featureDeploymentOrchestrator.SetCredentials(desc) != GameKitErrors.GAMEKIT_SUCCESS) { // The error is already logged by SetCredentials. return; } _featureDeploymentOrchestrator.RefreshFeatureStatuses(response => { // Take no action, the response.ResultCode is always GAMEKIT_SUCCESS. }); _gameKitEditorManager.ReloadAllFeatureSettings(); } /// <summary> /// Attempts to load and set Aws credentials from the user's .aws/credentials file. /// </summary> /// <returns>True if the Aws credentials have successfully been reloaded into the environment and credentials page.</returns> private bool LoadAndSetAwsCredentials() { if (TryLoadAwsCredentialsFromFile()) { OnAwsCredentialsChanged(true); return true; } return false; } /// <summary> /// Opens a file explorer for users to select a pre-existing saveInfo.yml file. /// /// When a user selects a existing saveInfo.yml file their custom environments, last used environments, credentials and project alias will be set automatically. /// This change will be persisted after Unity is restarted. /// </summary> private void OnLoadCustomGameConfigFile() { string path = EditorUtility.OpenFilePanel("Locate existing saveInfo.yml file", "", "yml"); if (string.IsNullOrEmpty(path)) { Logging.LogInfo("Configuration file wasn't selected"); return; } string fileDirectory = Path.GetDirectoryName(path); Logging.LogInfo(L10n.Tr($"Parsed game name from config: {fileDirectory}")); _projectAlias = new DirectoryInfo(Path.GetDirectoryName(path)).Name; } /// <summary> /// Checks if the game name that has been input is valid. /// </summary> /// <returns>True if the game name is valid and false if the game name is not valid.</returns> private bool IsGameNameValid() { if (_projectAlias.Length > 12) { _projectAliasErrorMessage = L10n.Tr("The game title must have 1 - 12 characters"); return false; } if (InputContainsReservedKeyword(_projectAlias, out string reservedKeywordOutput)) { _projectAliasErrorMessage = L10n.Tr($"The game title cannot contain the substring '{reservedKeywordOutput}'."); return false; } return !InputContainsInvalidCharacters(_projectAlias, _validLowerCaseAndNumericalRx, ref _projectAliasErrorMessage); } /// <summary> /// Checks if the custom environment name that has been input is valid. /// </summary> /// <returns>True if the environment name is valid and false if the environment name is not valid.</returns> private bool IsEnvironmentNameValid() { if (_customEnvironmentName.Length < 1 || _customEnvironmentName.Length > 16) { _customEnvironmentNameErrorMessage = L10n.Tr("The environment name must have 1-16 characters"); return false; } return !InputContainsInvalidCharacters(_customEnvironmentName, _validAlphanumericRx, ref _customEnvironmentNameErrorMessage); } /// <summary> /// Checks if the custom environment code that has been input is valid. /// </summary> /// <returns>True if the environment code is valid and false if the environment code is not valid.</returns> private bool IsEnvironmentCodeValid() { if ((_customEnvironmentCode.Length < 2 && GUI.GetNameOfFocusedControl() != "EnvironmentCodeTextField") || _customEnvironmentCode.Length > 3) { _customEnvironmentCodeErrorMessage = L10n.Tr("The environment code must have 2-3 characters"); return false; } if (InputContainsReservedKeyword(_customEnvironmentCode, out string reservedKeywordOutput)) { _customEnvironmentCodeErrorMessage = L10n.Tr($"The environment code cannot contain the substring '{reservedKeywordOutput}'."); return false; } return !InputContainsInvalidCharacters(_customEnvironmentCode, _validLowerCaseAndNumericalRx, ref _customEnvironmentCodeErrorMessage); } /// <summary> /// Checks if the access key that has been input is valid. /// </summary> /// <returns>True if the access key is valid and false if the access key is not valid.</returns> private bool IsAccessKeyValid() { if (_accessKeyId.Length > 128) { _accessKeyIdErrorMessage = L10n.Tr("The access key ID must be less than 128 characters."); return false; } return !InputContainsInvalidCharacters(_accessKeyId, _validUpperCaseAndNumericalRx, ref _accessKeyIdErrorMessage); } /// <summary> /// Checks if the secret key that has been input is valid. /// </summary> /// <returns>True if the secret key is valid and false if the secret key is not valid.</returns> private bool IsSecretKeyValid() { bool isValid = string.IsNullOrEmpty(_secretAccessKey) || _secretAccessKey.Length <= 40; if (!isValid) { _secretKeyErrorMessage = "Enter a valid secret access key."; } else { _secretKeyErrorMessage = string.Empty; } return isValid; } /// <summary> /// Checks if the input matches a regex. If the input does not match will display all invalid characters as part of the error message. /// </summary> /// <param name="input">The string that will be checked for invalid characters.</param> /// <param name="validCharactersRegex">The regex that will be running against the input to see if there are invalid characters.</param> /// <param name="errorMessage">A reference to the error message that should be altered in the case there is an invalid character.</param> /// <returns></returns> private bool InputContainsInvalidCharacters(string input, Regex validCharactersRegex, ref string errorMessage) { char[] invalidCharArray = input.Where(c => !validCharactersRegex.IsMatch(c.ToString())).ToArray(); if (invalidCharArray.Length != 0) { errorMessage = L10n.Tr($"Invalid characters: {string.Join(", ", invalidCharArray)}."); return true; } errorMessage = string.Empty; return false; } /// <summary> /// Checks if a string contains any reserved keywords that can cause issues with deployment. /// </summary> /// <param name="input">The string that is being checked for reserved keywords.</param> /// <param name="reservedKeywordOutput">If the input string does contain a reserved keyword, reservedKeywordOutput will be set to the first reserved keyword that was found. Otherwise reservedKeywordOutput will be empty.</param> /// <returns>True if the input contains reserved keywords, false if the input does not contain any reserved keywords.</returns> private bool InputContainsReservedKeyword(string input, out string reservedKeywordOutput) { reservedKeywordOutput = ""; foreach (string reservedKeyword in RESERVED_KEYWORDS) { if (input.Contains(reservedKeyword)) { reservedKeywordOutput = reservedKeyword; return true; } } return false; } /// <summary> /// Gets the custom user created environments and adds the environments to the maps and options. /// </summary> private void PopulateCustomEnvironments() { IDictionary<string, string> environments = _featureResourceManager.GetCustomEnvironments(); foreach (KeyValuePair<string, string> kvp in environments) { if (!_environmentMapping.ContainsKey(kvp.Key)) { _environmentMapping.Add(kvp.Key, kvp.Value); _environmentOptions.Add(kvp.Value); } if (!_environmentMapping.Values.Contains(kvp.Value)) { _environmentOptions.Remove(_environmentMapping[kvp.Key]); _environmentMapping.Remove(kvp.Key); _environmentMapping.Add(kvp.Key, kvp.Value); _environmentOptions.Add(kvp.Value); } } } /// <summary> /// Loads the user's last used environment from their saveInfo.yml file. /// </summary> private void LoadLastUsedEnvironment() { string lastUsedEnvironmentCode = _featureResourceManager.GetLastUsedEnvironment(); string lastUsedEnvironmentValue = _environmentMapping[lastUsedEnvironmentCode]; _currentEnvironment = _environmentOptions.IndexOf(lastUsedEnvironmentValue); _featureResourceManager.SetEnvironment(GetSelectedEnvironmentKey()); } /// <summary> /// Loads the user's last used region from their saveInfo.yml file. /// </summary> private void LoadLastUsedRegion() { string lastUsedRegionCode = _featureResourceManager.GetLastUsedRegion(); string lastUsedRegionValue = _regionMapping[lastUsedRegionCode]; _currentRegion = _regionOptions.IndexOf(lastUsedRegionValue); } /// <summary> /// Attempts to find a user's Aws credentials in their .aws/credentials file based on their project alias and environment key. /// </summary> /// <returns>Returns true if the Aws credentials have been found and set properly in the corresponding input boxes.</returns> private bool TryLoadAwsCredentialsFromFile() { string envKey = GetSelectedEnvironmentKey(); if (envKey == NEW_CUSTOM_ENV_KEY) { envKey = _customEnvironmentCode; } _credentialsManager.SetGameName(_projectAlias); _credentialsManager.SetEnv(envKey); string accessKey = _credentialsManager.GetAccessKey(); string secretKey = _credentialsManager.GetSecretAccessKey(); if (!string.IsNullOrEmpty(accessKey) && !string.IsNullOrEmpty(secretKey)) { _accessKeyId = accessKey; _secretAccessKey = secretKey; return true; } if (!_isNewProject && !string.IsNullOrEmpty(_accessKeyId) && !string.IsNullOrEmpty(_secretAccessKey)) { _showNewEnvironmentNotification = true; } return false; } /// <summary> /// Retrieves the user's Aws account id based on their input access key and secret key. /// </summary> private void RetrieveAccountId() { _awsAccountId = AWS_ACCOUNT_ID_LOADING; _credentialPairErrorMessage = string.Empty; GetAWSAccountIdDescription accountCredentials; accountCredentials.AccessKey = _accessKeyId; accountCredentials.AccessSecret = _secretAccessKey; void AccountIdCallback(StringCallbackResult accountId) { if (!string.IsNullOrEmpty(accountId.ResponseValue)) { _awsAccountId = accountId.ResponseValue; } } _featureResourceManager.GetAccountId(accountCredentials, AccountIdCallback); } /// <summary> /// Populates the environment map with default regions. /// </summary> private void PopulateDefaultEnvironments() { _environmentMapping["dev"] = "Development"; _environmentMapping["qa"] = "QA"; _environmentMapping["stg"] = "Staging"; _environmentMapping["prd"] = "Production"; _environmentMapping[NEW_CUSTOM_ENV_KEY] = "Add new environment"; _environmentOptions.Clear(); foreach (KeyValuePair<string, string> environmentKeyValuePair in _environmentMapping) { _environmentOptions.Add(environmentKeyValuePair.Value); } } /// <summary> /// Populates the region map and options with all supported Aws regions. /// </summary> private void PopulateRegions() { // List of all AWS regions (supported and unsupported) // All regions added here to also keep track of currently unsupported ones _regionOptions.Clear(); foreach (AwsRegion awsRegion in Enum.GetValues(typeof(AwsRegion))) { if (awsRegion.IsRegionSupported()) { _regionMapping[awsRegion.GetRegionKey()] = awsRegion.GetRegionDescription(); _regionOptions.Add(awsRegion.GetRegionDescription()); } } } /// <summary> /// When project alias is changed, check if the input is valid and if credentials already exist /// </summary> private void OnProjectAliasChanged() { if (IsGameNameValid()) { if (_credentialsManager.CheckAwsProfileExists(_projectAlias, GetSelectedEnvironmentKey())) { PopulateCustomEnvironments(); LoadAndSetAwsCredentials(); } } } /// <summary> /// Checks if the new environment selected has corresponding AWS credentials and sets the new environment in the feature resource manager /// </summary> private void OnEnvironmentSelectionChanged() { if (GetSelectedEnvironmentKey() != NEW_CUSTOM_ENV_KEY) { _showNewEnvironmentNotification = false; string previousAwsAccessKey = _accessKeyId; string previousAwsSecretKey = _secretAccessKey; if (_credentialsManager.CheckAwsProfileExists(_projectAlias, GetSelectedEnvironmentKey())) { TryLoadAwsCredentialsFromFile(); if (!previousAwsAccessKey.Equals(_accessKeyId) || !previousAwsSecretKey.Equals(_secretAccessKey)) { OnAwsCredentialsChanged(IsAccessKeyValid()); } } } else { _showNewEnvironmentNotification = true; } _featureResourceManager.SetEnvironment(GetSelectedEnvironmentKey()); } /// <summary> /// Determines if the user's access and secret keys are valid and if they are calls the Aws backend to retrieve their account Id. /// </summary> /// <param name="areFieldsValid">Boolean value stating if a changed field is valid, if not there is no need to attempt to continue getting the account id.</param> private void OnAwsCredentialsChanged(bool areFieldsValid) { _showNewEnvironmentNotification = false; if (!areFieldsValid) { _credentialPairErrorMessage = string.Empty; _awsAccountId = AWS_ACCOUNT_ID_EMPTY; return; } if (_accessKeyId.Length != 20 || _secretAccessKey.Length != 40) { if (!string.IsNullOrEmpty(_accessKeyId) && !string.IsNullOrEmpty(_secretAccessKey)) { _credentialPairErrorMessage = AWS_ACCOUNT_INVALID_PAIR; _awsAccountId = AWS_ACCOUNT_ID_EMPTY; } SetValidCredentialsSubmitted(false); return; } AccountDetails accountDetails = GetAccountDetails(); if (Application.internetReachability != NetworkReachability.NotReachable) { if (_featureResourceManager.IsAccountInfoValid(accountDetails)) { RetrieveAccountId(); return; } _credentialPairErrorMessage = AWS_ACCOUNT_INVALID_PAIR; _awsAccountId = AWS_ACCOUNT_ID_EMPTY; } else { _credentialPairErrorMessage = INTERNET_CONNECTIVITY_ISSUE; _awsAccountId = AWS_ACCOUNT_ID_EMPTY; } } /// <summary> /// Displays dialog about changing environment before setting the credentials submitted value to false /// </summary> private void OnChangeEnvironmentAndCredentials() { if (EditorUtility.DisplayDialog(L10n.Tr("Change Environment"), CHANGE_ENVIRONMENT_WARNING, "Ok", "Cancel")) { SetValidCredentialsSubmitted(false); _onEnvironmentOrRegionChange.Invoke(); } } /// <summary> /// Revert credentials back to a user's last used environments, reload the AWS credentials and mark credentials submitted as true. /// </summary> private void OnCancelEnvironmentAndCredentialsChange() { LoadLastUsedEnvironment(); LoadLastUsedRegion(); if (TryLoadAwsCredentialsFromFile()) { bool areCredentialsValid = IsAccessKeyValid() && IsSecretKeyValid(); OnAwsCredentialsChanged(areCredentialsValid); SetValidCredentialsSubmitted(areCredentialsValid); if (areCredentialsValid) { // Text Fields only update after they loose focus, in order to force the valid access key or secret key to replace the invalid one displayed, we need to force them to lose focus. GUI.FocusControl(null); } } _featureResourceManager.SetEnvironment(GetSelectedEnvironmentKey()); } /// <summary> /// Stores the user's current credentials and bootstraps their current environment /// </summary> private void OnSubmit() { _showNewEnvironmentNotification = false; bool isCustomEnvironment = GetSelectedEnvironmentKey() == NEW_CUSTOM_ENV_KEY; AccountDetails accountDetails = GetAccountDetails(); _featureResourceManager.SetAccountDetails(accountDetails); uint result = _featureResourceManager.BootstrapAccount(); if (result == GameKitErrors.GAMEKIT_SUCCESS) { // Save credentials _credentialsManager.SetGameName(accountDetails.GameName); _credentialsManager.SetEnv(accountDetails.Environment); _credentialsManager.SaveCredentials(accountDetails.AccessKey, accountDetails.AccessSecret); _featureResourceManager.SaveSettings(); // Save custom environment if (isCustomEnvironment) { _featureResourceManager.SaveCustomEnvironment(_customEnvironmentCode, _customEnvironmentName); PopulateCustomEnvironments(); _currentEnvironment = GetEnvironmentKeyIndex(_customEnvironmentCode); _customEnvironmentName = string.Empty; _customEnvironmentCode = string.Empty; } // Update client config file string gameAlias = _featureResourceManager.GetGameName(); string environmentCode = _featureResourceManager.GetLastUsedEnvironment(); if (!_gameKitManager.DoesConfigFileExist(gameAlias, environmentCode)) { _featureResourceManager.CreateEmptyClientConfigFile(); } _gameKitManager.CopyAndReloadConfigFile(gameAlias, environmentCode); SetValidCredentialsSubmitted(true); _isNewProject = false; } else if (result == GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_TOO_MANY_BUCKETS) { _credentialPairErrorMessage = AWS_ACCOUNT_HAS_TOO_MANY_BUCKETS; Logging.LogError(L10n.Tr($"The AWS account provided has reached its limit on S3 buckets. Please navigate to the AWS console to delete unnecessary buckets or request an increase: error {result}")); } else { _credentialPairErrorMessage = AWS_ACCOUNT_NOT_VALIDATED; Logging.LogError(L10n.Tr($"The user credentials you provided cannot be validated: error {result}")); _awsAccountId = AWS_ACCOUNT_ID_EMPTY; } } /// <summary> /// Creates and returns an account details structure based on the user's current inputs. /// </summary> /// <returns>Account details struct based on the user's current input.</returns> private AccountDetails GetAccountDetails() { string envCode = GetSelectedEnvironmentKey(); if (envCode == NEW_CUSTOM_ENV_KEY) { envCode = _customEnvironmentCode; } AccountDetails accountDetails = new AccountDetails { Environment = envCode, AccountId = _awsAccountId, GameName = _projectAlias, Region = GetCurrentRegionKey(), AccessKey = _accessKeyId, AccessSecret = _secretAccessKey }; return accountDetails; } /// <summary> /// Gets the index of a specified environment key within the environment map /// </summary> /// <param name="environmentKey">The environment key of which the index should be retrieved</param> /// <returns>The index of the passed in environment key</returns> private int GetEnvironmentKeyIndex(string environmentKey) { return _environmentMapping.Keys.ToList().IndexOf(environmentKey); } /// <summary> /// Gets the currently selected environment key value based on the current environment index. /// </summary> /// <returns>Environment key based on the currently selected environment.</returns> private string GetSelectedEnvironmentKey() { return _environmentMapping.Keys.ElementAt(_currentEnvironment); } /// <summary> /// Gets the currently selected region key value based on the current region index. /// </summary> /// <returns>Region key based on the currently selected region.</returns> private string GetCurrentRegionKey() { return _regionMapping.Keys.ElementAt(_currentRegion); } } }
1,171
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.IO; using System.Linq; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Features.GameKitGameSaving; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Windows.Settings.Pages.GameStateCloudSaving { [Serializable] public class GameStateCloudSavingExamplesTab : FeatureExamplesTab { private const string GAME_SAVING_TESTING_DIRECTORY_NAME = "Game_Saving"; public override FeatureType FeatureType => FeatureType.GameStateCloudSaving; private enum InitializationLevel { Uninitialized, InProgress, Initialized }; // Dependencies private IGameSavingProvider _gameSaving; private IFileManager _fileManager; // Examples [SerializeField] private SaveSlotExampleUI _saveSlotExampleUI; [SerializeField] private LoadSlotExampleUI _loadSlotExampleUI; [SerializeField] private DeleteSlotExampleUI _deleteSlotExampleUI; [SerializeField] private GetSlotSyncStatusExampleUI _getSlotSyncStatusExampleUI; [SerializeField] private GetAllSlotSyncStatusesExampleUI _getAllSlotSyncStatusesExampleUI; // State [SerializeField] private bool _areCachedSlotsDisplayed; private InitializationLevel _initializationLevel = InitializationLevel.Uninitialized; private string _saveInfoDirectory; private IDictionary<string, Slot> _slots = new Dictionary<string, Slot>(); public override void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { _gameSaving = dependencies.GameSaving; _fileManager = dependencies.FileManager; _saveInfoDirectory = _fileManager.GetGameKitSaveDirectory(); _saveSlotExampleUI.Initialize(CallSaveSlot, serializedProperty.FindPropertyRelative(nameof(_saveSlotExampleUI))); _loadSlotExampleUI.Initialize(CallLoadSlot, serializedProperty.FindPropertyRelative(nameof(_loadSlotExampleUI))); _deleteSlotExampleUI.Initialize(CallDeleteSlot, serializedProperty.FindPropertyRelative(nameof(_deleteSlotExampleUI))); _getSlotSyncStatusExampleUI.Initialize(CallGetSlotSyncStatus, serializedProperty.FindPropertyRelative(nameof(_getSlotSyncStatusExampleUI))); _getAllSlotSyncStatusesExampleUI.Initialize(CallGetAllSlotSyncStatuses, serializedProperty.FindPropertyRelative(nameof(_getAllSlotSyncStatusesExampleUI))); base.Initialize(dependencies, serializedProperty); } protected override void DrawExamples() { InitializeIfLoggedIn(); UninitializeIfLoggedOut(); _saveSlotExampleUI.OnGUI(); _loadSlotExampleUI.OnGUI(); _deleteSlotExampleUI.OnGUI(); _getSlotSyncStatusExampleUI.OnGUI(); _getAllSlotSyncStatusesExampleUI.OnGUI(); EditorGUILayoutElements.SectionDivider(); DrawCachedSlots(); } #region Helpers public static void DrawSaveSlot(Slot slot, int indentationLevel = 1) { EditorGUILayoutElements.TextField("Slot Name", slot.SlotName, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Sync Status", Enum.GetName(typeof(SlotSyncStatus), slot.SlotSyncStatus), indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Metadata Local", slot.MetadataLocal, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Metadata Cloud", slot.MetadataCloud, indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Size Local", slot.SizeLocal.ToString(), indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Size Cloud", slot.SizeCloud.ToString(), indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Last Modified Local", TimeUtils.EpochTimeToString(slot.LastModifiedLocal), indentationLevel, isEnabled: false); EditorGUILayoutElements.TextField("Last Modified Cloud", TimeUtils.EpochTimeToString(slot.LastModifiedCloud), indentationLevel, isEnabled: false); } public static void DrawSaveSlots(Slot[] slots, int indentationLevel = 1) { for (int i = 0; i < slots.Length; i++) { DrawSaveSlot(slots[i], indentationLevel); if (i != slots.Length - 1) { EditorGUILayoutElements.SectionDivider(); } } } private void DrawCachedSlots() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleContainer)) { _areCachedSlotsDisplayed = EditorGUILayout.Foldout(_areCachedSlotsDisplayed, L10n.Tr("Cached Slots"), SettingsGUIStyles.Page.FoldoutTitle); if (_areCachedSlotsDisplayed) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleFoldoutContainer)) { if (!_userInfo.IsLoggedIn) { EditorGUILayoutElements.Description(L10n.Tr("Log in and initialize <b>Game Saving</b> to view your cached slots."), 0); } else if (_initializationLevel != InitializationLevel.Initialized) { EditorGUILayoutElements.Description(L10n.Tr("Initializing cached slots..."), 0); } else if (_slots.Count == 0) { EditorGUILayoutElements.Description(L10n.Tr("No cached slots found. Try creating a new save slot by calling the <b>Save Slot</b> API."), 0); } else { DrawSaveSlots(_slots.Values.ToArray(), 0); } } } } } private string GetUserSaveInfoDirectory(string userName, string userId) { return $"{_saveInfoDirectory}/{userName}_{userId}/{GAME_SAVING_TESTING_DIRECTORY_NAME}"; } private string GetSaveInfoFilePath(string userName, string userId, string slotName) { return $"{GetUserSaveInfoDirectory(userName, userId)}/{slotName}{GameSavingConstants.SAVE_INFO_FILE_EXTENSION}"; } private void UpdateCachedSlots(Slot[] slots) { _slots.Clear(); foreach (Slot slot in slots) { _slots.Add(slot.SlotName, slot); } } private void InitializeIfLoggedIn() { // If the user is logged in, ensure that we are initialized if (_userInfo.IsLoggedIn && _initializationLevel == InitializationLevel.Uninitialized) { // We can't initialize unless Game Saving has been deployed to the account in some fashion; check for Game Saving in the config file. // This check is only necessary for the editor examples. In a real game, you can rely on your Game Saving feature being deployed. // In that situation, simply initialize GameSaving with InitializeGameSavingForUser(). if (_gameKitManager.AreFeatureSettingsLoaded(FeatureType.GameStateCloudSaving)) { _initializationLevel = InitializationLevel.InProgress; InitializeGameSavingForUser(); } else { Debug.Log($"Cannot initialize Game Saving for user {_userInfo.UserName}, as the feature does not appear to be deployed."); } } } private void UninitializeIfLoggedOut() { // If the user just logged out, clear local state and uninitialize if (!_userInfo.IsLoggedIn && _initializationLevel == InitializationLevel.Initialized) { _slots.Clear(); _initializationLevel = InitializationLevel.Uninitialized; } } #endregion #region GameSaving API Calls private void InitializeGameSavingForUser() { // Ensure that any synced slots for a previous user are cleared out _gameSaving.ClearSyncedSlots(); string[] saveInfoFiles = _fileManager.ListFiles(GetUserSaveInfoDirectory(_userInfo.UserName, _userInfo.UserId), $"*{GameSavingConstants.SAVE_INFO_FILE_EXTENSION}"); AddLocalSlotsDesc addLocalSlotsDesc = new AddLocalSlotsDesc { LocalSlotInformationFilePaths = saveInfoFiles }; Debug.Log($"Calling GameSaving.AddLocalSlots() with {addLocalSlotsDesc}"); _gameSaving.AddLocalSlots(addLocalSlotsDesc, () => { Debug.Log("GameSaving.AddLocalSlots() completed"); Debug.Log($"Calling GameSaving.GetAllSlotSyncStatuses() for user {_userInfo.UserName}"); _gameSaving.GetAllSlotSyncStatuses((SlotListResult result) => { Debug.Log($"GameSaving.GetAllSlotSyncStatuses() completed with result code {GameKitErrorConverter.GetErrorName(result.ResultCode)}"); if (result.ResultCode == GameKitErrors.GAMEKIT_SUCCESS) { /* * Check for sync conflicts: * * In your own game, when you call GetAllSlotSyncStatuses() at the game's startup, * you would want to loop through the "CachedSlots" parameter and look for any slots with SlotSyncStatus == IN_CONFLICT. * * If any slots are in conflict, you'd likely want to present this conflict to the player and let them decide which file to keep: the local save or the cloud save. */ UpdateCachedSlots(result.CachedSlots); } _initializationLevel = InitializationLevel.Initialized; }); }); } private void CallSaveSlot() { if (!System.IO.File.Exists(_saveSlotExampleUI.FilePath)) { _saveSlotExampleUI.ResultCode = GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_FILE_FAILED_TO_OPEN; } SaveSlotDesc saveSlotDesc = new SaveSlotDesc { SaveInfoFilePath = GetSaveInfoFilePath(_userInfo.UserName, _userInfo.UserId, _saveSlotExampleUI.SlotName), Data = _fileManager.ReadAllBytes(_saveSlotExampleUI.FilePath), EpochTime = _fileManager.GetFileLastModifiedMilliseconds(_saveSlotExampleUI.FilePath), Metadata = _saveSlotExampleUI.Metadata, OverrideSync = _saveSlotExampleUI.OverrideSync, SlotName = _saveSlotExampleUI.SlotName }; Debug.Log($"Calling GameSaving.SaveSlot() with {saveSlotDesc}"); _gameSaving.SaveSlot(saveSlotDesc, (SlotActionResult result) => { Debug.Log($"GameSaving.SaveSlot() completed with result code {GameKitErrorConverter.GetErrorName(result.ResultCode)}"); _saveSlotExampleUI.ResultCode = result.ResultCode; _saveSlotExampleUI.ActionedSlot = result.ActionedSlot; UpdateCachedSlots(result.CachedSlots); }); } private void CallLoadSlot() { if (!_slots.ContainsKey(_loadSlotExampleUI.SlotName)) { Debug.LogWarning($"Cannot load slot {_loadSlotExampleUI.SlotName}, as it doesn't exist. Please sync your slot status by calling GetAllSlotSyncStatuses()."); _loadSlotExampleUI.ResultCode = GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND; _loadSlotExampleUI.ActionedSlot = new Slot(); return; } /* * Before calling LoadSlot(), you need to pre-allocate enough bytes to hold the cloud save file. * * We recommend determining how many bytes are needed by caching the Slot object * from the most recent Game Saving API call before calling LoadSlot(). From this cached object, you * can get the SizeCloud of the slot you are going to download. Note: the SizeCloud will be incorrect * if the cloud save has been updated from another device since the last time this device cached the * Slot. In that case, call GetSlotSyncStatus() to get the accurate size. * * In this example, we cache the Slot object from *every* Game Saving API call because we * allow you to test out the Game Saving APIs in any order. * * Alternative to caching, you can call GetSlotSyncStatus(slotName) to get the size of the cloud file. * However, this has extra latency compared to caching the results of the previous Game Saving API call. */ long size = _slots[_loadSlotExampleUI.SlotName].SizeCloud; byte[] data = new byte[size]; LoadSlotDesc loadSlotDesc = new LoadSlotDesc { SaveInfoFilePath = GetSaveInfoFilePath(_userInfo.UserName, _userInfo.UserId, _loadSlotExampleUI.SlotName), Data = data, OverrideSync = _loadSlotExampleUI.OverrideSync, SlotName = _loadSlotExampleUI.SlotName, }; Debug.Log($"Calling GameSaving.LoadSlot() with {loadSlotDesc}"); _gameSaving.LoadSlot(loadSlotDesc, (SlotDataResult result) => { Debug.Log($"GameSaving.LoadSlot() completed with result code {GameKitErrorConverter.GetErrorName(result.ResultCode)}"); _loadSlotExampleUI.ResultCode = result.ResultCode; if (result.ResultCode == GameKitErrors.GAMEKIT_SUCCESS) { try { _fileManager.WriteAllBytes(_loadSlotExampleUI.FilePath, result.Data); } catch (Exception e) when (e is ArgumentException || e is NullReferenceException || e is IOException) { _loadSlotExampleUI.ResultCode = GameKitErrors.GAMEKIT_ERROR_FILE_WRITE_FAILED; Debug.LogException(e); } } _loadSlotExampleUI.ActionedSlot = result.ActionedSlot; UpdateCachedSlots(result.CachedSlots); }); } private void CallDeleteSlot() { if (!_slots.ContainsKey(_deleteSlotExampleUI.SlotName)) { Debug.LogWarning($"Cannot delete slot {_deleteSlotExampleUI.SlotName}, as it doesn't exist."); _deleteSlotExampleUI.ResultCode = GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND; return; } Debug.Log($"Calling GameSaving.DeleteSlot() for slot {_deleteSlotExampleUI.SlotName}"); _gameSaving.DeleteSlot(_deleteSlotExampleUI.SlotName, (SlotActionResult result) => { Debug.Log($"GameSaving.DeleteSlot() completed with result code {GameKitErrorConverter.GetErrorName(result.ResultCode)}"); _deleteSlotExampleUI.ResultCode = result.ResultCode; if (result.ResultCode == GameKitErrors.GAMEKIT_SUCCESS) { _slots.Remove(result.ActionedSlot.SlotName); /* * Delete the local SaveInfo.json file corresponding to the deleted save slot: * * In your own game, you'll probably want to delete the local save file and corresponding SaveInfo.json file from the device after calling DeleteSlot(). * If you keep the SaveInfo.json file, then next time the game boots up this library will recommend re-uploading the save file to the cloud when * you call GetAllSlotSyncStatuses() or GetSlotSyncStatus(). * * Note: DeleteSlot() doesn't delete any local files from the device. It only deletes data from the cloud and from memory (i.e. the cached slot). */ string saveInfoPath = GetSaveInfoFilePath(_userInfo.UserName, _userInfo.UserId, result.ActionedSlot.SlotName); _fileManager.DeleteFile(saveInfoPath); } }); } private void CallGetSlotSyncStatus() { if (!_slots.ContainsKey(_getSlotSyncStatusExampleUI.SlotName)) { Debug.Log($"Cannot get sync status for slot {_getSlotSyncStatusExampleUI.SlotName}, as it isn't cached. Either create a new slot by calling SaveSlot(), or refresh the list of available slots with GetAllSlotSyncStatuses()."); } Debug.Log($"Calling GameSaving.GetSlotSyncStatus() for slot {_getSlotSyncStatusExampleUI.SlotName}"); _gameSaving.GetSlotSyncStatus(_getSlotSyncStatusExampleUI.SlotName, (SlotActionResult result) => { Debug.Log($"GameSaving.GetSlotSyncStatus() completed with result code {GameKitErrorConverter.GetErrorName(result.ResultCode)}"); _getSlotSyncStatusExampleUI.ResultCode = result.ResultCode; _getSlotSyncStatusExampleUI.ActionedSlot = result.ActionedSlot; UpdateCachedSlots(result.CachedSlots); }); } private void CallGetAllSlotSyncStatuses() { Debug.Log($"Calling GameSaving.GetAllSlotSyncStatuses()"); _gameSaving.GetAllSlotSyncStatuses((SlotListResult result) => { Debug.Log($"GameSaving.GetAllSlotSyncStatuses() completed with result code {GameKitErrorConverter.GetErrorName(result.ResultCode)}"); _getAllSlotSyncStatusesExampleUI.ResultCode = result.ResultCode; _getAllSlotSyncStatusesExampleUI.Slots = result.CachedSlots; UpdateCachedSlots(result.CachedSlots); }); } #endregion } #region Example [Serializable] public class SaveSlotExampleUI : GameKitExampleUI { public override string ApiName => "Save Slot"; protected override bool _shouldDisplayResponse => true; public string SlotName; public string Metadata; public string FilePath; public bool OverrideSync; public Slot ActionedSlot = new Slot(); protected override void DrawInput() { PropertyField(nameof(SlotName), "Slot Name"); PropertyField(nameof(Metadata), "Metadata"); SerializedProperty filePath = _serializedProperty.FindPropertyRelative(nameof(FilePath)); filePath.stringValue = EditorGUILayoutElements.FileSelection("File Path", filePath.stringValue, "Select a file", "", 0); PropertyField(nameof(OverrideSync), "Override Sync"); } protected override void DrawOutput() { GameStateCloudSavingExamplesTab.DrawSaveSlot(ActionedSlot); } } [Serializable] public class LoadSlotExampleUI : GameKitExampleUI { public override string ApiName => "Load Slot"; protected override bool _shouldDisplayResponse => true; public string SlotName; public string FilePath; public bool OverrideSync; public Slot ActionedSlot = new Slot(); protected override void DrawInput() { PropertyField(nameof(SlotName), "Slot Name"); SerializedProperty filePath = _serializedProperty.FindPropertyRelative(nameof(FilePath)); filePath.stringValue = EditorGUILayoutElements.FileSelection("File Path", filePath.stringValue, "Select a file", "", 0, openingFile: false); PropertyField(nameof(OverrideSync), "Override Sync"); } protected override void DrawOutput() { GameStateCloudSavingExamplesTab.DrawSaveSlot(ActionedSlot); } } [Serializable] public class DeleteSlotExampleUI : GameKitExampleUI { public override string ApiName => "Delete Slot"; public string SlotName; protected override void DrawInput() { PropertyField(nameof(SlotName), "Slot Name"); } } [Serializable] public class GetSlotSyncStatusExampleUI : GameKitExampleUI { public override string ApiName => "Get Slot Sync Status"; protected override bool _shouldDisplayResponse => true; public string SlotName; public Slot ActionedSlot = new Slot(); protected override void DrawInput() { PropertyField(nameof(SlotName), "Slot Name"); } protected override void DrawOutput() { GameStateCloudSavingExamplesTab.DrawSaveSlot(ActionedSlot); } } [Serializable] public class GetAllSlotSyncStatusesExampleUI : GameKitExampleUI { public override string ApiName => "Get All Slot Sync Statuses"; protected override bool _shouldDisplayResponse => true; public Slot[] Slots = new Slot[0]; protected override void DrawOutput() { GameStateCloudSavingExamplesTab.DrawSaveSlots(Slots); } } #endregion }
494
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; namespace AWS.GameKit.Editor.Windows.Settings.Pages.GameStateCloudSaving { [Serializable] public class GameStateCloudSavingPage : FeaturePage { public override FeatureType FeatureType => FeatureType.GameStateCloudSaving; [SerializeField] private GameStateCloudSavingSettingsTab _gameStateCloudSavingSettingsTab; [SerializeField] private GameStateCloudSavingExamplesTab _gameStateCloudSavingExamplesTab; public void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { _gameStateCloudSavingSettingsTab.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_gameStateCloudSavingSettingsTab))); _gameStateCloudSavingExamplesTab.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_gameStateCloudSavingExamplesTab))); base.Initialize(GetDefaultTabs(_gameStateCloudSavingSettingsTab, _gameStateCloudSavingExamplesTab), dependencies); } } }
32
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Models.FeatureSettings; namespace AWS.GameKit.Editor.Windows.Settings.Pages.GameStateCloudSaving { [Serializable] public class GameStateCloudSavingSettingsTab : FeatureSettingsTab { public override FeatureType FeatureType => FeatureType.GameStateCloudSaving; protected override IEnumerable<IFeatureSetting> FeatureSpecificSettings => new List<IFeatureSetting>() { _maxSlotsPerPlayer }; protected override IEnumerable<SecretSetting> FeatureSecrets => new List<SecretSetting>() { // No feature secrets. }; // Feature Settings [SerializeField] private FeatureSettingInt _maxSlotsPerPlayer = new FeatureSettingInt("max_save_slots_per_player", defaultValue: 10); private static readonly int MINIMUM_SLOTS_PER_PLAYER = 0; // This is not a hard limit. You may increase this value up to Int32.MaxValue, although Unity's UI slider overflows after about 2140000000. private static readonly int MAXIMUM_SLOTS_PER_PLAYER = 100; protected override void DrawSettings() { SerializedProperty maxSlotsPerPlayerProperty = GetFeatureSettingProperty(nameof(_maxSlotsPerPlayer)); maxSlotsPerPlayerProperty.intValue = EditorGUILayoutElements.IntSlider(L10n.Tr("Maximum save slots"), maxSlotsPerPlayerProperty.intValue, MINIMUM_SLOTS_PER_PLAYER, MAXIMUM_SLOTS_PER_PLAYER, indentationLevel: 0); } } }
49
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // System using System; using System.Collections.Generic; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Features.GameKitIdentity; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.Windows.Settings.Pages.IdentityAndAuthentication { [Serializable] public class IdentityAndAuthenticationExamplesTab : FeatureExamplesTab { public override FeatureType FeatureType => FeatureType.Identity; protected override bool RequiresLogin => false; // Dependencies private IIdentityProvider _identity; // Examples [SerializeField] private RegisterExampleUI _registerExampleUI; [SerializeField] private ResendConfirmationExampleUI _resendConfirmationExampleUI; [SerializeField] private ConfirmEmailExampleUI _confirmEmailExampleUI; [SerializeField] private LoginExampleUI _loginExampleUI; [SerializeField] private GetUserExampleUI _getUserExampleUI; [SerializeField] private ForgotPasswordExampleUI _forgotPasswordExampleUI; [SerializeField] private ConfirmForgotPasswordExampleUI _confirmForgotPasswordExampleUI; [SerializeField] private OpenFacebookLoginExampleUI _openFacebookLoginExampleUI; [SerializeField] private LogoutExampleUI _logoutExampleUI; public override void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { _identity = dependencies.Identity; _registerExampleUI.Initialize(CallRegister, serializedProperty.FindPropertyRelative(nameof(_registerExampleUI))); _resendConfirmationExampleUI.Initialize(CallResendConfirmation, serializedProperty.FindPropertyRelative(nameof(_resendConfirmationExampleUI))); _confirmEmailExampleUI.Initialize(CallConfirmEmail, serializedProperty.FindPropertyRelative(nameof(_confirmEmailExampleUI))); _loginExampleUI.Initialize(CallLogin, serializedProperty.FindPropertyRelative(nameof(_loginExampleUI))); _getUserExampleUI.Initialize(CallGetUser, serializedProperty.FindPropertyRelative(nameof(_getUserExampleUI))); _forgotPasswordExampleUI.Initialize(CallForgotPassword, serializedProperty.FindPropertyRelative(nameof(_forgotPasswordExampleUI))); _confirmForgotPasswordExampleUI.Initialize(CallConfirmForgotPassword, serializedProperty.FindPropertyRelative(nameof(_confirmForgotPasswordExampleUI))); _openFacebookLoginExampleUI.Initialize(CallOpenFacebookLogin, serializedProperty.FindPropertyRelative(nameof(_openFacebookLoginExampleUI))); _logoutExampleUI.Initialize(CallLogout, serializedProperty.FindPropertyRelative(nameof(_logoutExampleUI))); _displayLoginWidget = false; base.Initialize(dependencies, serializedProperty); } #region Draw Examples protected override void DrawExamples() { _registerExampleUI.OnGUI(); _resendConfirmationExampleUI.OnGUI(); _confirmEmailExampleUI.OnGUI(); _loginExampleUI.OnGUI(); _getUserExampleUI.OnGUI(); _forgotPasswordExampleUI.OnGUI(); _confirmForgotPasswordExampleUI.OnGUI(); _openFacebookLoginExampleUI.OnGUI(); _logoutExampleUI.OnGUI(); } #endregion #region Identity API Calls private void CallRegister() { UserRegistration userRegistration = new UserRegistration { UserName = _registerExampleUI.UserName, Password = _registerExampleUI.Password, Email = _registerExampleUI.Email }; Debug.Log($"Calling Identity.Register() with {userRegistration}"); _identity.Register(userRegistration, (uint resultCode) => { Debug.Log($"Identity.Register() completed with result code {resultCode}"); _registerExampleUI.ResultCode = resultCode; }); } private void CallResendConfirmation() { ResendConfirmationCodeRequest resendConfirmationCodeRequest = new ResendConfirmationCodeRequest { UserName = _resendConfirmationExampleUI.UserName }; Debug.Log($"Calling Identity.ResendConfirmationCode() with {resendConfirmationCodeRequest}"); _identity.ResendConfirmationCode(resendConfirmationCodeRequest, (uint resultCode) => { Debug.Log($"Identity.ResendConfirmationCode() completed with result code {resultCode}"); _resendConfirmationExampleUI.ResultCode = resultCode; }); } private void CallConfirmEmail() { ConfirmRegistrationRequest confirmRegistrationRequest = new ConfirmRegistrationRequest { UserName = _confirmEmailExampleUI.UserName, ConfirmationCode = _confirmEmailExampleUI.ConfirmationCode }; Debug.Log($"Calling Identity.ConfirmRegistration() with {confirmRegistrationRequest}"); _identity.ConfirmRegistration(confirmRegistrationRequest, (uint resultCode) => { Debug.Log($"Identity.ConfirmRegistration() completed with result code {resultCode}"); _confirmEmailExampleUI.ResultCode = resultCode; }); } private void CallLogin() { UserLogin userLogin = new UserLogin { UserName = _loginExampleUI.UserName, Password = _loginExampleUI.Password }; Debug.Log($"Calling Identity.Login() with {userLogin}"); _identity.Login(userLogin, (uint resultCode) => { Debug.Log($"Identity.Login() completed with result code {resultCode}"); _loginExampleUI.ResultCode = resultCode; _userInfo.UserName = userLogin.UserName; }); } private void CallGetUser() { Debug.Log("Calling Identity.GetUser()"); _identity.GetUser((GetUserResult result) => { Debug.Log($"Identity.GetUser() completed with result code {result.ResultCode} and response {result.Response}"); _getUserExampleUI.ResultCode = result.ResultCode; _getUserExampleUI.Response = result.Response; }); } private void CallForgotPassword() { ForgotPasswordRequest forgotPasswordRequest = new ForgotPasswordRequest { UserName = _forgotPasswordExampleUI.UserName }; Debug.Log($"Calling Identity.ForgotPassword() with {forgotPasswordRequest}"); _identity.ForgotPassword(forgotPasswordRequest, (uint resultCode) => { Debug.Log($"Identity.ForgotPassword() completed with result code {resultCode}"); _forgotPasswordExampleUI.ResultCode = resultCode; }); } private void CallConfirmForgotPassword() { ConfirmForgotPasswordRequest confirmForgotPasswordRequest = new ConfirmForgotPasswordRequest { UserName = _confirmForgotPasswordExampleUI.UserName, NewPassword = _confirmForgotPasswordExampleUI.NewPassword, ConfirmationCode = _confirmForgotPasswordExampleUI.ConfirmationCode }; Debug.Log($"Calling Identity.ConfirmForgotPassword() with {confirmForgotPasswordRequest}"); _identity.ConfirmForgotPassword(confirmForgotPasswordRequest, (uint resultCode) => { Debug.Log($"Identity.ConfirmForgotPassword() completed with result code {resultCode}"); _confirmForgotPasswordExampleUI.ResultCode = resultCode; }); } private void CallOpenFacebookLogin() { const string FAILED_LOGIN = "FAILED_LOGIN"; _openFacebookLoginExampleUI.Response.Clear(); Debug.Log("Calling Identity.GetFederatedLoginUrl() with FederatedIdentityProvider.FACEBOOK"); _openFacebookLoginExampleUI.Response["status"] = "POLLING FOR LOGIN COMPLETION ..."; Action<uint> completionCallback = (uint result) => { if (result != GameKitErrors.GAMEKIT_SUCCESS) { _openFacebookLoginExampleUI.Response["status"] = FAILED_LOGIN; _openFacebookLoginExampleUI.ResultCode = result; return; } _openFacebookLoginExampleUI.Response["status"] = "LOGIN COMPLETE"; // No username gets configured when logging in with facebook, put in a filler that will unlock rest of the API examples _userInfo.UserName = "facebook_user"; _identity.GetUser((GetUserResult result) => { Debug.Log($"Identity.GetUser() completed with result code {result.ResultCode} and response {result.Response}"); _userInfo.UserId = result.Response.UserId; }); }; _identity.FederatedLogin(FederatedIdentityProvider.FACEBOOK, (MultiKeyValueStringCallbackResult result) => { Debug.Log($"Identity.GetFederatedLoginUrl() completed with result code {result.ResultCode}"); _openFacebookLoginExampleUI.ResultCode = result.ResultCode; if (result.ResultCode == GameKitErrors.GAMEKIT_SUCCESS) { for (int i = 0; i < result.ResponseKeys.Length; i++) { _openFacebookLoginExampleUI.Response[result.ResponseKeys[i]] = result.ResponseValues[i]; } } else { _openFacebookLoginExampleUI.Response["status"] = FAILED_LOGIN; } }, completionCallback); } private void CallLogout() { Debug.Log("Calling Identity.Logout()"); _identity.Logout((uint resultCode) => { Debug.Log($"Identity.Logout() completed with result code {resultCode}"); _logoutExampleUI.ResultCode = resultCode; _userInfo.UserName = string.Empty; _userInfo.UserId = string.Empty; }); } #endregion } #region Example Classes [Serializable] public class RegisterExampleUI : GameKitExampleUI { public override string ApiName => "Register"; public string UserName; [NonSerialized] public string Password = string.Empty; // Since NonSerialized, must initialize to prevent from being null instead of empty public string Email; protected override void DrawInput() { PropertyField(nameof(UserName), "User Name"); PropertyField(nameof(Email), "Email"); Password = EditorGUILayoutElements.PasswordField("Password", Password, 0); } } [Serializable] public class ResendConfirmationExampleUI : GameKitExampleUI { public override string ApiName => "Resend Confirmation Code"; public string UserName; protected override void DrawInput() { PropertyField(nameof(UserName), "User Name"); } } [Serializable] public class ConfirmEmailExampleUI : GameKitExampleUI { public override string ApiName => "Confirm Email"; public string UserName; public string ConfirmationCode; protected override void DrawInput() { PropertyField(nameof(UserName), "User Name"); PropertyField(nameof(ConfirmationCode), "Confirmation Code"); } } [Serializable] public class LoginExampleUI : GameKitExampleUI { public override string ApiName => "Login"; public string UserName; [NonSerialized] public string Password = string.Empty; // Since NonSerialized, must initialize to prevent from being null instead of empty protected override void DrawInput() { PropertyField(nameof(UserName), "User Name"); Password = EditorGUILayoutElements.PasswordField("Password", Password, 0); } } [Serializable] public class GetUserExampleUI : GameKitExampleUI { public override string ApiName => "Get User"; protected override bool _shouldDisplayResponse => true; public GetUserResponse Response = new GetUserResponse { UserId = "", UserName = "", Email = "", CreatedAt = "", UpdatedAt = "", FacebookExternalId = "", FacebookRefId = "" }; protected override void DrawOutput() { EditorGUILayoutElements.TextField("User Name", Response.UserName, isEnabled: false); EditorGUILayoutElements.TextField("User Id", Response.UserId, isEnabled: false); EditorGUILayoutElements.TextField("Email", Response.Email, isEnabled: false); EditorGUILayoutElements.TextField("Created At", Response.CreatedAt, isEnabled: false); EditorGUILayoutElements.TextField("Updated At", Response.UpdatedAt, isEnabled: false); EditorGUILayoutElements.TextField("Facebook External Id", Response.FacebookExternalId, isEnabled: false); EditorGUILayoutElements.TextField("Facebook Ref Id", Response.FacebookRefId, isEnabled: false); } } [Serializable] public class OpenFacebookLoginExampleUI : GameKitExampleUI { public override string ApiName => "Open Facebook Login"; public readonly IDictionary<string, string> Response = new Dictionary<string, string>(); protected override bool _shouldDisplayResponse => true; protected override void DrawOutput() { foreach (KeyValuePair<string, string> entry in Response) { EditorGUILayoutElements.LabelField(entry.Key, entry.Value); } } } [Serializable] public class LogoutExampleUI : GameKitExampleUI { public override string ApiName => "Logout"; } [Serializable] public class ForgotPasswordExampleUI : GameKitExampleUI { public override string ApiName => "Forgot Password"; public string UserName; protected override void DrawInput() { PropertyField(nameof(UserName), "User Name"); } } [Serializable] public class ConfirmForgotPasswordExampleUI : GameKitExampleUI { public override string ApiName => "Confirm Forgot Password"; public string UserName; [NonSerialized] public string NewPassword = string.Empty; // Since NonSerialized, must initialize to prevent from being null instead of empty public string ConfirmationCode; protected override void DrawInput() { PropertyField(nameof(UserName), "User Name"); NewPassword = EditorGUILayoutElements.PasswordField("New Password", NewPassword, 0); PropertyField(nameof(ConfirmationCode), "Confirmation Code"); } } #endregion }
392
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; namespace AWS.GameKit.Editor.Windows.Settings.Pages.IdentityAndAuthentication { [Serializable] public class IdentityAndAuthenticationPage : FeaturePage { public override FeatureType FeatureType => FeatureType.Identity; [SerializeField] private IdentityAndAuthenticationSettingsTab _identitySettingsTab; [SerializeField] private IdentityAndAuthenticationExamplesTab _identityExamplesTab; public void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { _identitySettingsTab.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_identitySettingsTab))); _identityExamplesTab.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_identityExamplesTab))); base.Initialize(GetDefaultTabs(_identitySettingsTab, _identityExamplesTab), dependencies); } } }
32
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Models.FeatureSettings; namespace AWS.GameKit.Editor.Windows.Settings.Pages.IdentityAndAuthentication { [Serializable] public class IdentityAndAuthenticationSettingsTab : FeatureSettingsTab { private const string EMAIL_ENABLED_FEATURE_KEY = "is_email_enabled"; private const string FACEBOOK_ENABLED_FEATURE_KEY = "is_facebook_enabled"; private const string FACEBOOK_CLIENT_ID_FEATURE_KEY = "facebook_client_id"; private const string FACEBOOK_SECRET_FEATURE_KEY = "facebook_client_secret"; public override FeatureType FeatureType => FeatureType.Identity; protected override IEnumerable<IFeatureSetting> FeatureSpecificSettings => new List<IFeatureSetting>() { _isEnabledEmailAndPassword, _isEnabledFacebook, _facebookAppId }; protected override IEnumerable<SecretSetting> FeatureSecrets => new List<SecretSetting>() { _facebookAppSecret }; // Feature Settings [SerializeField] private FeatureSettingBool _isEnabledEmailAndPassword = new FeatureSettingBool(EMAIL_ENABLED_FEATURE_KEY, defaultValue: true); [SerializeField] private FeatureSettingBool _isEnabledFacebook = new FeatureSettingBool(FACEBOOK_ENABLED_FEATURE_KEY, defaultValue: false); [SerializeField] private FeatureSettingString _facebookAppId = new FeatureSettingString(FACEBOOK_CLIENT_ID_FEATURE_KEY, defaultValue: string.Empty); private SecretSetting _facebookAppSecret = new SecretSetting(FACEBOOK_SECRET_FEATURE_KEY, string.Empty, false); protected override void DrawSettings() { DrawLoginMechanisms(); EditorGUILayoutElements.SectionSpacer(); if (IsEnabledAnyIdentityProvider()) { DrawIdentityProviderCredentials(); } } private void DrawLoginMechanisms() { EditorGUILayoutElements.Description(L10n.Tr("Login mechanisms"), indentationLevel: 0); // Email & password is always enabled. It cannot be turned off. using (new EditorGUI.DisabledScope(true)) { EditorGUILayoutElements.ToggleField(L10n.Tr("Email / password"), _isEnabledEmailAndPassword.CurrentValue); } SerializedProperty isEnabledFacebookProperty = GetFeatureSettingProperty(nameof(_isEnabledFacebook)); isEnabledFacebookProperty.boolValue = EditorGUILayoutElements.ToggleField(L10n.Tr("Facebook"), isEnabledFacebookProperty.boolValue); } private bool IsEnabledAnyIdentityProvider() { return _isEnabledFacebook.CurrentValue; } private void DrawIdentityProviderCredentials() { EditorGUILayoutElements.Description(L10n.Tr("Identity provider credentials"), indentationLevel: 0); EditorGUILayoutElements.Description(L10n.Tr("To save credentials changes, deploy or update your Identity feature.")); if (_isEnabledFacebook.CurrentValue) { EditorGUILayoutElements.Description(L10n.Tr("Facebook"), indentationLevel: 1); SerializedProperty facebookAppIdProperty = GetFeatureSettingProperty(nameof(_facebookAppId)); facebookAppIdProperty.stringValue = EditorGUILayoutElements.TextField(L10n.Tr("App ID"), facebookAppIdProperty.stringValue, indentationLevel: 2); if (_facebookAppSecret.IsStoredInCloud) { _facebookAppSecret.SecretValue = EditorGUILayoutElements.PasswordField(L10n.Tr("App Secret"), _facebookAppSecret.SecretValue, indentationLevel: 2, L10n.Tr("Secured in AWS Secrets Manager")); } else { _facebookAppSecret.SecretValue = EditorGUILayoutElements.PasswordField(L10n.Tr("App Secret"), _facebookAppSecret.SecretValue, indentationLevel: 2); } } } } }
103
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Utils; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Windows.Settings.Pages.Log { [Serializable] public class LogPage : Page { private const string COUNT_OVERFLOW_TEXT = "999+"; private const uint COUNT_OVERFLOW_LIMIT = 1000; private const int MINIMUM_LOG_QUEUE_ENTRIES = 0; private const int MAXIMUM_LOG_QUEUE_ENTRIES = 10000; public override string DisplayName => L10n.Tr("Log"); private SerializedProperty _serializedProperty; [SerializeField] private Vector2 _scrollPositionMain; [SerializeField] private Vector2 _scrollPositionLogs; // Global log settings [SerializeField] private int _verbosityLevel = (int)(Logging.MinimumUnityLoggingLevel - 1); [SerializeField] private int _maximumLogEntries = Logging.MaxLogQueueSize; // Toggles for log display [SerializeField] private bool _isWordWrapEnabled = false; [SerializeField] private bool _shouldFilterInfoLogs = false; [SerializeField] private bool _shouldFilterWarnLogs = false; [SerializeField] private bool _shouldFilterErrorLogs = false; public void Initialize(SerializedProperty serializedProperty) { _serializedProperty = serializedProperty; } protected override void DrawContent() { using (EditorGUILayout.ScrollViewScope scrollView = new EditorGUILayout.ScrollViewScope(_scrollPositionMain)) { _scrollPositionMain = scrollView.scrollPosition; DrawGlobalSettings(); using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.LogPage.LogSection)) { bool shouldCopyToClipboard = DrawLogBoxOptions(); EditorGUILayoutElements.HorizontalDivider(); DrawLogBox(shouldCopyToClipboard); } } } private void DrawGlobalSettings() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.LogPage.GlobalSettingsSection)) { EditorGUILayoutElements.SectionHeader(L10n.Tr("Global log settings")); EditorGUILayout.Space(0); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel(L10n.Tr(L10n.Tr("Console logging level"))); string[] options = { L10n.Tr("Verbose"), L10n.Tr("Info"), L10n.Tr("Warning"), L10n.Tr("Error"), L10n.Tr("Exception") }; _verbosityLevel = GUILayout.SelectionGrid(_verbosityLevel, options, options.Length, SettingsGUIStyles.LogPage.LoggingLevel, GUILayout.ExpandWidth(false), GUILayout.MinWidth(0)); Logging.MinimumUnityLoggingLevel = (Logging.Level)_verbosityLevel + 1; GUILayout.FlexibleSpace(); } EditorGUILayoutElements.SectionSpacer(-17.5f); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel(L10n.Tr("Maximum log entries")); _maximumLogEntries = EditorGUILayoutElements.IntSlider(string.Empty, _maximumLogEntries, MINIMUM_LOG_QUEUE_ENTRIES, MAXIMUM_LOG_QUEUE_ENTRIES); Logging.MaxLogQueueSize = _maximumLogEntries; } } } private bool DrawLogBoxOptions() { using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button(L10n.Tr("Clear"), SettingsGUIStyles.LogPage.ButtonLeft)) { Logging.ClearLogQueue(); } bool shouldCopyToClipboard = GUILayout.Button(L10n.Tr("Copy"), SettingsGUIStyles.LogPage.ButtonLeft); _isWordWrapEnabled = EditorGUILayoutElements.ToggleLeft(L10n.Tr("Toggle word wrap"), _isWordWrapEnabled); GUILayout.FlexibleSpace(); _shouldFilterInfoLogs = GUILayout.Toggle(_shouldFilterInfoLogs, CreateLogFilterToggleContent(Logging.InfoLogCount, SettingsGUIStyles.Icons.InfoIcon), SettingsGUIStyles.LogPage.ButtonRight); _shouldFilterWarnLogs = GUILayout.Toggle(_shouldFilterWarnLogs, CreateLogFilterToggleContent(Logging.WarningLogCount, SettingsGUIStyles.Icons.WarnIcon), SettingsGUIStyles.LogPage.ButtonRight); _shouldFilterErrorLogs = GUILayout.Toggle(_shouldFilterErrorLogs, CreateLogFilterToggleContent(Logging.ErrorLogCount, SettingsGUIStyles.Icons.ErrorIcon), SettingsGUIStyles.LogPage.ButtonRight); return shouldCopyToClipboard; } } private void DrawLogBox(bool shouldCopyToClipboard) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.LogPage.LogBox)) { using (EditorGUILayout.ScrollViewScope scrollView = new EditorGUILayout.ScrollViewScope(_scrollPositionLogs)) { _scrollPositionLogs = scrollView.scrollPosition; string displayedLogs = string.Empty; Texture entryIcon; bool useDarkLine = true; foreach (string entry in Logging.LogQueue) { if (entry.Contains(Logging.Level.ERROR.ToString()) || entry.Contains(Logging.Level.EXCEPTION.ToString())) { if (_shouldFilterErrorLogs) { continue; } else { entryIcon = SettingsGUIStyles.Icons.ErrorIcon; } } else if (entry.Contains(Logging.Level.WARNING.ToString())) { if (_shouldFilterWarnLogs) { continue; } else { entryIcon = SettingsGUIStyles.Icons.WarnIcon; } } else { if (_shouldFilterInfoLogs) { continue; } else { entryIcon = SettingsGUIStyles.Icons.InfoIcon; } } GUIStyle style = new GUIStyle(SettingsGUIStyles.LogPage.LogEntry) { wordWrap = _isWordWrapEnabled, normal = new GUIStyleState() { textColor = SettingsGUIStyles.LogPage.LogInfoTextColor.Get(), background = useDarkLine ? SettingsGUIStyles.LogPage.DarkBackground : SettingsGUIStyles.LogPage.LightBackground, } }; useDarkLine = !useDarkLine; GUIContent content = new GUIContent(entry, entryIcon); Rect entrySize = GUILayoutUtility.GetRect(content, style); EditorGUI.LabelField(entrySize, new GUIContent(entry, entryIcon), style); displayedLogs += entry + "\n"; } if (shouldCopyToClipboard) { GUIUtility.systemCopyBuffer = displayedLogs; } } } } private GUIContent CreateLogFilterToggleContent(uint logCount, Texture icon) { if (logCount >= COUNT_OVERFLOW_LIMIT) { return new GUIContent(COUNT_OVERFLOW_TEXT, icon); } else { return new GUIContent(logCount.ToString(), icon); } } } }
209
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Linq; using AWS.GameKit.Editor.GUILayoutExtensions; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Features.GameKitUserGameplayData; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.Windows.Settings.Pages.UserGameplayData { [Serializable] public class UserGameplayDataExamplesTab : FeatureExamplesTab { private static readonly string RETRY_THREAD_OVERVIEW = L10n.Tr("In order to handle making offline calls, the retry thread must be started. Once the retry thread has been started, all calls made while the network state is unhealthy will be stored in a queue and retried based on the default client settings, " + "unless new settings have been set by the SetClientSettings() method. The retry thread should be stopped before persisting or loading any cached data to the queue."); private static readonly string NETWORK_STATUS_OVERVIEW = L10n.Tr("The Network status will be changed to unhealthy after a call has failed and been placed into the offline queue. Once a call has been made successfully or retried successfully the status will be set back to Healthy. " + "If the retry thread has not been started, the network status will always be treated as healthy and all calls will be attempted."); private static readonly string CACHE_PROCESSED_OVERVIEW = L10n.Tr("The Cache Processing Status will be set after a Cache file has been loaded into the queue and processed using the LoadFromCache() method."); private static readonly string SET_CLIENT_SETTINGS_OVERVIEW = L10n.Tr("Client settings can optionally be set before the retry thread is started. If SetClientSettings() is not called default values will be used. To learn more about the following fields, view their tool tips below. " + "The values of this slider are suggestions, however, the API will take any valid uint."); private static readonly string PERSIST_TO_CACHE_OVERVIEW = L10n.Tr("The Persist to Cache method should be used to save the current queue of API calls, that have not been successfully made, to disk when the player exits the program. " + "The optimal file extension for the cache file is '.dat' and should be saved within the 'Application.datapath' directory or any directory a player can access at runtime."); private static readonly string LOAD_FROM_CACHE_OVERVIEW = L10n.Tr("The Load from Cache method should be used to load any failed calls that a user may have had during their last session into the queue that will be retried with the retry thread."); private static readonly string DROP_CACHED_EVENTS_OVERVIEW = L10n.Tr("Dropping all Cached Events will clear the current queue of unmade calls that were loading into the queue using LoadFromCache(). " + "This will not effect any existing cache files that have been saved to disk with PersistToCache(), only calls that have already been loaded to the queue from a cache."); private static readonly IList<string> RETRY_STATEGY_OPTIONS = new List<string> { L10n.Tr("Exponential Backoff"), L10n.Tr("Constant Interval") }; public override FeatureType FeatureType => FeatureType.UserGameplayData; // Dependencies private IUserGameplayDataProvider _userGameplayData; // Delegates private delegate void _networkChangedDelegate(NetworkStatusChangeResults result); // User Gameplay Data Examples [SerializeField] private AddBundleExampleUI _addBundleExampleUI; [SerializeField] private ListUserGameplayDataBundlesExampleUI _listUserGameplayDataExampleUI; [SerializeField] private GetBundleExampleUI _getBundleExampleUI; [SerializeField] private GetBundleItemExampleUI _getBundleItemExampleUI; [SerializeField] private UpdateBundleItemExampleUI _updateBundleItemExampleUI; [SerializeField] private DeleteAllUserGameplayDataExampleUI _deleteAllUserGameplayDataExampleUI; [SerializeField] private DeleteBundleExampleUI _deleteBundleExampleUI; [SerializeField] private DeleteBundleItemsExampleUI _deleteBundleItemsExampleUI; // Offline Support Examples [SerializeField] private RetryThreadExampleUI _retryThreadExampleUI; [SerializeField] private NetworkStatusExampleUI _networkStatusExampleUI; [SerializeField] private CacheProcessedExampleUI _cacheProcessedExampleUI; [SerializeField] private PersistToCacheExampleUI _persistToCacheExampleUI; [SerializeField] private LoadFromCacheExampleUI _loadFromCacheExampleUI; [SerializeField] private DropAllCachedEventsExampleUI _dropAllCachedEventsExampleUI; // Set Client Settings Examples [SerializeField] private SetClientSettingsExampleUI _setClientSettingsExampleUI; public override void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { _userGameplayData = dependencies.UserGameplayData; // User Gameplay Data Examples _addBundleExampleUI.Initialize(CallAddBundle, serializedProperty.FindPropertyRelative(nameof(_addBundleExampleUI))); _listUserGameplayDataExampleUI.Initialize(CallListBundles, serializedProperty.FindPropertyRelative(nameof(_listUserGameplayDataExampleUI))); _getBundleExampleUI.Initialize(CallGetBundle, serializedProperty.FindPropertyRelative(nameof(_getBundleExampleUI))); _getBundleItemExampleUI.Initialize(CallGetBundleItem, serializedProperty.FindPropertyRelative(nameof(_getBundleItemExampleUI))); _updateBundleItemExampleUI.Initialize(CallUpdateBundleItem, serializedProperty.FindPropertyRelative(nameof(_updateBundleItemExampleUI))); _deleteAllUserGameplayDataExampleUI.Initialize(CallDeleteAllUserGameplayData, serializedProperty.FindPropertyRelative(nameof(_deleteAllUserGameplayDataExampleUI))); _deleteBundleExampleUI.Initialize(CallDeleteBundle, serializedProperty.FindPropertyRelative(nameof(_deleteBundleExampleUI))); _deleteBundleItemsExampleUI.Initialize(CallDeleteBundleItems, serializedProperty.FindPropertyRelative(nameof(_deleteBundleItemsExampleUI))); // Set Client Settings Example _setClientSettingsExampleUI.Initialize(CallSetClientSettings, serializedProperty.FindPropertyRelative(nameof(_setClientSettingsExampleUI))); // Offline Support Examples _retryThreadExampleUI.Initialize(CallStartRetryBackgroundThread, CallStopRetryBackgroundThread, serializedProperty.FindPropertyRelative(nameof(_retryThreadExampleUI))); CallSetNetworkChangeDelegate(); CallSetCacheProcessedDelegate(); _persistToCacheExampleUI.Initialize(CallPersistToCache, serializedProperty.FindPropertyRelative(nameof(_persistToCacheExampleUI))); _loadFromCacheExampleUI.Initialize(CallLoadFromCache, serializedProperty.FindPropertyRelative(nameof(_loadFromCacheExampleUI))); _dropAllCachedEventsExampleUI.Initialize(CallDropAllCachedEvents, serializedProperty.FindPropertyRelative(nameof(_dropAllCachedEventsExampleUI))); base.Initialize(dependencies, serializedProperty); } protected override void DrawExamples() { _addBundleExampleUI.OnGUI(); _listUserGameplayDataExampleUI.OnGUI(); _getBundleExampleUI.OnGUI(); _getBundleItemExampleUI.OnGUI(); _updateBundleItemExampleUI.OnGUI(); _deleteAllUserGameplayDataExampleUI.OnGUI(); _deleteBundleExampleUI.OnGUI(); _deleteBundleItemsExampleUI.OnGUI(); EditorGUILayoutElements.SectionDivider(); EditorGUILayout.LabelField("Offline Setup", SettingsGUIStyles.Page.Title); EditorGUILayout.Space(5); _retryThreadExampleUI.OnGUI(); _networkStatusExampleUI.OnGUI(); _cacheProcessedExampleUI.OnGUI(); _setClientSettingsExampleUI.OnGUI(); _persistToCacheExampleUI.OnGUI(); _loadFromCacheExampleUI.OnGUI(); _dropAllCachedEventsExampleUI.OnGUI(); } public override void OnLogout() { _retryThreadExampleUI.ForceStopRetryThread(); _networkStatusExampleUI.NetworkStatusChangeResult = null; // In NetworkStatusExampleUI, null is treated as a user just logged in _cacheProcessedExampleUI.CacheProcessedResult = null; // In CacheProcessedExampleUI, null is treated as a user just logged in } #region User Gameplay Data API Calls private void CallAddBundle() { if (_addBundleExampleUI.BundleKeys.Distinct().Count() != _addBundleExampleUI.BundleKeys.Count()) { _addBundleExampleUI.ResultCode = GameKitErrors.GAMEKIT_ERROR_GENERAL; Debug.LogError("All Bundle Key values in UserGameplayData.AddBundle() must be unique"); return; } // In the case where the list of keys and list of values do not need to be serialized and displayed on the screen it is recommended to skip this step and just use a Dictionary. Dictionary<string, string> bundleDictionary = Enumerable.Range(0, _addBundleExampleUI.BundleKeys.Count) .ToDictionary(i => _addBundleExampleUI.BundleKeys[i], i => _addBundleExampleUI.BundleValues[i]); AddUserGameplayDataDesc addUserGameplayData = new AddUserGameplayDataDesc { BundleName = _addBundleExampleUI.BundleName, BundleItems = bundleDictionary }; Debug.Log($"Calling UserGameplayData.AddBundle() for {_addBundleExampleUI.BundleName}"); _userGameplayData.AddBundle(addUserGameplayData, (AddUserGameplayDataResults result) => { Debug.Log($"UserGameplayData.AddBundle() completed with result code {result.ResultCode}"); _addBundleExampleUI.ResultCode = result.ResultCode; if (result.BundleItems.Count > 0) { foreach (KeyValuePair<string, string> bundleItem in result.BundleItems) { Debug.LogError($"Failed to process item - [{ bundleItem.Key}, { bundleItem.Value}]"); } } }); } private void CallListBundles() { Action listBundlesCall = () => { _userGameplayData.ListBundles((MultiStringCallbackResult result) => { Debug.Log($"UserGameplayData.ListBundles() completed with result code {result.ResultCode}"); _listUserGameplayDataExampleUI.ResultCode = result.ResultCode; _listUserGameplayDataExampleUI.BundleNames = result.ResponseValues.ToList(); }); }; if (_userGameplayData.IsBackgroundThreadRunning()) { // Only do this if the background thread is running as we might have data in the queue that should be synchronized before retrieving the bundles _userGameplayData.TryForceSynchronizeAndExecute(listBundlesCall, () => { Debug.Log("Could not synchronize data with the backend."); }); } else { listBundlesCall(); } } private void CallGetBundle() { Debug.Log($"Calling UserGameplayData.GetBundle() for {_getBundleExampleUI.BundleName}"); Action getBundleCall = () => { _userGameplayData.GetBundle(_getBundleExampleUI.BundleName, (GetUserGameplayDataBundleResults result) => { Debug.Log($"UserGameplayData.GetBundle() completed with result code {result.ResultCode}"); _getBundleExampleUI.ResultCode = result.ResultCode; _getBundleExampleUI.BundleKeys = result.Bundles.Keys.ToList(); _getBundleExampleUI.BundleValues = result.Bundles.Values.ToList(); }); }; if (_userGameplayData.IsBackgroundThreadRunning()) { // Only do this if the background thread is running as we might have data in the queue that should be synchronized before retrieving the bundle _userGameplayData.TryForceSynchronizeAndExecute(getBundleCall, () => { Debug.Log("Could not synchronize data with the backend."); }); } else { getBundleCall(); } } private void CallGetBundleItem() { Debug.Log($"Calling UserGameplayData.GetBundleItem() with {_getBundleItemExampleUI.BundleName}"); UserGameplayDataBundleItem userGameplayDayaBundleItem = new UserGameplayDataBundleItem { BundleName = _getBundleItemExampleUI.BundleName, BundleItemKey = _getBundleItemExampleUI.BundleItemKey }; Action getBundleCall = () => { _userGameplayData.GetBundleItem(userGameplayDayaBundleItem, (StringCallbackResult result) => { Debug.Log($"UserGameplayData.GetBundle() completed with result code {result.ResultCode}"); _getBundleItemExampleUI.ResultCode = result.ResultCode; _getBundleItemExampleUI.BundleItemValueResponse = result.ResponseValue; }); }; if (_userGameplayData.IsBackgroundThreadRunning()) { // Only do this if the background thread is running as we might have data in the queue that should be synchronized before retrieving the bundle item _userGameplayData.TryForceSynchronizeAndExecute(getBundleCall, () => { Debug.Log("Could not synchronize data with the backend."); }); } else { getBundleCall(); } } private void CallUpdateBundleItem() { Debug.Log($"Calling UserGameplayData.UpdateItem() with {_getBundleItemExampleUI.BundleName}"); UserGameplayDataBundleItemValue userGameplayDataBundleItemValue = new UserGameplayDataBundleItemValue { BundleName = _updateBundleItemExampleUI.BundleName, BundleItemKey = _updateBundleItemExampleUI.BundleItemKey, BundleItemValue = _updateBundleItemExampleUI.NewBundleItemValue }; _userGameplayData.UpdateItem(userGameplayDataBundleItemValue, (uint resultCode) => { Debug.Log($"UserGameplayData.UpdateItem() completed with result code {resultCode}"); _updateBundleItemExampleUI.ResultCode = resultCode; }); } private void CallDeleteAllUserGameplayData() { Debug.Log($"Calling UserGameplayData.DeleteAllData() to delete all User Gameplay data for the currently logged in user"); _userGameplayData.DeleteAllData((uint resultCode) => { Debug.Log($"UserGameplayData.DeleteAllData() completed with result code {resultCode}"); _deleteAllUserGameplayDataExampleUI.ResultCode = resultCode; }); } private void CallDeleteBundle() { Debug.Log($"Calling UserGameplayData.DeleteBundle() with {_deleteBundleExampleUI.BundleName}"); _userGameplayData.DeleteBundle(_deleteBundleExampleUI.BundleName, (uint resultCode) => { Debug.Log($"UserGameplayData.DeleteBundle() completed with result code {resultCode}"); _deleteBundleExampleUI.ResultCode = resultCode; }); } private void CallDeleteBundleItems() { DeleteUserGameplayDataBundleItemsDesc deleteUserGameplayDataBundleItemsDesc = new DeleteUserGameplayDataBundleItemsDesc { BundleName = _deleteBundleItemsExampleUI.BundleName, BundleItemKeys = _deleteBundleItemsExampleUI.BundleItemKeys.ToArray(), NumKeys = (ulong)_deleteBundleItemsExampleUI.BundleItemKeys.Count }; Debug.Log($"Calling UserGameplayData.DeleteBundleItems() with {deleteUserGameplayDataBundleItemsDesc}"); _userGameplayData.DeleteBundleItems(deleteUserGameplayDataBundleItemsDesc, (uint resultCode) => { Debug.Log($"UserGameplayData.DeleteBundleItems() completed with result code {resultCode}"); _deleteBundleItemsExampleUI.ResultCode = resultCode; }); } #endregion #region Example GUI Classes [Serializable] public class AddBundleExampleUI : GameKitExampleUI { public override string ApiName => "Add Bundle"; public string BundleName; /* * Note: A List of Keys and a List of values are used as a workaround to Dictionaries not being serializable in C#. * In the IUserGameplayDataProvider.AddBundle these lists will be formed into a dictionary before being passed in. * A dictionary type should be used here as long as the data does not need to be serialized or showed on screen. */ public List<string> BundleKeys = new List<string>(new string[1]); public List<string> BundleValues = new List<string>(new string[1]); protected override void DrawInput() { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel("Bundle Name"); using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleDictionaryInputAligned)) { PropertyField(nameof(BundleName)); GUILayout.Space(4); SerializedProperty serializedBundleKeys = _serializedProperty.FindPropertyRelative(nameof(BundleKeys)); SerializedProperty serializedBundleValues = _serializedProperty.FindPropertyRelative(nameof(BundleValues)); EditorGUILayoutElements.SerializableExamplesDictionary( serializedBundleKeys, serializedBundleValues, BundleKeys, BundleValues, "Item Keys", "Item Values"); } } } } [Serializable] public class ListUserGameplayDataBundlesExampleUI : GameKitExampleUI { public override string ApiName => "List User Gameplay Data Bundles"; protected override bool _shouldDisplayResponse => true; public List<string> BundleNames = new List<string>(); protected override void DrawOutput() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleResponseInputAligned)) { SerializedProperty serializedBundleKeys = _serializedProperty.FindPropertyRelative(nameof(BundleNames)); EditorGUILayoutElements.SerializableExamplesList( serializedBundleKeys, BundleNames, "Bundle Names", true); } } } [Serializable] public class GetBundleExampleUI : GameKitExampleUI { public override string ApiName => "Get Bundle"; protected override bool _shouldDisplayResponse => true; public string BundleName; /* * Note: A List of Keys and a List of values is used as a workaround to Dictionaries not being serializable in C#. * In the IUserGameplayDataProvider.GetBundle the response will contain a dictionary that is then broken up into two lists for the sake of this example. */ public List<string> BundleKeys = new List<string>(); public List<string> BundleValues = new List<string>(); protected override void DrawInput() { PropertyField(nameof(BundleName), "Bundle Name"); } protected override void DrawOutput() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleResponseInputAligned)) { SerializedProperty serializedBundleKeys = _serializedProperty.FindPropertyRelative(nameof(BundleKeys)); SerializedProperty serializedBundleValues = _serializedProperty.FindPropertyRelative(nameof(BundleValues)); EditorGUILayoutElements.SerializableExamplesDictionary( serializedBundleKeys, serializedBundleValues, BundleKeys, BundleValues, "Bundle Keys", "Bundle Values", isReadonly: true); } } } [Serializable] public class GetBundleItemExampleUI : GameKitExampleUI { public override string ApiName => "Get Bundle Item"; protected override bool _shouldDisplayResponse => true; public string BundleName; public string BundleItemKey; public string BundleItemValueResponse; protected override void DrawInput() { PropertyField(nameof(BundleName), "Bundle Name"); PropertyField(nameof(BundleItemKey), "Bundle Item Key"); } protected override void DrawOutput() { EditorGUILayoutElements.TextField("Bundle Item ", BundleItemValueResponse, isEnabled: false); } } [Serializable] public class UpdateBundleItemExampleUI : GameKitExampleUI { public override string ApiName => "Update Bundle Item"; public string BundleName; public string BundleItemKey; public string NewBundleItemValue; protected override void DrawInput() { PropertyField(nameof(BundleName), "Bundle Name"); PropertyField(nameof(BundleItemKey), "Bundle Item Key"); PropertyField(nameof(NewBundleItemValue), "New Bundle Item Value"); } } [Serializable] public class DeleteAllUserGameplayDataExampleUI : GameKitExampleUI { public override string ApiName => "Delete All User Gameplay Data"; } [Serializable] public class DeleteBundleExampleUI : GameKitExampleUI { public override string ApiName => "Delete Bundle"; public string BundleName; protected override void DrawInput() { PropertyField(nameof(BundleName), "Bundle Name"); } } [Serializable] public class DeleteBundleItemsExampleUI : GameKitExampleUI { public override string ApiName => "Delete Bundle Items"; public string BundleName; public List<string> BundleItemKeys = new List<string>(new string[1]); protected override void DrawInput() { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel("Bundle Name"); using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleDictionaryInputAligned)) { PropertyField(nameof(BundleName)); GUILayout.Space(4); SerializedProperty serializedBundleKeys = _serializedProperty.FindPropertyRelative(nameof(BundleItemKeys)); EditorGUILayoutElements.SerializableExamplesList( serializedBundleKeys, BundleItemKeys, "Bundle Item Keys"); } } } } #endregion #region Offline Support Examples API Calls private void CallStartRetryBackgroundThread() { Debug.Log("Calling UserGameplayData.StartRetryBackgroundThread()"); _userGameplayData.StartRetryBackgroundThread(); } private void CallStopRetryBackgroundThread() { Debug.Log("Calling UserGameplayData.StopRetryBackgroundThread()"); _userGameplayData.StopRetryBackgroundThread(); _cacheProcessedExampleUI.CacheProcessedResult = null; // After the user stops the retry thread they can retry another cache file } private void CallSetNetworkChangeDelegate() { Debug.Log("Calling UserGameplayData.SetNetworkChangeDelegate()"); _userGameplayData.SetNetworkChangeDelegate((NetworkStatusChangeResults result) => { Debug.Log($"UserGameplayData Network Change detected. IsConnectionOk: {result.IsConnectionOk}"); _networkStatusExampleUI.NetworkStatusChangeResult = result; }); } private void CallSetCacheProcessedDelegate() { Debug.Log("Calling UserGameplayData.SetCacheProcessedDelegate()"); _userGameplayData.SetCacheProcessedDelegate((CacheProcessedResults result) => { Debug.Log($"UserGameplayData Cache processing completed with result code {result.ResultCode}"); _cacheProcessedExampleUI.CacheProcessedResult = result; }); } private void CallSetClientSettings() { UserGameplayDataClientSettings clientSettings = new UserGameplayDataClientSettings { ClientTimeoutSeconds = _setClientSettingsExampleUI.ClientTimeoutInSeconds, RetryIntervalSeconds = _setClientSettingsExampleUI.RetryIntervalSeconds, MaxRetryQueueSize = _setClientSettingsExampleUI.MaxRetryQueueSize, MaxRetries = _setClientSettingsExampleUI.MaxRetries, RetryStrategy = _setClientSettingsExampleUI.RetryStrategy, MaxExponentialRetryThreshold = _setClientSettingsExampleUI.MaxExponentialRetryThreshold, PaginationSize = _setClientSettingsExampleUI.PaginationSize }; Debug.Log("Calling UserGameplayData.SetClientSettings()"); _userGameplayData.SetClientSettings(clientSettings, () => { // The result code below is not displayed in the examples UI but setting the result code marks the call as completed _setClientSettingsExampleUI.ResultCode = GameKitErrors.GAMEKIT_SUCCESS; Debug.Log($"UserGameplayData client settings set successfully."); }); } private void CallPersistToCache() { Debug.Log("Calling UserGameplayData.PersistToCache()"); // If you need the PersistToCache call to be blocking, which is recommended when saving OnApplicationExit, use ImmediatePersistToCache instead _userGameplayData.PersistToCache(_persistToCacheExampleUI.FilePath, (uint result) => { Debug.Log($"UserGameplayData.PersistToCache() completed with result code {result}"); _persistToCacheExampleUI.ResultCode = result; }); } private void CallLoadFromCache() { Debug.Log("Calling UserGameplayData.LoadFromCache()"); _userGameplayData.LoadFromCache(_loadFromCacheExampleUI.FilePath, (uint result) => { Debug.Log($"UserGameplayData.LoadFromCache() completed with result code {result}"); _loadFromCacheExampleUI.ResultCode = result; }); } private void CallDropAllCachedEvents() { Debug.Log("Calling UserGameplayData.DropAllCachedEvents()"); _userGameplayData.DropAllCachedEvents(() => { // The result code below is not displayed in the examples UI but setting the result code marks the call as completed _dropAllCachedEventsExampleUI.ResultCode = GameKitErrors.GAMEKIT_SUCCESS; Debug.Log($"All operations that were loading from cache dropped successfully from the retry thread."); }); } #endregion #region Offline Support Examples GUI Classes [Serializable] public class RetryThreadExampleUI : IDrawable { private bool _isRetryThreadStarted; private bool _isExampleDisplayed = true; private Action _startRetryThreadAction; private Action _stopRetryThreadAction; protected SerializedProperty _serializedProperty; public void Initialize(Action startRetryThreadAction, Action stopRetryThreadAction, SerializedProperty serializedProperty) { _startRetryThreadAction = startRetryThreadAction; _stopRetryThreadAction = stopRetryThreadAction; _serializedProperty = serializedProperty; } public void ForceStopRetryThread() { // Should be called when the user logs out to ensure the retry thread can be started again by a new user if (_isRetryThreadStarted) { _isRetryThreadStarted = false; _stopRetryThreadAction(); } } public void OnGUI() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleContainer)) { _isExampleDisplayed = EditorGUILayout.Foldout(_isExampleDisplayed, "Retry Thread", SettingsGUIStyles.Page.FoldoutTitle); if (_isExampleDisplayed) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleFoldoutContainer)) { EditorGUILayout.LabelField(RETRY_THREAD_OVERVIEW, SettingsGUIStyles.Page.TextAreaSubtext); EditorGUILayout.Space(5); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayoutElements.PrefixLabel("Action", 0); if (_isRetryThreadStarted) { if (GUILayout.Button(L10n.Tr("Stop Retry Thread"), SettingsGUIStyles.Buttons.GreyButtonNormal)) { _isRetryThreadStarted = false; _stopRetryThreadAction(); } } else { if (GUILayout.Button(L10n.Tr("Start Retry Thread"), SettingsGUIStyles.Buttons.GreyButtonNormal)) { _isRetryThreadStarted = true; _startRetryThreadAction(); } } } } } } } } [Serializable] public class NetworkStatusExampleUI : IDrawable { public NetworkStatusChangeResults NetworkStatusChangeResult; private bool _isExampleDisplayed = true; public void OnGUI() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleContainer)) { _isExampleDisplayed = EditorGUILayout.Foldout(_isExampleDisplayed, "Last Known Network Status", SettingsGUIStyles.Page.FoldoutTitle); if (_isExampleDisplayed) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleFoldoutContainer)) { EditorGUILayout.LabelField(NETWORK_STATUS_OVERVIEW, SettingsGUIStyles.Page.TextAreaSubtext); EditorGUILayoutElements.CustomField(L10n.Tr("Network status"), () => { // GameKit will treat the first call as if we are online, status will change based on the result of the first call if the retry thread has been started if (NetworkStatusChangeResult == null || NetworkStatusChangeResult.IsConnectionOk) { EditorGUILayoutElements.DeploymentStatusIcon(FeatureStatus.Deployed); EditorGUILayout.LabelField("Online"); } else { EditorGUILayoutElements.DeploymentStatusIcon(FeatureStatus.Error); EditorGUILayout.LabelField("Offline"); } }, indentationLevel: 0); } } } } } [Serializable] public class CacheProcessedExampleUI : IDrawable { public CacheProcessedResults CacheProcessedResult; private bool _isExampleDisplayed = true; public void OnGUI() { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleContainer)) { _isExampleDisplayed = EditorGUILayout.Foldout(_isExampleDisplayed, "Cache Status", SettingsGUIStyles.Page.FoldoutTitle); if (_isExampleDisplayed) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.FeatureExamplesTab.ExampleFoldoutContainer)) { EditorGUILayout.LabelField(CACHE_PROCESSED_OVERVIEW, SettingsGUIStyles.Page.TextAreaSubtext); EditorGUILayoutElements.CustomField(L10n.Tr("Cache Processing Status"), () => { // GameKit will treat the first call as if we are online, status will change based on the result of the first call if (CacheProcessedResult == null) { EditorGUILayout.LabelField("No Cache Processed"); } else if (CacheProcessedResult.IsCacheProcessed) { EditorGUILayoutElements.DeploymentStatusIcon(FeatureStatus.Deployed); EditorGUILayout.LabelField("Cache Processed Successfully"); } else { EditorGUILayoutElements.DeploymentStatusIcon(FeatureStatus.Error); EditorGUILayout.LabelField("Cache Processing Failed"); } }, indentationLevel: 0); } } } } } [Serializable] public class SetClientSettingsExampleUI : GameKitExampleUI { public override string ApiName => "Set Client Settings"; protected override bool _shouldDisplayDescription => true; protected override bool _shouldDisplayResult => false; public uint ClientTimeoutInSeconds = 3; public uint RetryIntervalSeconds = 5; public uint MaxRetryQueueSize = 256; public uint MaxRetries = 32; public uint RetryStrategy = 0; public uint MaxExponentialRetryThreshold = 32; public uint PaginationSize = 100; protected override void DrawDescription() { EditorGUILayout.LabelField(SET_CLIENT_SETTINGS_OVERVIEW, SettingsGUIStyles.Page.TextAreaSubtext); } protected override void DrawInput() { SerializedProperty clientTimeoutInSecondsProperty =_serializedProperty.FindPropertyRelative(nameof(ClientTimeoutInSeconds)); ClientTimeoutInSeconds = (uint)EditorGUILayoutElements.IntSlider(L10n.Tr("Client Timeout"), clientTimeoutInSecondsProperty.intValue, 1, 100, indentationLevel: 0); EditorGUI.LabelField(GUILayoutUtility.GetLastRect(), new GUIContent(string.Empty, "Connection timeout in seconds for the internal HTTP client. Default is 3. Uses default if set to 0.")); SerializedProperty retryIntervalInSecondsProperty = _serializedProperty.FindPropertyRelative(nameof(RetryIntervalSeconds)); RetryIntervalSeconds = (uint)EditorGUILayoutElements.IntSlider(L10n.Tr("Retry Interval"), retryIntervalInSecondsProperty.intValue, 1, 100, indentationLevel: 0); EditorGUI.LabelField(GUILayoutUtility.GetLastRect(), new GUIContent(string.Empty, "Seconds to wait between retries. Default is 5. Uses default value if set to 0.")); SerializedProperty maxRetryQueueSizeProperty = _serializedProperty.FindPropertyRelative(nameof(MaxRetryQueueSize)); MaxRetryQueueSize = (uint)EditorGUILayoutElements.IntSlider(L10n.Tr("Max Retry Queue Size"), maxRetryQueueSizeProperty.intValue, 1, 1000, indentationLevel: 0); EditorGUI.LabelField(GUILayoutUtility.GetLastRect(), new GUIContent(string.Empty, "Maximum length of custom http client request queue size. Once the queue is full, new requests will be dropped. Default is 256. Uses default if set to 0.")); SerializedProperty maxRetriesProperty = _serializedProperty.FindPropertyRelative(nameof(MaxRetries)); MaxRetries = (uint)EditorGUILayoutElements.IntSlider(L10n.Tr("Max Retries"), maxRetriesProperty.intValue, 1, 100, indentationLevel: 0); EditorGUI.LabelField(GUILayoutUtility.GetLastRect(), new GUIContent(string.Empty, "Maximum number of times to retry a request before dropping it. Default is 32. Uses default if set to 0.")); SerializedProperty retryStrategyProperty = _serializedProperty.FindPropertyRelative(nameof(RetryStrategy)); RetryStrategy = (uint)EditorGUILayout.Popup("Retry Strategy", retryStrategyProperty.intValue, RETRY_STATEGY_OPTIONS.ToArray()); SerializedProperty maxExponentialRetriesThresholdProperty = _serializedProperty.FindPropertyRelative(nameof(MaxExponentialRetryThreshold)); MaxExponentialRetryThreshold = (uint)EditorGUILayoutElements.IntSlider(L10n.Tr("Max Exponential Retries"), maxExponentialRetriesThresholdProperty.intValue, 1, 100, indentationLevel: 0); EditorGUI.LabelField(GUILayoutUtility.GetLastRect(), new GUIContent(string.Empty, "Maximum retry threshold for Exponential Backoff. Forces a retry even if exponential backoff is set to a greater value. Default is 32. Uses default if set to 0.")); SerializedProperty paginationSizeProperty = _serializedProperty.FindPropertyRelative(nameof(PaginationSize)); PaginationSize = (uint)EditorGUILayoutElements.IntSlider(L10n.Tr("Pagination Size"), paginationSizeProperty.intValue, 1, 100, indentationLevel: 0); EditorGUI.LabelField(GUILayoutUtility.GetLastRect(), new GUIContent(string.Empty, "Number of items to retrieve when executing paginated calls such as Get All Data. Default is 100. Uses default if set to 0.")); } } [Serializable] public class PersistToCacheExampleUI : GameKitExampleUI { public override string ApiName => "Persist to Cache"; protected override bool _shouldDisplayDescription => true; public string FilePath; protected override void DrawDescription() { EditorGUILayout.LabelField(PERSIST_TO_CACHE_OVERVIEW, SettingsGUIStyles.Page.TextAreaSubtext); } protected override void DrawInput() { SerializedProperty filePath = _serializedProperty.FindPropertyRelative(nameof(FilePath)); filePath.stringValue = EditorGUILayoutElements.FileSelection("File Path", filePath.stringValue, "Select a file", "", 0); } } [Serializable] public class LoadFromCacheExampleUI : GameKitExampleUI { public override string ApiName => "Load from Cache"; protected override bool _shouldDisplayDescription => true; public string FilePath; protected override void DrawDescription() { EditorGUILayout.LabelField(LOAD_FROM_CACHE_OVERVIEW, SettingsGUIStyles.Page.TextAreaSubtext); } protected override void DrawInput() { SerializedProperty filePath = _serializedProperty.FindPropertyRelative(nameof(FilePath)); filePath.stringValue = EditorGUILayoutElements.FileSelection("File Path", filePath.stringValue, "Select a file", "", 0); } } [Serializable] public class DropAllCachedEventsExampleUI : GameKitExampleUI { public override string ApiName => "Drop all Cached Events"; protected override bool _shouldDisplayDescription => true; protected override bool _shouldDisplayResult => false; protected override void DrawDescription() { EditorGUILayout.LabelField(DROP_CACHED_EVENTS_OVERVIEW, SettingsGUIStyles.Page.TextAreaSubtext); } } #endregion } }
870
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; namespace AWS.GameKit.Editor.Windows.Settings.Pages.UserGameplayData { [Serializable] public class UserGameplayDataPage : FeaturePage { public override FeatureType FeatureType => FeatureType.UserGameplayData; [SerializeField] private UserGameplayDataSettingsTab _userGameplayDataSettingsTab; [SerializeField] private UserGameplayDataExamplesTab _userGameplayDataExamplesTab; public void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { _userGameplayDataSettingsTab.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_userGameplayDataSettingsTab))); _userGameplayDataExamplesTab.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_userGameplayDataExamplesTab))); base.Initialize(GetDefaultTabs(_userGameplayDataSettingsTab, _userGameplayDataExamplesTab), dependencies); } } }
32
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Models; namespace AWS.GameKit.Editor.Windows.Settings.Pages.UserGameplayData { [Serializable] public class UserGameplayDataSettingsTab : FeatureSettingsTab { public override FeatureType FeatureType => FeatureType.UserGameplayData; protected override IEnumerable<IFeatureSetting> FeatureSpecificSettings => new List<IFeatureSetting>() { // No feature specific settings. }; protected override IEnumerable<SecretSetting> FeatureSecrets => new List<SecretSetting>() { // No feature secrets. }; protected override bool ShouldReloadFeatureSettings() => false; protected override bool ShouldDrawSettingsSection() => false; protected override void DrawSettings() { // No settings. } } }
40
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEngine; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime { /// <summary> /// This script must always be attached to an active object in the current scene, otherwise the AWS GameKit APIs will not work. /// This script automatically creates and attaches itself to a GameObject named "GameKit" if this script isn't present in the scene. /// This happens by calling CreateGameKitRuntimeManagerIfNotValid() below during the normal editor window update state. /// </summary> [ExecuteAlways, DisallowMultipleComponent] public class GameKitRuntimeManager : MonoBehaviour { private const string GAME_KIT_OBJECT_NAME = "GameKitManager"; private static GameKitRuntimeManager _instance; private static GameObject _objectInstance; private static bool _isActive = false; #region Editor Code /// <summary> /// This method will check for and add (if missing) a GameKit game object with this script attached. /// </summary> /// <param name="objectInstance">A handle for the GameKit object that this method creates.</param> public static void KeepGameKitObjectAlive() { // if the script is already active then there is nothing to do if (!_isActive) { // attempt to get an instance of the object or create a new one GameObject instance = GetGameObjectInstance(); // try to get an instance of this script from the object GameKitRuntimeManager scriptInstance = instance.GetComponent<GameKitRuntimeManager>(); // if the script was not attached, then attach it if (scriptInstance == null) { scriptInstance = instance.AddComponent<GameKitRuntimeManager>(); } // enable the script scriptInstance.enabled = true; // the object should not move and always be set to static instance.isStatic = true; // activate the object instance.SetActive(true); } } private static GameObject GetGameObjectInstance() { // if there is not already an instance of the object then create it if (_objectInstance == null) { _objectInstance = new GameObject(GAME_KIT_OBJECT_NAME); } return _objectInstance; } #endregion #region Runtime Code private void Awake() { if (Application.isPlaying) { if (_instance == null) { _instance = GetComponent<GameKitRuntimeManager>(); // prevent the parent of this object from being destroyed during scene changes DontDestroyOnLoad(gameObject); } } } private void OnEnable() { Logging.LogInfo("GameKitRuntimeManager is now running."); _isActive = true; } private void Update() { GameKitManager gameKitManager = Singleton<GameKitManager>.Get(); gameKitManager.EnsureFeaturesAreInitialized(); gameKitManager.Update(); } private void OnDisable() { _isActive = false; Logging.LogInfo("GameKitRuntimeManager is no longer running."); } private void OnApplicationQuit() { Singleton<GameKitManager>.Get().OnApplicationQuit(); #if !UNITY_EDITOR // In editor mode don't dispose GameKit manager. // In non-editor execution environments and while we are still on the main thread, // clean up the GameKitManager and related features Singleton<GameKitManager>.Get().Dispose(); #endif // cleanup the instance _instance = null; } private void OnApplicationPause(bool isPaused) { Singleton<GameKitManager>.Get().OnApplicationPause(isPaused); } #endregion } }
131
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Exceptions; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.Core { /// <summary> /// Implements ICoreWrapper and ICoreWrapperProvider /// </summary> public class CoreWrapper : Singleton<CoreWrapper>, ICoreWrapperProvider { #if UNITY_EDITOR // Select the correct source path based on the platform private const string IMPORT = "aws-gamekit-core"; // Saved session manager instance private IntPtr _accountInstance = IntPtr.Zero; private IntPtr _featureResourcesInstance = IntPtr.Zero; private IntPtr _settingsInstance = IntPtr.Zero; private IntPtr _featureStatusInstance = IntPtr.Zero; private IntPtr _deploymentOrchestrator = IntPtr.Zero; [DllImport(IMPORT)] private static extern uint GameKitGetAwsAccountId(IntPtr dispatchReceiver, FuncStringCallback responseCb, string accessKey, string secretKey, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern IntPtr GameKitAccountInstanceCreate(AccountInfo accountInfo, AccountCredentials credentials, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern IntPtr GameKitAccountInstanceCreateWithRootPaths(AccountInfo accountInfo, AccountCredentials credentials, string rootPath, string pluginRootPath, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern void GameKitAccountInstanceRelease(IntPtr accountInstance); [DllImport(IMPORT)] private static extern bool GameKitAccountHasValidCredentials(IntPtr accountInstance); [DllImport(IMPORT)] private static extern uint GameKitAccountInstanceBootstrap(IntPtr accountInstance); [DllImport(IMPORT)] private static extern uint GameKitAccountSaveSecret(IntPtr accountInstance, string secretName, string secretValue); [DllImport(IMPORT)] private static extern uint GameKitAccountCheckSecretExists(IntPtr accountInstance, string secretName); [DllImport(IMPORT)] private static extern uint GameKitAccountUploadAllDashboards(IntPtr accountInstance); [DllImport(IMPORT)] private static extern IntPtr GameKitResourcesInstanceCreate(AccountInfo accountInfo, AccountCredentials credentials, FeatureType featureType, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern IntPtr GameKitResourcesInstanceCreateWithRootPaths(AccountInfo accountInfo, AccountCredentials credentials, FeatureType featureType, string rootPath, string pluginRootPath, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern void GameKitResourcesInstanceRelease(IntPtr resourcesInstance); [DllImport(IMPORT)] private static extern uint GameKitResourcesCreateEmptyConfigFile(IntPtr resourcesInstance); [DllImport(IMPORT)] private static extern IntPtr GameKitSettingsInstanceCreate(string rootPath, string pluginVersion, string shortGameName, string currentEnvironment, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern void GameKitSettingsInstanceRelease(IntPtr settingsInstance); [DllImport(IMPORT)] private static extern void GameKitSettingsSetGameName(IntPtr settingsInstance, string gameName); [DllImport(IMPORT)] private static extern void GameKitSettingsSetLastUsedRegion(IntPtr settingsInstance, string region); [DllImport(IMPORT)] private static extern void GameKitSettingsSetLastUsedEnvironment(IntPtr settingsInstance, string envCode); [DllImport(IMPORT)] private static extern void GameKitSettingsAddCustomEnvironment(IntPtr settingsInstance, string envCode, string envDescription); [DllImport(IMPORT)] private static extern void GameKitSettingsSetFeatureVariables(IntPtr settingsInstance, FeatureType featureType, string[] varKeys, string[] varValues, ulong numKeys); [DllImport(IMPORT)] private static extern uint GameKitSettingsSave(IntPtr settingsInstance); [DllImport(IMPORT)] private static extern uint GameKitSettingsPopulateAndSave(IntPtr settingsInstance, string gameName, string envCode, string region); [DllImport(IMPORT)] private static extern void GameKitSettingsGetGameName(IntPtr settingsInstance, IntPtr dispatchReceiver, FuncStringCallback responseCb); [DllImport(IMPORT)] private static extern void GameKitSettingsGetLastUsedRegion(IntPtr settingsInstance, IntPtr dispatchReceiver, FuncStringCallback responseCb); [DllImport(IMPORT)] private static extern void GameKitSettingsGetLastUsedEnvironment(IntPtr settingsInstance, IntPtr dispatchReceiver, FuncStringCallback responseCb); [DllImport(IMPORT)] private static extern void GameKitSettingsGetCustomEnvironments(IntPtr settingsInstance, IntPtr dispatchReceiver, FuncKeyValueStringCallback responseCb); [DllImport(IMPORT)] private static extern void GameKitSettingsGetFeatureVariables(IntPtr settingsInstance, IntPtr dispatchReceiver, FeatureType featureType, FuncKeyValueStringCallback responseCb); [DllImport(IMPORT)] private static extern void GameKitSettingsGetSettingsFilePath(IntPtr settingsInstance, IntPtr dispatchReceiver, FuncStringCallback responseCb); [DllImport(IMPORT)] private static extern uint GameKitSaveAwsCredentials(string profileName, string accessKey, string secretKey, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern bool GameKitAwsProfileExists(string profileName); [DllImport(IMPORT)] private static extern uint GameKitSetAwsAccessKey(string profileName, string newAccessKey, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern uint GameKitSetAwsSecretKey(string profileName, string newSecretKey, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern uint GameKitGetAwsProfile(string profileName, IntPtr dispatchReceiver, FuncKeyValueStringCallback responseCb, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern IntPtr GameKitDeploymentOrchestratorCreate(string baseTemplatesFolder, string instanceFilesFolder, string sourceEngine, string pluginVersion, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern void GameKitDeploymentOrchestratorInstanceRelease(IntPtr deploymentOrchestratorInstance); [DllImport(IMPORT)] private static extern uint GameKitDeploymentOrchestratorSetCredentials(IntPtr deploymentOrchestratorInstance, AccountInfo accountInfo, AccountCredentials accountCredentials); [DllImport(IMPORT)] private static extern FeatureStatus GameKitDeploymentOrchestratorGetFeatureStatus(IntPtr deploymentOrchestratorInstance, FeatureType feature); [DllImport(IMPORT)] private static extern FeatureStatusSummary GameKitDeploymentOrchestratorGetFeatureStatusSummary(IntPtr deploymentOrchestratorInstance, FeatureType feature); [DllImport(IMPORT)] private static extern bool GameKitDeploymentOrchestratorIsFeatureDeploymentInProgress(IntPtr deploymentOrchestratorInstance, FeatureType feature); [DllImport(IMPORT)] private static extern bool GameKitDeploymentOrchestratorIsFeatureUpdating(IntPtr deploymentOrchestratorInstance, FeatureType feature); [DllImport(IMPORT)] private static extern bool GameKitDeploymentOrchestratorIsAnyFeatureUpdating(IntPtr deploymentOrchestratorInstance); [DllImport(IMPORT)] private static extern uint GameKitDeploymentOrchestratorRefreshFeatureStatus(IntPtr deploymentOrchestratorInstance, FeatureType feature, IntPtr receiver, FuncDeploymentResponseCallback resultCb); [DllImport(IMPORT)] private static extern uint GameKitDeploymentOrchestratorRefreshFeatureStatuses(IntPtr deploymentOrchestratorInstance, IntPtr receiver, FuncDeploymentResponseCallback resultCb); [DllImport(IMPORT)] private static extern bool GameKitDeploymentOrchestratorCanCreateFeature(IntPtr deploymentOrchestratorInstance, FeatureType feature, IntPtr receiver, FuncCanExecuteDeploymentActionCallback resultCb); [DllImport(IMPORT)] private static extern bool GameKitDeploymentOrchestratorCanRedeployFeature(IntPtr deploymentOrchestratorInstance, FeatureType feature, IntPtr receiver, FuncCanExecuteDeploymentActionCallback resultCb); [DllImport(IMPORT)] private static extern bool GameKitDeploymentOrchestratorCanDeleteFeature(IntPtr deploymentOrchestratorInstance, FeatureType feature, IntPtr receiver, FuncCanExecuteDeploymentActionCallback resultCb); [DllImport(IMPORT)] private static extern uint GameKitDeploymentOrchestratorCreateFeature(IntPtr deploymentOrchestratorInstance, FeatureType feature, IntPtr receiver, FuncDeploymentResponseCallback resultCb); [DllImport(IMPORT)] private static extern uint GameKitDeploymentOrchestratorRedeployFeature(IntPtr deploymentOrchestratorInstance, FeatureType feature, IntPtr receiver, FuncDeploymentResponseCallback resultCb); [DllImport(IMPORT)] private static extern uint GameKitDeploymentOrchestratorDeleteFeature(IntPtr deploymentOrchestratorInstance, FeatureType feature, IntPtr receiver, FuncDeploymentResponseCallback resultCb); [DllImport(IMPORT)] private static extern uint GameKitDeploymentOrchestratorDescribeFeatureResources(IntPtr deploymentOrchestratorInstance, FeatureType feature, IntPtr receiver, FuncResourceInfoCallback resultCb); #region GameKitAccount public StringCallbackResult GetAWSAccountId(GetAWSAccountIdDescription iamAccountCredentials) { StringCallbackResult results = new StringCallbackResult(); uint status = DllLoader.TryDll(results, (IntPtr dispatchReceiver) => GameKitGetAwsAccountId(dispatchReceiver, GameKitCallbacks.StringCallback, iamAccountCredentials.AccessKey, iamAccountCredentials.AccessSecret, Logging.LogCb), nameof(GameKitGetAwsAccountId), GameKitErrors.GAMEKIT_ERROR_GENERAL); results.ResultCode = status; return results; } public IntPtr GetAccountInstance() { if (_accountInstance == IntPtr.Zero) { throw new GameKitInstanceNotFound("CoreWrapper::AccountInstanceCreate() must be called with proper account and credential details before any account methods can be used"); } return _accountInstance; } public IntPtr AccountInstanceCreate(AccountInfo accountInfo, AccountCredentials credentials, FuncLoggingCallback logCb) { _accountInstance = DllLoader.TryDll(() => GameKitAccountInstanceCreate(accountInfo, credentials, logCb), nameof(GameKitAccountInstanceCreate), IntPtr.Zero); return _accountInstance; } public IntPtr AccountInstanceCreateWithRootPaths(AccountInfo accountInfo, AccountCredentials credentials, string rootPath, string pluginRootPath, FuncLoggingCallback logCb) { _accountInstance = DllLoader.TryDll(() => GameKitAccountInstanceCreateWithRootPaths(accountInfo, credentials, rootPath, pluginRootPath, logCb), nameof(GameKitAccountInstanceCreateWithRootPaths), IntPtr.Zero); return _accountInstance; } public void AccountInstanceRelease() { if (_accountInstance != IntPtr.Zero) { DllLoader.TryDll(() => GameKitAccountInstanceRelease(GetAccountInstance()), nameof(GameKitAccountInstanceRelease)); _accountInstance = IntPtr.Zero; } } public bool AccountHasValidCredentials() { return DllLoader.TryDll(() => GameKitAccountHasValidCredentials(GetAccountInstance()), nameof(GameKitAccountHasValidCredentials), false); } public uint AccountInstanceBootstrap() { return DllLoader.TryDll(() => GameKitAccountInstanceBootstrap(GetAccountInstance()), nameof(GameKitAccountInstanceBootstrap), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint GameKitAccountSaveSecret(string secretName, string secretValue) { return DllLoader.TryDll(() => GameKitAccountSaveSecret(GetAccountInstance(), secretName, secretValue), nameof(GameKitAccountSaveSecret), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint GameKitAccountCheckSecretExists(string secretName) { if (_accountInstance != IntPtr.Zero) { return DllLoader.TryDll(() => GameKitAccountCheckSecretExists(GetAccountInstance(), secretName), nameof(GameKitAccountCheckSecretExists), GameKitErrors.GAMEKIT_ERROR_GENERAL); } return GameKitErrors.GAMEKIT_WARNING_SECRETSMANAGER_SECRET_NOT_FOUND; } public uint GameKitAccountUploadAllDashboards() { return DllLoader.TryDll(() => GameKitAccountUploadAllDashboards(GetAccountInstance()), nameof(GameKitAccountUploadAllDashboards), GameKitErrors.GAMEKIT_ERROR_GENERAL); } #endregion #region GameKitResources public IntPtr GetResourcesInstance() { if ((_featureResourcesInstance) == IntPtr.Zero) { throw new GameKitInstanceNotFound("CoreWrapper::ResourcesInstanceCreate() must be called with account and credentials information before any account methods can be used"); } return _featureResourcesInstance; } public IntPtr ResourcesInstanceCreate(AccountInfo accountInfo, AccountCredentials credentials, FeatureType featureType, FuncLoggingCallback logCb) { _featureResourcesInstance = DllLoader.TryDll(() => GameKitResourcesInstanceCreate(accountInfo, credentials, featureType, logCb), nameof(GameKitResourcesInstanceCreate), IntPtr.Zero); return _featureResourcesInstance; } public IntPtr ResourcesInstanceCreateWithRootPaths(AccountInfo accountInfo, AccountCredentials credentials, FeatureType featureType, string rootPath, string pluginRootPath, FuncLoggingCallback logCb) { _featureResourcesInstance = DllLoader.TryDll(() => GameKitResourcesInstanceCreateWithRootPaths(accountInfo, credentials, featureType, rootPath, pluginRootPath, logCb), nameof(GameKitResourcesInstanceCreateWithRootPaths), IntPtr.Zero); return _featureResourcesInstance; } public void ResourcesInstanceRelease() { if (_featureResourcesInstance != IntPtr.Zero) { DllLoader.TryDll(() => GameKitResourcesInstanceRelease(GetResourcesInstance()), nameof(GameKitResourcesInstanceRelease)); _featureResourcesInstance = IntPtr.Zero; } } public uint ResourcesCreateEmptyConfigFile() { return DllLoader.TryDll(() => GameKitResourcesCreateEmptyConfigFile(GetResourcesInstance()), nameof(GameKitResourcesCreateEmptyConfigFile), GameKitErrors.GAMEKIT_ERROR_GENERAL); } #endregion #region GameKitSettings public IntPtr GetSettingsInstance() { if (_settingsInstance == IntPtr.Zero) { throw new GameKitInstanceNotFound("CoreWrapper::SettingsInstanceCreate() must be called with proper paths before any settings methods can be used"); } return _settingsInstance; } public IntPtr SettingsInstanceCreate(string rootPath, string pluginVersion, string shortGameName, string currentEnvironment, FuncLoggingCallback logCb) { if (_settingsInstance == IntPtr.Zero) { _settingsInstance = DllLoader.TryDll<IntPtr>(() => GameKitSettingsInstanceCreate(rootPath, pluginVersion, shortGameName, currentEnvironment, logCb), nameof(GameKitSettingsInstanceCreate), IntPtr.Zero); } return _settingsInstance; } public void SettingsInstanceRelease() { if (_settingsInstance != IntPtr.Zero) { DllLoader.TryDll(() => GameKitSettingsInstanceRelease(GetSettingsInstance()), nameof(GameKitSettingsInstanceRelease)); _settingsInstance = IntPtr.Zero; } } public void SettingsSetGameName(string gameName) { DllLoader.TryDll(() => GameKitSettingsSetGameName(GetSettingsInstance(), gameName), nameof(GameKitSettingsSetGameName)); } public string SettingsGetGameName() { StringCallbackResult results = new StringCallbackResult(); DllLoader.TryDll(results, (IntPtr dispatchReceiver) => GameKitSettingsGetGameName(GetSettingsInstance(), dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitSettingsGetGameName)); return results.ResponseValue; } public void SettingsSetLastUsedRegion(string region) { DllLoader.TryDll(() => GameKitSettingsSetLastUsedRegion(GetSettingsInstance(), region), nameof(GameKitSettingsSetLastUsedRegion)); } public string SettingsGetLastUsedRegion() { StringCallbackResult results = new StringCallbackResult(); DllLoader.TryDll(results, (IntPtr dispatchReceiver) => GameKitSettingsGetLastUsedRegion(GetSettingsInstance(), dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitSettingsGetLastUsedRegion)); return results.ResponseValue; } public void SettingsSetLastUsedEnvironment(string envcode) { DllLoader.TryDll(() => GameKitSettingsSetLastUsedEnvironment(GetSettingsInstance(), envcode), nameof(GameKitSettingsSetLastUsedEnvironment)); } public string SettingsGetLastUsedEnvironment() { StringCallbackResult results = new StringCallbackResult(); DllLoader.TryDll(results, (IntPtr dispatchReceiver) => GameKitSettingsGetLastUsedEnvironment(GetSettingsInstance(), dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitSettingsGetLastUsedEnvironment)); return results.ResponseValue; } public Dictionary<string, string> SettingsGetCustomEnvironments() { MultiKeyValueStringCallbackResult callbackResults = new MultiKeyValueStringCallbackResult(); DllLoader.TryDll(callbackResults, (IntPtr dispatchReceiver) => GameKitSettingsGetCustomEnvironments(GetSettingsInstance(), dispatchReceiver, GameKitCallbacks.MultiKeyValueStringCallback), nameof(GameKitSettingsGetCustomEnvironments)); Dictionary<string, string> results = new Dictionary<string, string>(); for (uint i = 0; i < callbackResults.ResponseKeys.Length; ++i) { results[callbackResults.ResponseKeys[i]] = callbackResults.ResponseValues[i]; } return results; } public Dictionary<string, string> SettingsGetFeatureVariables(FeatureType featureType) { MultiKeyValueStringCallbackResult callbackResults = new MultiKeyValueStringCallbackResult(); DllLoader.TryDll(callbackResults, (IntPtr dispatchReceiver) => GameKitSettingsGetFeatureVariables(GetSettingsInstance(), dispatchReceiver, featureType, GameKitCallbacks.MultiKeyValueStringCallback), nameof(GameKitSettingsGetFeatureVariables)); Dictionary<string, string> results = new Dictionary<string, string>(); for (uint i = 0; i < callbackResults.ResponseKeys.Length; ++i) { results[callbackResults.ResponseKeys[i]] = callbackResults.ResponseValues[i]; } return results; } public void SettingsAddCustomEnvironment(string envCode, string envDescription) { DllLoader.TryDll(() => GameKitSettingsAddCustomEnvironment(GetSettingsInstance(), envCode, envDescription), nameof(GameKitSettingsAddCustomEnvironment)); } public void SettingsSetFeatureVariables(FeatureType featureType, string[] varKeys, string[] varValues, ulong numKeys) { DllLoader.TryDll(() => GameKitSettingsSetFeatureVariables(GetSettingsInstance(), featureType, varKeys, varValues, numKeys), nameof(GameKitSettingsAddCustomEnvironment)); } public uint SettingsSave() { return DllLoader.TryDll(() => GameKitSettingsSave(GetSettingsInstance()), nameof(GameKitSettingsSave), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint SettingsPopulateAndSave(string gameName, string envCode, string region) { return DllLoader.TryDll(() => GameKitSettingsPopulateAndSave(GetSettingsInstance(), gameName, envCode, region), nameof(GameKitSettingsPopulateAndSave), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public string SettingsGetSettingsFilePath() { StringCallbackResult results = new StringCallbackResult(); DllLoader.TryDll(results, (IntPtr dispatchReceiver) => GameKitSettingsGetSettingsFilePath(GetSettingsInstance(), dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitSettingsGetSettingsFilePath)); return results.ResponseValue; } public uint SaveAWSCredentials(string profileName, string accessKey, string secretKey, FuncLoggingCallback logCb) { return DllLoader.TryDll(() => GameKitSaveAwsCredentials(profileName, accessKey, secretKey, logCb), nameof(GameKitSaveAwsCredentials), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public bool AwsProfileExists(string profileName) { return DllLoader.TryDll(() => GameKitAwsProfileExists(profileName), nameof(GameKitAwsProfileExists), false); } public uint SetAWSAccessKey(string profileName, string newAccessKey, FuncLoggingCallback logCb) { return DllLoader.TryDll(() => GameKitSetAwsAccessKey(profileName, newAccessKey, logCb), nameof(GameKitSetAwsAccessKey), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint SetAWSSecretKey(string profileName, string newSecretKey, FuncLoggingCallback logCb) { return DllLoader.TryDll(() => GameKitSetAwsSecretKey(profileName, newSecretKey, logCb), nameof(GameKitSetAwsSecretKey), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public KeyValueStringCallbackResult GetAWSProfile(string profileName, FuncLoggingCallback logCb) { KeyValueStringCallbackResult results = new KeyValueStringCallbackResult(); uint status = DllLoader.TryDll(results, (IntPtr dispatchReceiver) => GameKitGetAwsProfile(profileName, dispatchReceiver, GameKitCallbacks.KeyValueStringCallback, logCb), nameof(GameKitGetAwsProfile), GameKitErrors.GAMEKIT_ERROR_GENERAL); results.ResultCode = status; return results; } #endregion #region Deployment Orchestrator public IntPtr GetDeploymentOrchestratorInstance() { if (_deploymentOrchestrator == IntPtr.Zero) { throw new GameKitInstanceNotFound("CoreWrapper::DeploymentOrchestratorInstanceCreate() must be called with proper paths before any settings methods can be used"); } return _deploymentOrchestrator; } public IntPtr DeploymentOrchestratorInstanceCreate(string baseTemplatesFolder, string instanceFilesFolder) { if (_deploymentOrchestrator == IntPtr.Zero) { string sourceEngine = "UNITY"; string version = "UNKNOWN"; UnityEditor.PackageManager.Requests.ListRequest req = UnityEditor.PackageManager.Client.List(); while (!req.IsCompleted) { // Keep sleeping until all package info is read from disk, takes about 0.5 - 1.5 seconds for request to read as complete System.Threading.Thread.Sleep(250); } foreach (UnityEditor.PackageManager.PackageInfo item in req.Result) { if (item.name == GameKitPaths.Get().GAME_KIT_FOLDER_NAME) { version = item.version; } } _deploymentOrchestrator = DllLoader.TryDll<IntPtr>(() => GameKitDeploymentOrchestratorCreate( baseTemplatesFolder, instanceFilesFolder, sourceEngine, version, Logging.LogCb), nameof(GameKitDeploymentOrchestratorCreate), IntPtr.Zero); } return _deploymentOrchestrator; } public void DeploymentOrchestratorInstanceRelease() { if (_deploymentOrchestrator != IntPtr.Zero) { DllLoader.TryDll(() => GameKitDeploymentOrchestratorInstanceRelease(GetDeploymentOrchestratorInstance()), nameof(GameKitDeploymentOrchestratorInstanceRelease)); _deploymentOrchestrator = IntPtr.Zero; } } public uint DeploymentOrchestratorSetCredentials(SetCredentialsDesc setCredentialsDesc) { return DllLoader.TryDll(() => GameKitDeploymentOrchestratorSetCredentials(GetDeploymentOrchestratorInstance(), setCredentialsDesc.AccountInfo, setCredentialsDesc.AccountCredentials), nameof(GameKitDeploymentOrchestratorSetCredentials), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public FeatureStatus DeploymentOrchestratorGetFeatureStatus(FeatureType feature) { return DllLoader.TryDll(() => GameKitDeploymentOrchestratorGetFeatureStatus(GetDeploymentOrchestratorInstance(), feature), nameof(GameKitDeploymentOrchestratorGetFeatureStatus), FeatureStatus.Unknown); } public FeatureStatusSummary DeploymentOrchestratorGetFeatureStatusSummary(FeatureType feature) { return DllLoader.TryDll(() => GameKitDeploymentOrchestratorGetFeatureStatusSummary(GetDeploymentOrchestratorInstance(), feature), nameof(GameKitDeploymentOrchestratorGetFeatureStatusSummary), FeatureStatusSummary.Unknown); } public bool DeploymentOrchestratorIsFeatureDeploymentInProgress(FeatureType feature) { return DllLoader.TryDll(() => GameKitDeploymentOrchestratorIsFeatureDeploymentInProgress(GetDeploymentOrchestratorInstance(), feature), nameof(GameKitDeploymentOrchestratorIsFeatureDeploymentInProgress), false); } public bool DeploymentOrchestratorIsFeatureUpdating(FeatureType feature) { return DllLoader.TryDll(() => GameKitDeploymentOrchestratorIsFeatureUpdating(GetDeploymentOrchestratorInstance(), feature), nameof(GameKitDeploymentOrchestratorIsFeatureUpdating), false); } public bool DeploymentOrchestratorIsAnyFeatureUpdating() { return DllLoader.TryDll(() => GameKitDeploymentOrchestratorIsAnyFeatureUpdating(GetDeploymentOrchestratorInstance()), nameof(GameKitDeploymentOrchestratorIsAnyFeatureUpdating), false); } public DeploymentResponseResult DeploymentOrchestratorRefreshFeatureStatus(FeatureType feature) { DeploymentResponseResult result = new DeploymentResponseResult(); DeploymentResponseCallbackResult callbackResult = new DeploymentResponseCallbackResult(); result.ResultCode = DllLoader.TryDll(callbackResult, (IntPtr dispatchReceiver) => GameKitDeploymentOrchestratorRefreshFeatureStatus(GetDeploymentOrchestratorInstance(), feature, dispatchReceiver, GameKitCallbacks.DeploymentResponseCallback), nameof(GameKitDeploymentOrchestratorRefreshFeatureStatus), GameKitErrors.GAMEKIT_ERROR_GENERAL); for (int i = 0; i < callbackResult.Features.Length; ++i) { result.FeatureStatuses[callbackResult.Features[i]] = callbackResult.FeatureStatuses[i]; } return result; } public DeploymentResponseResult DeploymentOrchestratorRefreshFeatureStatuses() { DeploymentResponseResult result = new DeploymentResponseResult(); DeploymentResponseCallbackResult callbackResult = new DeploymentResponseCallbackResult(); result.ResultCode = DllLoader.TryDll(callbackResult, (IntPtr dispatchReceiver) => GameKitDeploymentOrchestratorRefreshFeatureStatuses(GetDeploymentOrchestratorInstance(), dispatchReceiver, GameKitCallbacks.DeploymentResponseCallback), nameof(GameKitDeploymentOrchestratorRefreshFeatureStatuses), GameKitErrors.GAMEKIT_ERROR_GENERAL); for (int i = 0; i < callbackResult.Features.Length; ++i) { result.FeatureStatuses[callbackResult.Features[i]] = callbackResult.FeatureStatuses[i]; } return result; } public CanExecuteDeploymentActionResult DeploymentOrchestratorCanCreateFeature(FeatureType feature) { CanExecuteDeploymentActionResult result = new CanExecuteDeploymentActionResult(); DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitDeploymentOrchestratorCanCreateFeature(GetDeploymentOrchestratorInstance(), feature, dispatchReceiver, GameKitCallbacks.CanExecuteDeploymentActionCallback), nameof(GameKitDeploymentOrchestratorCanCreateFeature), false); return result; } public CanExecuteDeploymentActionResult DeploymentOrchestratorCanRedeployFeature(FeatureType feature) { CanExecuteDeploymentActionResult result = new CanExecuteDeploymentActionResult(); DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitDeploymentOrchestratorCanRedeployFeature(GetDeploymentOrchestratorInstance(), feature, dispatchReceiver, GameKitCallbacks.CanExecuteDeploymentActionCallback), nameof(GameKitDeploymentOrchestratorCanRedeployFeature), false); return result; } public CanExecuteDeploymentActionResult DeploymentOrchestratorCanDeleteFeature(FeatureType feature) { CanExecuteDeploymentActionResult result = new CanExecuteDeploymentActionResult(); DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitDeploymentOrchestratorCanDeleteFeature(GetDeploymentOrchestratorInstance(), feature, dispatchReceiver, GameKitCallbacks.CanExecuteDeploymentActionCallback), nameof(GameKitDeploymentOrchestratorCanDeleteFeature), false); return result; } public DeploymentResponseResult DeploymentOrchestratorCreateFeature(FeatureType feature) { DeploymentResponseResult result = new DeploymentResponseResult(); DeploymentResponseCallbackResult callbackResult = new DeploymentResponseCallbackResult(); result.ResultCode = DllLoader.TryDll(callbackResult, (IntPtr dispatchReceiver) => GameKitDeploymentOrchestratorCreateFeature(GetDeploymentOrchestratorInstance(), feature, dispatchReceiver, GameKitCallbacks.DeploymentResponseCallback), nameof(GameKitDeploymentOrchestratorCreateFeature), GameKitErrors.GAMEKIT_ERROR_GENERAL); for (int i = 0; i < callbackResult.Features.Length; ++i) { result.FeatureStatuses[callbackResult.Features[i]] = callbackResult.FeatureStatuses[i]; } return result; } public DeploymentResponseResult DeploymentOrchestratorRedeployFeature(FeatureType feature) { DeploymentResponseResult result = new DeploymentResponseResult(); DeploymentResponseCallbackResult callbackResult = new DeploymentResponseCallbackResult(); result.ResultCode = DllLoader.TryDll(callbackResult, (IntPtr dispatchReceiver) => GameKitDeploymentOrchestratorRedeployFeature(GetDeploymentOrchestratorInstance(), feature, dispatchReceiver, GameKitCallbacks.DeploymentResponseCallback), nameof(GameKitDeploymentOrchestratorRedeployFeature), GameKitErrors.GAMEKIT_ERROR_GENERAL); for (int i = 0; i < callbackResult.Features.Length; ++i) { result.FeatureStatuses[callbackResult.Features[i]] = callbackResult.FeatureStatuses[i]; } return result; } public DeploymentResponseResult DeploymentOrchestratorDeleteFeature(FeatureType feature) { DeploymentResponseResult result = new DeploymentResponseResult(); DeploymentResponseCallbackResult callbackResult = new DeploymentResponseCallbackResult(); result.ResultCode = DllLoader.TryDll(callbackResult, (IntPtr dispatchReceiver) => GameKitDeploymentOrchestratorDeleteFeature(GetDeploymentOrchestratorInstance(), feature, dispatchReceiver, GameKitCallbacks.DeploymentResponseCallback), nameof(GameKitDeploymentOrchestratorDeleteFeature), GameKitErrors.GAMEKIT_ERROR_GENERAL); for (int i = 0; i < callbackResult.Features.Length; ++i) { result.FeatureStatuses[callbackResult.Features[i]] = callbackResult.FeatureStatuses[i]; } return result; } public MultiResourceInfoCallbackResult DeploymentOrchestratorDescribeFeatureResources(FeatureType feature) { MultiResourceInfoCallbackResult result = new MultiResourceInfoCallbackResult(); DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitDeploymentOrchestratorDescribeFeatureResources(GetDeploymentOrchestratorInstance(), feature, dispatchReceiver, GameKitCallbacks.MultiResourceInfoCallback), nameof(GameKitDeploymentOrchestratorDescribeFeatureResources), GameKitErrors.GAMEKIT_ERROR_GENERAL); return result; } #endregion #endif } }
574
aws-gamekit-unity
aws
C#
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This was generated by a script, do not modify! namespace AWS.GameKit.Runtime.Core { /// <summary> /// Constants with a 1:1 match to GameKit DLL API return values. /// </summary> public static class GameKitErrors { public const uint GAMEKIT_SUCCESS = 0x0; public const uint GAMEKIT_ERROR_INVALID_PROVIDER = 0x2; public const uint GAMEKIT_ERROR_PARAMETERS_FILE_SAVE_FAILED = 0x3; public const uint GAMEKIT_ERROR_CLOUDFORMATION_FILE_SAVE_FAILED = 0x4; public const uint GAMEKIT_ERROR_SETTINGS_FILE_SAVE_FAILED = 0x5; public const uint GAMEKIT_ERROR_NO_ID_TOKEN = 0x6; public const uint GAMEKIT_ERROR_HTTP_REQUEST_FAILED = 0x7; public const uint GAMEKIT_ERROR_PARSE_JSON_FAILED = 0x8; public const uint GAMEKIT_ERROR_SIGN_REQUEST_FAILED = 0x9; public const uint GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED = 0xA; public const uint GAMEKIT_ERROR_FILE_OPEN_FAILED = 0xB; public const uint GAMEKIT_ERROR_FILE_WRITE_FAILED = 0xC; public const uint GAMEKIT_ERROR_FILE_READ_FAILED = 0xD; public const uint GAMEKIT_ERROR_DIRECTORY_CREATE_FAILED = 0xE; public const uint GAMEKIT_ERROR_DIRECTORY_NOT_FOUND = 0xF; public const uint GAMEKIT_ERROR_FUNCTIONS_COPY_FAILED = 0x10; public const uint GAMEKIT_ERROR_METHOD_NOT_IMPLEMENTED = 0x15E; public const uint GAMEKIT_ERROR_GENERAL = 0x15F; public const uint GAMEKIT_ERROR_REGION_CODE_CONVERSION_FAILED = 0x160; public const uint GAMEKIT_ERROR_CREDENTIALS_FILE_NOT_FOUND = 0x161; public const uint GAMEKIT_ERROR_CREDENTIALS_FILE_SAVE_FAILED = 0x162; public const uint GAMEKIT_ERROR_CREDENTIALS_NOT_FOUND = 0x163; public const uint GAMEKIT_ERROR_CREDENTIALS_FILE_MALFORMED = 0x164; public const uint GAMEKIT_ERROR_REQUEST_TIMED_OUT = 0x165; public const uint GAMEKIT_ERROR_SETTINGS_MISSING = 0x166; public const uint GAMEKIT_ERROR_BOOTSTRAP_BUCKET_LOOKUP_FAILED = 0x1F5; public const uint GAMEKIT_ERROR_BOOTSTRAP_BUCKET_CREATION_FAILED = 0x1F6; public const uint GAMEKIT_ERROR_BOOTSTRAP_INVALID_REGION_CODE = 0x1F7; public const uint GAMEKIT_ERROR_BOOTSTRAP_MISSING_PLUGIN_ROOT = 0x1F8; public const uint GAMEKIT_ERROR_BOOTSTRAP_REGION_CODE_CONVERSION_FAILED = 0x1F9; public const uint GAMEKIT_ERROR_BOOTSTRAP_TOO_MANY_BUCKETS = 0x1FA; public const uint GAMEKIT_ERROR_FUNCTIONS_PATH_NOT_FOUND = 0x3E9; public const uint GAMEKIT_ERROR_CLOUDFORMATION_PATH_NOT_FOUND = 0x3EA; public const uint GAMEKIT_ERROR_FUNCTION_ZIP_INIT_FAILED = 0x3EB; public const uint GAMEKIT_ERROR_FUNCTION_ZIP_WRITE_FAILED = 0x3EC; public const uint GAMEKIT_ERROR_PARAMSTORE_WRITE_FAILED = 0x3ED; public const uint GAMEKIT_ERROR_BOOTSTRAP_BUCKET_UPLOAD_FAILED = 0x3EE; public const uint GAMEKIT_ERROR_SECRETSMANAGER_WRITE_FAILED = 0x3EF; public const uint GAMEKIT_ERROR_CLOUDFORMATION_STACK_CREATION_FAILED = 0x3F0; public const uint GAMEKIT_ERROR_CLOUDFORMATION_STACK_UPDATE_FAILED = 0x3F1; public const uint GAMEKIT_ERROR_CLOUDFORMATION_RESOURCE_CREATION_FAILED = 0x3F2; public const uint GAMEKIT_ERROR_CLOUDFORMATION_STACK_DELETE_FAILED = 0x3F3; public const uint GAMEKIT_ERROR_CLOUDFORMATION_DESCRIBE_RESOURCE_FAILED = 0x3F4; public const uint GAMEKIT_ERROR_CLOUDFORMATION_DESCRIBE_STACKS_FAILED = 0x3F5; public const uint GAMEKIT_ERROR_APIGATEWAY_DEPLOYMENT_CREATION_FAILED = 0x3F6; public const uint GAMEKIT_ERROR_APIGATEWAY_STAGE_DEPLOYMENT_FAILED = 0x3F7; public const uint GAMEKIT_ERROR_LAYERS_PATH_NOT_FOUND = 0x3F8; public const uint GAMEKIT_ERROR_LAYER_ZIP_INIT_FAILED = 0x3F9; public const uint GAMEKIT_ERROR_LAYER_ZIP_WRITE_FAILED = 0x3FA; public const uint GAMEKIT_ERROR_LAYER_CREATION_FAILED = 0x3FB; public const uint GAMEKIT_ERROR_CLOUDFORMATION_GET_TEMPLATE_FAILED = 0x3FC; public const uint GAMEKIT_ERROR_PARAMSTORE_READ_FAILED = 0x3FD; public const uint GAMEKIT_ERROR_CLOUDFORMATION_NO_CURRENT_STACK_STATUS = 0x3FE; public const uint GAMEKIT_ERROR_REGISTER_USER_FAILED = 0x10000; public const uint GAMEKIT_ERROR_CONFIRM_REGISTRATION_FAILED = 0x10001; public const uint GAMEKIT_ERROR_RESEND_CONFIRMATION_CODE_FAILED = 0x10002; public const uint GAMEKIT_ERROR_LOGIN_FAILED = 0x10003; public const uint GAMEKIT_ERROR_FORGOT_PASSWORD_FAILED = 0x10004; public const uint GAMEKIT_ERROR_CONFIRM_FORGOT_PASSWORD_FAILED = 0x10005; public const uint GAMEKIT_ERROR_LOGOUT_FAILED = 0x10007; public const uint GAMEKIT_ERROR_MALFORMED_USERNAME = 0x10008; public const uint GAMEKIT_ERROR_MALFORMED_PASSWORD = 0x10009; public const uint GAMEKIT_ERROR_INVALID_FEDERATED_IDENTITY_PROVIDER = 0x10010; public const uint GAMEKIT_ERROR_ACHIEVEMENTS_ICON_UPLOAD_FAILED = 0x10800; public const uint GAMEKIT_ERROR_ACHIEVEMENTS_INVALID_ID = 0x10801; public const uint GAMEKIT_ERROR_ACHIEVEMENTS_PAYLOAD_TOO_LARGE = 0x10802; public const uint GAMEKIT_ERROR_USER_GAMEPLAY_DATA_PAYLOAD_INVALID = 0x010C00; public const uint GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED = 0x010C01; public const uint GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED = 0x010C02; public const uint GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED = 0x010C03; public const uint GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME = 0x010C04; public const uint GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY = 0x010C05; public const uint GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_WRITE_FAILED = 0x010C06; public const uint GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_READ_FAILED = 0x010C07; public const uint GAMEKIT_ERROR_USER_GAMEPLAY_DATA_UNPROCESSED_ITEMS = 0x010C08; public const uint GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND = 0x11000; public const uint GAMEKIT_ERROR_GAME_SAVING_CLOUD_SLOT_IS_NEWER = 0x11001; public const uint GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT = 0x11002; public const uint GAMEKIT_ERROR_GAME_SAVING_DOWNLOAD_SLOT_ALREADY_IN_SYNC = 0x11003; public const uint GAMEKIT_ERROR_GAME_SAVING_UPLOAD_SLOT_ALREADY_IN_SYNC = 0x11004; public const uint GAMEKIT_ERROR_GAME_SAVING_EXCEEDED_MAX_SIZE = 0x11005; public const uint GAMEKIT_ERROR_GAME_SAVING_FILE_EMPTY = 0x11006; public const uint GAMEKIT_ERROR_GAME_SAVING_FILE_FAILED_TO_OPEN = 0x11007; public const uint GAMEKIT_ERROR_GAME_SAVING_LOCAL_SLOT_IS_NEWER = 0x11008; public const uint GAMEKIT_ERROR_GAME_SAVING_SLOT_UNKNOWN_SYNC_STATUS = 0x11009; public const uint GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME = 0x1100A; public const uint GAMEKIT_ERROR_GAME_SAVING_MISSING_SHA = 0x1100B; public const uint GAMEKIT_ERROR_GAME_SAVING_SLOT_TAMPERED = 0x1100C; public const uint GAMEKIT_ERROR_GAME_SAVING_BUFFER_TOO_SMALL = 0x1100D; public const uint GAMEKIT_ERROR_GAME_SAVING_MAX_CLOUD_SLOTS_EXCEEDED = 0x1100E; public const uint GAMEKIT_WARNING_SECRETSMANAGER_SECRET_NOT_FOUND = 0x11400; public static string ToString(uint gameKitError) => "0x" + gameKitError.ToString("X"); } }
107
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Features.GameKitUserGameplayData; using AWS.GameKit.Runtime.Features.GameKitGameSaving; using AWS.GameKit.Runtime.Features.GameKitAchievements; using AWS.GameKit.Runtime.Features.GameKitIdentity; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.Core { /// <summary> /// Manager for all GameKit features. /// </summary> public class GameKitManager : IDisposable { /// <summary> /// The count of how many features are currently being managed by the GameKitManager. /// </summary> public int FeatureCount => _features.Count; protected List<GameKitFeatureBase> _features = new List<GameKitFeatureBase>(); private SessionManager _sessionManager = SessionManager.Get(); private bool _disposedValue = false; private bool _isInitialized = false; /// <summary> /// Constructs a GameKitManager object. /// </summary> /// <remarks> /// This should only be called from within Unity's main game thread. /// </remarks> public GameKitManager() { AddFeatures(); } ~GameKitManager() => Dispose(); /// <summary> /// Public initializer used to manually initialize feature where required. /// </summary> /// <param name="reinitialize">When true, forces reinitialization of all features even if they are already initialized.</param> public void EnsureFeaturesAreInitialized(bool reinitialize = false) { if (!_isInitialized || reinitialize) { Logging.LogInfo("GameKitManager: initializing features."); ReloadConfigFile(); // initialize all of the features in list order _features.ForEach(feature => feature.OnInitialize()); _isInitialized = true; } } /// <summary> /// Public implementation of Dispose pattern callable by consumers. Used to manually cleanup the GameKitManager. /// </summary> public void Dispose() { if (!_disposedValue) { Logging.LogInfo("GameKitManager: cleaning up features."); // cleanup each of the features in reverse list order try { for (int i = _features.Count - 1; i >= 0; --i) { _features[i].OnDispose(); } } finally { _isInitialized = false; } // release the session manager's instance _sessionManager.Release(); _disposedValue = true; } GC.SuppressFinalize(this); } /// <summary> /// Public OnApplicationPause method for the GameKitManager, this is intended to be called from a Monbehavior OnApplicationPauseMethod. /// This can be used to notify features that a game instance has been paused or unpaused. /// <param name="isPaused">True if the application is paused, else False.</param> /// </summary> public void OnApplicationPause(bool isPaused) { // Notify all features that the application pause status has been changed _features.ForEach(feature => feature.OnApplicationPause(isPaused)); } /// <summary> /// Public OnApplicationQuit method for the GameKitManager, this is intended to be called from a Monbehavior OnApplicationQuit. /// This can be used to notify features that a game instance has been quit. /// /// OnApplicationQuit is called in both Standalone and Editor mode unlike Dispose which is only called in Standalone. /// </summary> public void OnApplicationQuit() { // Notify all features that the application has been quit _features.ForEach(feature => feature.OnApplicationQuit()); } /// <summary> /// Public update method for the GameKitManager, this is intended to only be called during a Monobehavior update or editor update. /// </summary> public void Update() { // update each feature _features.ForEach(feature => feature.Update()); } /// <summary> /// See SessionManager.ReloadConfig(). /// </summary> /// <remarks> /// This method must be called before using any GameKit feature APIs. /// </remarks> /// <returns>True if every feature's settings are loaded in memory from the "awsGameKitClientConfig.yml" file, false otherwise.</returns> public bool ReloadConfigFile() { #if (UNITY_ANDROID || UNITY_IPHONE || UNITY_IOS) && !UNITY_EDITOR _sessionManager.ReloadConfigMobile(); #else _sessionManager.ReloadConfig(); #endif return AreAllFeatureSettingsLoaded(); } /// <summary> /// Return true if every feature's settings are loaded in memory from the config file, false otherwise. /// </summary> public bool AreAllFeatureSettingsLoaded() { bool result = false; _features.ForEach(feature => { result &= AreFeatureSettingsLoaded(feature.FeatureType); }); return result; } /// <summary> /// See SessionManager.AreSettingsLoaded(). /// </summary> /// <remarks> /// These settings are found in file "awsGameKitClientConfig.yml" which is generated by GameKit each time you deploy or re-deploy a feature. /// The file is loaded by calling either SessionManagerWrapper.Create() or SessionManagerWrapper.ReloadConfigFile(). /// </remarks> /// <param name="type">FeatureType enum that is being checked</param> /// <returns>True if the settings for the feature are loaded, false otherwise.</returns> public bool AreFeatureSettingsLoaded(FeatureType type) { return _sessionManager.AreSettingsLoaded(type); } #if UNITY_EDITOR /// <summary> /// See SessionManager.CopyAndReloadConfig(). /// </summary> /// <param name="gameAlias">The game's alias, ex: "mygame".</param> /// <param name="environmentCode">The environment to copy the config from, ex: "dev".</param> /// <returns>True if the "awsGameKitClientConfig.yml" was reloaded successfully, false otherwise.</returns> public void CopyAndReloadConfigFile(string gameAlias, string environmentCode) { _sessionManager.CopyAndReloadConfig(gameAlias, environmentCode); #if UNITY_ANDROID _sessionManager.CopyConfigToMobileAssets(gameAlias, environmentCode); #endif } /// <summary> /// See SessionManager.DoesConfigFileExist(). /// </summary> /// <param name="gameAlias">The game's alias, ex: "mygame".</param> /// <param name="environmentCode">The environment to copy the config from, ex: "dev".</param> public bool DoesConfigFileExist(string gameAlias, string environmentCode) { return _sessionManager.DoesConfigFileExist(gameAlias, environmentCode); } #endif #if UNITY_EDITOR /// <summary> /// Add a feature which is only used inside the Unity editor. This method should only be called by AWS GameKit. Game developers don't need to call this method. /// </summary> public void AddEditorOnlyFeature(GameKitFeatureBase feature) { _features.Add(feature); EnsureFeaturesAreInitialized(reinitialize: true); } #endif protected virtual void AddFeatures() { // add features that need to be initialized first _features.Add(Identity.Get()); // add all features, if a feature is not wanted and the DLLs are removed then it should be commented out here as well _features.Add(Achievements.Get()); _features.Add(UserGameplayData.Get()); _features.Add(GameSaving.Get()); } protected void SetSessionManager(SessionManager sessionManager) { _sessionManager = sessionManager; } } }
231
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Runtime.Core { /// <summary> /// Interface for the AWS GameKit Core APIs. /// </summary> public interface ICoreWrapperProvider { #if UNITY_EDITOR #region GameKitAccount /// <summary> /// Get the AWS Account ID which corresponds to the provided Access Key and Secret Key. /// </summary> /// <remarks> /// For more information about AWS access keys and secret keys, see: https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys /// </remarks> /// <param name="accountCredentials">Struct containing an access key and secret key.</param> /// <returns>StringCallbackResults which contains a ChrPtr result containing the Account ID and the result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult GameKitErrors.cs file for details.</returns> public StringCallbackResult GetAWSAccountId(GetAWSAccountIdDescription accountCredentials); /// <summary> /// Gets (and creates if necessary) a GameKitAccount instance, which can be used to access the Core Account APIs. /// </summary> /// <remarks> /// Make sure to call AccountInstanceRelease() to destroy the returned object when finished with it. /// </remarks> /// <returns>Pointer to the new GameKitAccount instance.</returns> public IntPtr GetAccountInstance(); /// <summary> /// Create a GameKitAccount instance, which can be used to access the GameKitAccount API. /// </summary> /// <remarks> /// Make sure to call AccountInstanceRelease() to destroy the returned object when finished with it. /// </remarks> /// <param name="accountInfo">Struct holding account id, game name, and deployment environment.</param> /// <param name="credentials">Struct holding account id, region, access key, and secret key.</param> /// <param name="logCb">Callback function for logging information and errors.</param> /// <returns>Pointer to the new GameKitAccount instance.</returns> public IntPtr AccountInstanceCreate(AccountInfo accountInfo, AccountCredentials credentials, FuncLoggingCallback logCb); /// <summary> /// Create a GameKitAccount instance, which can be used to access the GameKitAccount API. Also sets the plugin and game root paths. /// </summary> /// <remarks> /// Make sure to call AccountInstanceRelease() to destroy the returned object when finished with it. /// </remarks> /// <param name="accountInfo">Struct holding account id, game name, and deployment environment.</param> /// <param name="credentials">Struct holding account id, region, access key, and secret key.</param> /// <param name="rootPath">New path for GAMEKIT_ROOT</param> /// <param name="pluginRootPath">New path for the plugin root directory.</param> /// <param name="logCb">Callback function for logging information and errors.</param> /// <returns>Pointer to the new GameKitAccount instance.</returns> public IntPtr AccountInstanceCreateWithRootPaths(AccountInfo accountInfo, AccountCredentials credentials, string rootPath, string pluginRootPath, FuncLoggingCallback logCb); /// <summary> /// Destroy the provided GameKitAccount instance. /// </summary> public void AccountInstanceRelease(); /// <summary> /// Get the GAMEKIT_ROOT path where the "instance" templates and settings are going to be stored. /// </summary> /// <returns>True if the credentials are valid, false otherwise.</returns> public bool AccountHasValidCredentials(); /// <summary> /// Create a bootstrap bucket in the AWS account if it doesn't already exist. /// </summary> /// <remarks> /// The bootstrap bucket must be created before deploying any stacks or Lambda functions. There needs to be a unique bootstrap bucket for each combination of Environment, Account ID, and GameName. /// </remarks> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult GameKitErrors.cs file for details.</returns> public uint AccountInstanceBootstrap(); /// <summary> /// Create or update a secret in AWS SecretsManager (https://aws.amazon.com/secrets-manager/). /// </summary> /// <remarks> /// The secret name will be "gamekit_<environment>_<gameName>_<secretName>", for example: "gamekit_dev_mygame_amazon_client_secret". /// </remarks> /// <param name="secretName">Name of the secret. Will be prefixed as described in the details.</param> /// <param name="secretValue">Value of the secret.</param> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult GameKitErrors.cs file for details.</returns> public uint GameKitAccountSaveSecret(string secretName, string secretValue); /// <summary> /// Checks if a secret exists in AWS SecretsManager (https://aws.amazon.com/secrets-manager/). /// </summary> /// <remarks> /// The secret name will be "gamekit_<environment>_<gameName>_<secretName>", for example: "gamekit_dev_mygame_amazon_client_secret". /// </remarks> /// <param name="secretName">Name of the secret. Will be prefixed as described in the details.</param> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult GameKitErrors.cs file for details.</returns> public uint GameKitAccountCheckSecretExists(string secretName); /// <summary> /// Upload the dashboard configuration file for every feature to the bootstrap bucket. /// </summary> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult GameKitErrors.cs file for details.</returns> public uint GameKitAccountUploadAllDashboards(); #endregion #region GameKitResources /// <summary> /// Gets (and creates if necessary) a GameKitResources instance, which can be used to access the Core Account APIs. /// </summary> /// <remarks> /// Make sure to call ResourcesInstanceRelease() to destroy the returned object when finished with it. /// </remarks> /// <returns>Pointer to the new GameKitResources instance.</returns> public IntPtr GetResourcesInstance(); /// <summary> /// Create a GameKitFeatureResources instance, which can be used to access the GameKitFeatureResources API. /// </summary> /// <remarks> /// Make sure to call GameKitResourcesInstanceRelease() to destroy the returned object when finished with it. /// </remarks> /// <param name="accountInfo">Struct holding account id, game name, and deployment environment.</param> /// <param name="credentials">Struct holding account id, region, access key, and secret key.</param> /// <param name="featureType">The GameKit feature to work with.</param> /// <param name="logCb">Callback function for logging information and errors.</param> /// <returns>Pointer to the new GameKitFeatureResources instance.</returns> public IntPtr ResourcesInstanceCreate(AccountInfo accountInfo, AccountCredentials credentials, FeatureType featureType, FuncLoggingCallback logCb); /// <summary> /// Create a GameKitFeatureResources instance, which can be used to access the GameKitFeatureResources API. Also sets the root and pluginRoot paths. /// </summary> /// <remarks> /// Make sure to call GameKitResourcesInstanceRelease() to destroy the returned object when finished with it. /// </remarks> /// <param name="accountInfo">Struct holding account id, game name, and deployment environment.</param> /// <param name="credentials">Struct holding account id, region, access key, and secret key.</param> /// <param name="featureType">The GameKit feature to work with.</param> /// <param name="rootPath">New path for GAMEKIT_ROOT.</param> /// <param name="pluginRootPath">New path for the plugin root directory.</param> /// <param name="logCb">Callback function for logging information and errors.</param> /// <returns>Pointer to the new GameKitFeatureResources instance.</returns> public IntPtr ResourcesInstanceCreateWithRootPaths(AccountInfo accountInfo, AccountCredentials credentials, FeatureType featureType, string rootPath, string pluginRootPath, FuncLoggingCallback logCb); /// <summary> /// Destroy the provided GameKitFeatureResources instance. /// </summary> public void ResourcesInstanceRelease(); /// <summary> /// Create an empty client configuration file in the current environment's instance files folder. /// </summary> /// <remarks> /// Call this to bootstrap a GameKit config file as soon as an environment has been selected. /// </remarks> /// <returns>The result status code of the operation (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. The empty config file was created.<br/> /// - GAMEKIT_ERROR_DIRECTORY_CREATE_FAILED: There was an error while creating missing directories in the filepath leading to the config file. Check the logs to see the root cause.<br/> /// - GAMEKIT_ERROR_FILE_OPEN_FAILED: There was an error while opening an output stream for the new or existing config file. Check the logs to see the root cause.<br/> /// - GAMEKIT_ERROR_FILE_WRITE_FAILED: There was an error while writing text to the config file. /// </returns> public uint ResourcesCreateEmptyConfigFile(); #endregion #region GameKitSettings /// <summary> /// Gets a GameKitSettings instance, which can be used to access the Core Settings APIs. /// </summary> /// <remarks> /// Make sure to call Release() to destroy the returned object when finished with it. /// </remarks> /// <returns>Pointer to the new GameKitSessionManager instance.</returns> public IntPtr GetSettingsInstance(); /// <summary> /// Create a GameKitSettings instance and load the settings from the GameKit Settings YAML file. /// </summary> /// <remarks> /// Make sure to call SettingsInstanceRelease() to destroy the returned object when finished with it. /// </remarks> /// <param name="rootPath">The GAMEKIT_ROOT path where the "instance" templates and settings are stored.</param> /// <param name="pluginVersion">The GameKit plugin version.</param> /// <param name="currentEnvironment">The current active environment based on what was selected in Environment and Credentials category eg "dev", "qa", custom</param> /// <param name="shortGameName">A shortened version of the game name.</param> /// <param name="logCb">Callback function for logging information and errors</param> /// <returns>Pointer to the new GameKitSettings instance.</returns> public IntPtr SettingsInstanceCreate(string rootPath, string pluginVersion, string shortGameName, string currentEnvironment, FuncLoggingCallback logCb); /// <summary> /// Destroy the provided GameKitSettings instance. /// </summary> public void SettingsInstanceRelease(); /// <summary> /// Set the game's name. /// </summary> /// <param name="gameName">The new game name.</param> public void SettingsSetGameName(string gameName); /// <summary> /// Get the game's full name, example: "Stevie goes to the moon". /// </summary> /// <returns>A string containing the name of the game.</returns> public string SettingsGetGameName(); /// <summary> /// Set the last used region. /// </summary> /// <param name="region">The region last used, example: "us-west-2".</param> public void SettingsSetLastUsedRegion(string region); /// <summary> /// Get the developers last submitted region, example: "us-west-2". /// </summary> /// <returns>A string containing the name of the last submitted region<./returns> public string SettingsGetLastUsedRegion(); /// <summary> /// Set the last used environment. /// </summary> /// <param name="envcode">The environment code.</param> public void SettingsSetLastUsedEnvironment(string envcode); /// <summary> /// Get the developers last submitted environment code, example: "dev". /// </summary> /// <returns>A string containing the last submitted environment code.</returns> public string SettingsGetLastUsedEnvironment(); /// <summary> /// Get all the custom environment key-value pairs (ex: "gam", "Gamma").<br/><br/> /// /// The custom environments are returned through the callback and receiver.<br/> /// The callback is invoked once for each custom environment.<br/> /// The returned keys are 3-letter environment codes(ex: "gam"), and the values are corresponding environment descriptions(ex: "Gamma"). /// </summary> /// <returns>A result object containing a map of environment key value pairs</returns> public Dictionary<string, string> SettingsGetCustomEnvironments(); /// <summary> /// Get all of the feature's variables as key-value pairs.<br/><br/> /// /// The variables are returned through the callback and receiver.<br/> /// The callback is invoked once for each variable.The variables are returned as key-value pairs of (variableName, variableValue).<br/> /// The callback will not be invoked if the feature is missing from the settings file. /// </summary> /// <param name="featureType">The feature to get the variables for</param> /// <returns>A result object containing a map of variable key value pairs</returns> public Dictionary<string, string> SettingsGetFeatureVariables(FeatureType featureType); /// <summary> /// Add a custom deployment environment to the AWS GameKit settings menu. /// </summary> /// <remarks> /// This custom environment will be available to select from the dropdown menu in the Environment and Credentials section of the settings menu, /// alongside the default environments of "Development", "QA", "Staging", and "Production". /// </remarks> /// <param name="envCode">Two to Three letter code for the environment name. This code will be prefixed on all AWS resources that are /// deployed to this environment.Ex: "gam" for "Gamma".</param> /// <param name="envDescription">envDescription The environment name that will be displayed in the Environment and Credentials section of the settings menu. Ex: "Gamma".</param> public void SettingsAddCustomEnvironment(string envCode, string envDescription); /// <summary> /// Add key-value pairs to the feature's variables map, overwriting existing keys. /// </summary> /// <remarks> /// The parameters "varKeys", "varValues", and "numKeys" represent a map<string, string>, where varKeys[N] maps to varValues[N], and numKeys is the total number of key-value pairs. /// </remarks> /// <param name="featureType">The feature to set the variables for.</param> /// <param name="varKeys">The variable names.</param> /// <param name="varValues">The variable values.</param> /// <param name="numKeys">The number of key-value pairs. The length of varKeys, varValues, and numKeys should be equal.</param> public void SettingsSetFeatureVariables(FeatureType featureType, string[] varKeys, string[] varValues, ulong numKeys); /// <summary> /// Write the GAMEKIT Settings YAML file to disk. /// </summary> /// <remarks> /// Call this to persist any changes made through the "Set", "Add/Delete", "Activate/Deactivate" methods. /// </remarks> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult GameKitErrors.cs file for details.</returns> public uint SettingsSave(); /// <summary> /// Set the Game's name, environment, and resion, then save settings /// </summary> /// <remarks> /// Use this method to create the settings file directory, set the game's name, set the games environment, set the games region, and then persist the settings. /// </remarks> /// <param name="gameName">The game's correctly formatted name</param> /// <param name="envCode">The 3-letter environment code to get the description for</param> /// <param name="region">The AWS deployment region</param> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult errors.h file for details.</returns> public uint SettingsPopulateAndSave(string gameName, string envCode, string region); /// <summary> /// Get the path to the "saveInfo.yml" settings file. /// </summary> /// <remarks> /// The path is equal to "GAMEKIT_ROOT/shortGameName/saveInfo.yml". /// </remarks> /// <returns>The path to "saveInfo.yml" as a string.</returns> public string SettingsGetSettingsFilePath(); /// <summary> /// Save a new profile to the AWS credentials file. /// </summary> /// <param name="profileName">The name of the profile we are saving or updating in the credentials ini file.</param> /// <param name="accessKey">The access key of the AWS IAM role we are saving.</param> /// <param name="secretKey">The secret key of the AWS IAM role we are saving.</param> /// <param name="logCb">Callback function for logging information and errors. </param> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult GameKitErrors.cs file for details.</returns> public uint SaveAWSCredentials(string profileName, string accessKey, string secretKey, FuncLoggingCallback logCb); /// <summary> /// Sets the AWS access key of an existing profile. /// </summary> /// <param name="profileName">The name of the profile we are updating in the credentials ini file.</param> /// <param name="newAccessKey">The new access key that will be assigned to this profile.</param> /// <param name="logCb">Callback function for logging information and errors. </param> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult GameKitErrors.cs file for details.</returns> public uint SetAWSAccessKey(string profileName, string newAccessKey, FuncLoggingCallback logCb); /// <summary> /// Sets the AWS secret key of an existing profile. /// </summary> /// <remarks> /// If the profile passed in does not exist, will not automatically create the profile and will return an error. /// </remarks> /// <param name="profileName">The name of the profile we are updating in the credentials ini file.</param> /// <param name="newSecretKey">The new secret key that will be assigned to this profile.</param> /// <param name="logCb">Callback function for logging information and errors. </param> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult GameKitErrors.cs file for details.</returns> public uint SetAWSSecretKey(string profileName, string newSecretKey, FuncLoggingCallback logCb); /// <summary> /// Gets the access key and secret key corresponding to a pre-existing profile in the AWS credentials file. /// </summary> /// <param name="profileName">The name of the profile we are getting the access key and secret from.</param> /// <param name="logCb">Callback function for logging information and errors. </param> /// <returns>Callback function for logging information and errors.</returns> public KeyValueStringCallbackResult GetAWSProfile(string profileName, FuncLoggingCallback logCb); #endregion #region Deployment Orchestrator /// <summary> /// Get a pointer to an already initialized GameKitDeploymentOrchestrator instance. /// </summary> /// <remarks>This method will throw if DeploymentOrchestratorInstanceCreate was not called prior to calling this method.</remarks> /// <returns>Pointer to the existing GameKitDeploymentOrchestrator instance.</returns> public IntPtr GetDeploymentOrchestratorInstance(); /// <summary> /// Create a GameKitDeploymentOrchestrator instance. /// </summary> /// <param name="baseTemplatesFolder">The folder where the "base" templates are stored. The base templates are the cloud formation templates, lambda functions, etc. which are copied to make the instance files (see next parameter).</param> /// <param name="instanceFilesFolder">The folder where the "instance" files and settings are going to be stored. The instance files are copied from the base templates, and are intended to be modified by the user.</param> /// <returns>Pointer to the new GameKitDeploymentOrchestrator instance.</returns> public IntPtr DeploymentOrchestratorInstanceCreate(string baseTemplatesFolder, string instanceFilesFolder); /// <summary> /// Destroy the provided GameKitDeploymentOrchestrator instance. /// </summary> public void DeploymentOrchestratorInstanceRelease(); /// <summary> /// Set account credentials. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="setCredentialsDesc">Object holding the AccountInfo and AccountCredentials.</param> /// <returns> /// The result status code of the operation (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_ORCHESTRATION_DEPLOYMENT_IN_PROGRESS: Cannot change credentials while a deployment is in progress. /// - GAMEKIT_ERROR_REGION_CODE_CONVERSION_FAILED: Could not retrieve the short region code from the mappings file. See the log for details on how to fix this. /// </returns> public uint DeploymentOrchestratorSetCredentials(SetCredentialsDesc setCredentialsDesc); /// <summary> /// Get the status of a requested feature. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns>FeatureStatus enum related to the status of the requested feature.</returns> public FeatureStatus DeploymentOrchestratorGetFeatureStatus(FeatureType feature); /// <summary> /// Get an abridged status of a requested feature. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns>FeatureStatusSummary enum related to the abridged status of the requested feature.</returns> public FeatureStatusSummary DeploymentOrchestratorGetFeatureStatusSummary(FeatureType feature); /// <summary> /// Check if the requested feature is currently being created, redeployed, or deleted. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures.<br/><br/> /// /// Unlike DeploymentOrchestratorIsFeatureUpdating, this method returns true while the Main stack is being deployed (before the feature itself is created or redeployed). /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns>true if the requested feature is being created, redeployed, or deleted.</returns> public bool DeploymentOrchestratorIsFeatureDeploymentInProgress(FeatureType feature); /// <summary> /// Check if the requested feature is currently updating (i.e. it's FeatureStatus is not Deployed, Undeployed, Error, or RollbackComplete). /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns>true if the requested feature is updating.</returns> public bool DeploymentOrchestratorIsFeatureUpdating(FeatureType feature); /// <summary> /// Check if any GameKit feature is currently updating (i.e. has a FeatureStatus other than Deployed, Undeployed, Error, or RollbackComplete). /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <returns>true if any feature is updating.</returns> public bool DeploymentOrchestratorIsAnyFeatureUpdating(); /// <summary> /// Refresh the status of a requested feature. /// </summary> /// <remarks> /// This is a long running operation. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// The <see cref="FeatureStatus"/> of all features and the result status code of the operation.<br/><br/> /// /// The result status code will be one of (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </returns> public DeploymentResponseResult DeploymentOrchestratorRefreshFeatureStatus(FeatureType feature); /// <summary> /// Refresh the status of all features. /// </summary> /// <remarks> /// This is a long running operation. /// </remarks> /// <returns> /// The <see cref="FeatureStatus"/> of all features and the result status code of the operation.<br/><br/> /// /// The result status code will be one of (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </returns> public DeploymentResponseResult DeploymentOrchestratorRefreshFeatureStatuses(); /// <summary> /// Request if a feature is in a state to be created. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// A <see cref="CanExecuteDeploymentActionResult"/> object describing whether the feature can be created.<br/> /// A <see cref="DeploymentActionBlockedReason"/> and list of blocking <see cref="FeatureType"/> are provided in cases where the feature cannot be created. /// </returns> public CanExecuteDeploymentActionResult DeploymentOrchestratorCanCreateFeature(FeatureType feature); /// <summary> /// Request if a feature can be re-deployed. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// A <see cref="CanExecuteDeploymentActionResult"/> object describing whether the feature can be redeployed.<br/> /// A <see cref="DeploymentActionBlockedReason"/> and list of blocking <see cref="FeatureType"/> are provided in cases where the feature cannot be redeployed. /// </returns> public CanExecuteDeploymentActionResult DeploymentOrchestratorCanRedeployFeature(FeatureType feature); /// <summary> /// Request if a feature is in a state where it can be deleted. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// A <see cref="CanExecuteDeploymentActionResult"/> object describing whether the feature can be deleted.<br/> /// A <see cref="DeploymentActionBlockedReason"/> and list of blocking <see cref="FeatureType"/> are provided in cases where the feature cannot be deleted. /// </returns> public CanExecuteDeploymentActionResult DeploymentOrchestratorCanDeleteFeature(FeatureType feature); /// <summary> /// Create a requested feature. /// </summary> /// <remarks> /// This is a long running operation. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// The <see cref="FeatureStatus"/> of all features and the result status code of the operation.<br/><br/> /// /// The result status code will be one of (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_ORCHESTRATION_INVALID_FEATURE_STATE: Cannot create feature as it or one of its dependencies are in an invalid state for deployment. /// </returns> public DeploymentResponseResult DeploymentOrchestratorCreateFeature(FeatureType feature); /// <summary> /// Re-deploy a requested feature. /// </summary> /// <remarks> /// This is a long running operation. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// The <see cref="FeatureStatus"/> of all features and the result status code of the operation.<br/><br/> /// /// The result status code will be one of (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_ORCHESTRATION_INVALID_FEATURE_STATE: Cannot redeploy feature as it or one of its dependencies are in an invalid state for deployment. /// </returns> public DeploymentResponseResult DeploymentOrchestratorRedeployFeature(FeatureType feature); /// <summary> /// Delete a requested feature. /// </summary> /// <remarks> /// This is a long running operation. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// The <see cref="FeatureStatus"/> of all features and the result status code of the operation.<br/><br/> /// /// The result status code will be one of (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_CLOUDFORMATION_STACK_DELETE_FAILED: Failed to delete the stack, check output log for exact reason.<br/> /// - GAMEKIT_ERROR_ORCHESTRATION_INVALID_FEATURE_STATE: Cannot delete feature as it or one of its downstream dependencies are in an invalid state for deletion. /// </returns> public DeploymentResponseResult DeploymentOrchestratorDeleteFeature(FeatureType feature); /// <summary> /// Gets the deployment status of each AWS resource within the specified feature. /// </summary> /// <remarks> /// This is a long running operation. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// The resource id, resource type, and resource status of each AWS resource within the specified feature.<br/><br/> /// /// Also returns the result status code of the operation, which will be one of (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_CLOUDFORMATION_DESCRIBE_RESOURCE_FAILED: If status of the resources could not be determined. /// </returns> public MultiResourceInfoCallbackResult DeploymentOrchestratorDescribeFeatureResources(FeatureType feature); #endregion #endif } }
584
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.IO; using System.Text; // Unity using UnityEditor; using UnityEngine; using UnityEngine.Networking; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Utils; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Runtime.Core { /// <summary> /// This class provides a high level interface for the SessionManager. /// Call SessionManager.Get() to get the singleton instance of this class. /// </summary> /// <remarks> /// The SessionManager provides APIs for loading and querying the "awsGameKitClientConfig.yaml" file, also known as "the config file".<br/><br/> /// /// The config file is loaded by calling ReloadConfig() or CopyAndReloadConfig().<br/><br/> /// /// The config file contains settings that are needed at runtime in order to call any of the GameKit feature APIs. /// The config file's settings are specific to the currently selected environment code (i.e. "dev", "qa", "prd", etc.). /// The environment can be changed in the "Environment & Credentials" page of the AWS GameKit Settings Window.<br/><br/> /// /// The config file is automatically created/updated each time a GameKit feature is created or redeployed, or when the environment changes (i.e. "dev", "qa", "prd", etc.).<br/><br/> /// /// The config file is located in the folder "Assets/AWS GameKit/Resources/" and is automatically included in builds of your game. /// It is automatically included because it resides in a folder with the special name "Resources". /// Learn more about Unity's special "Resources/" folder name at: https://docs.unity3d.com/Manual/SpecialFolders.html /// </remarks> public class SessionManager : Singleton<SessionManager> { private readonly SessionManagerWrapper _wrapper = SessionManagerWrapper.Get(); private class ConfigPath { public const string NAME_WITHOUT_EXTENSION = "awsGameKitClientConfig"; /// <summary> /// The filename of the client config file located in the special "Resources/" folder. /// </summary> public const string DESTINATION_NAME = NAME_WITHOUT_EXTENSION + ".yaml"; #if UNITY_EDITOR /// <summary> /// The filename of the client config files located in the environment specific "InstanceFiles/" folders. /// </summary> /// <remarks> /// The source and destination files have different extensions (.yml and .yaml respectively). /// The .yaml extension is required in order to load the file as a TextAsset with <c>Resources.Load()</c> (see https://docs.unity3d.com/Manual/class-TextAsset.html). /// The .yml extension is generated by the underlying AWS GameKit C++ Library. /// The file extension is changed when the file is copied to the destination location by <c>CopyAndReloadConfig()</c>. /// </remarks> private const string SOURCE_NAME = NAME_WITHOUT_EXTENSION + ".yml"; private string SourceRelativePathFromPackageFolder => Path.Combine("Editor", "CloudResources", "InstanceFiles", _gameAlias, _environmentCode, SOURCE_NAME); internal string SourceAbsolutePath => Path.Combine(GameKitPaths.Get().ASSETS_FULL_PATH, SourceRelativePathFromPackageFolder); internal string SourceAssetDatabasePath => Path.Combine(GameKitPaths.Get().ASSETS_RELATIVE_PATH, SourceRelativePathFromPackageFolder); internal string DestinationAssetDatabasePath => Path.Combine(GameKitPaths.Get().ASSETS_RESOURCES_RELATIVE_PATH, DESTINATION_NAME); private readonly string _gameAlias; private readonly string _environmentCode; public ConfigPath(string gameAlias, string environmentCode) { _gameAlias = gameAlias; _environmentCode = environmentCode; } #endif } /// <summary> /// Set a specified token's value. /// </summary> /// <param name="tokenType">The type of token to set.</param> /// <param name="value">The value of the token</param> public void SetToken(TokenType tokenType, string value) { _wrapper.SessionManagerSetToken(tokenType, value); } /// <summary> /// Check if settings are loaded for the passed in feature. /// </summary> /// <remarks> /// These settings are found in the config file, which is described in the class documentation. /// The file is loaded by calling either ReloadConfig() or CopyAndReloadConfig(). /// </remarks> /// <param name="featureType">The feature to check.</param> /// <returns>True if the feature's settings are loaded, false otherwise.</returns> public bool AreSettingsLoaded(FeatureType featureType) { return _wrapper.SessionManagerAreSettingsLoaded(featureType); } /// <summary> /// Reload the config file from the special "Resources/" folder. /// </summary> /// <remarks> /// The config file is described in the class documentation. /// </remarks> public void ReloadConfig() { Logging.LogInfo("SessionManagerWrapper::ReloadConfig()"); TextAsset configFile = Resources.Load<TextAsset>(ConfigPath.NAME_WITHOUT_EXTENSION); if (configFile == null) { if (!Application.isPlaying) { // Don't log anything during Edit Mode. // The config file won't exist until the user has submitted their AWS Credentials. return; } string howToFix = Application.isEditor ? "re-enter Play Mode" : "re-build the game"; Logging.LogError($"The {ConfigPath.DESTINATION_NAME} file is missing. AWS GameKit feature APIs will not work. " + $"Please make sure at least one AWS GameKit feature is deployed and then {howToFix}."); return; } _wrapper.SessionManagerReloadConfigContents(configFile.text); } /// <summary> /// Inject the CA certificate into the client config and load it. /// </summary> /// <remarks> /// Use this for Mobile devices that need a CA Cert for the CURL Http client. /// </remarks> internal void ReloadConfigMobile() { Logging.LogInfo("SessionManagerWrapper::ReloadConfigMobile()"); #if UNITY_ANDROID // Helper to build URI to asset inside a jar/apk Func<string, string> buildJarAssetPath = (string rawAsset) => { return $"jar:file://{Application.dataPath}!/assets/raw/{rawAsset}"; }; // Helper to read an asset from a jar/apk. This blocks so only use it to read small assets. Func<string, string> readTextFromJarAsset = (string fullPath) => { Logging.LogInfo($"Reading asset from jar {fullPath}"); UnityWebRequest request = UnityWebRequest.Get(fullPath); request.SendWebRequest(); while (!request.isDone) { // NO-OP } if (request.result != UnityWebRequest.Result.Success) { Logging.LogError($"Could not read asset {fullPath}, error {request.error}"); return string.Empty; } return request.downloadHandler.text; }; // Load client config text string clientConfigPath = buildJarAssetPath(ConfigPath.DESTINATION_NAME); string clientConfigContent = readTextFromJarAsset(clientConfigPath); // Load CA Certificate and save it to Persistent Data Path if it doesn't exist string caCertReadPath = buildJarAssetPath("cacert.pem"); string caCertWritePath = $"{Application.persistentDataPath}/cacert.pem"; // persistentDataPath ends in / if (!File.Exists(caCertWritePath)) { Logging.LogInfo($"Writing CA Certificate to file {caCertWritePath}"); string caCertContent = readTextFromJarAsset(caCertReadPath); File.WriteAllText(caCertWritePath, caCertContent); } else { Logging.LogInfo($"CA Certificate found at {caCertWritePath}"); } // Add CA Certificate to client config. We need this for HTTPS calls to the backend Logging.LogInfo("Updating Client config"); StringBuilder sb = new StringBuilder(clientConfigContent); sb.Append(System.Environment.NewLine); sb.Append($"ca_cert_file: {caCertWritePath}"); sb.Append(System.Environment.NewLine); Logging.LogInfo("Reloading Client config"); _wrapper.SessionManagerReloadConfigContents(sb.ToString()); #endif #if UNITY_IPHONE TextAsset configFile = Resources.Load<TextAsset>(ConfigPath.NAME_WITHOUT_EXTENSION); string sslPemDataPath = $"{Application.dataPath}/Security/Certs/cacert.pem"; StringBuilder sb = new StringBuilder(configFile.text); sb.Append(System.Environment.NewLine); sb.Append($"ca_cert_file: {sslPemDataPath}"); sb.Append(System.Environment.NewLine); _wrapper.SessionManagerReloadConfigContents(sb.ToString()); #endif } /// <summary> /// Releases all resources for the SessionManager. /// </summary> /// /// <remarks>Should only be called by the GameKitManager. Calling outside of the manager many cause runtime exceptions. </remarks> public virtual void Release() { _wrapper.ReleaseInstance(); } #if UNITY_EDITOR /// <summary> /// Copy the specific environment's config file to the special "Resources/" folder, then reload settings from this config file. /// </summary> /// <remarks> /// This method is only called in Editor Mode. It is called whenever a GameKit feature is created or redeployed, or when the environment changes (i.e. "dev", "qa", "prd", etc.).<br/><br/> /// /// The purpose of this method is to persist the current environment's config file to the special "Resources/" folder so it can be loaded by <c>ReloadConfig()</c>.<br/><br/> /// /// The config file and the special "Resources/" folder are described in the class documentation. /// </remarks> /// <param name="gameAlias">The game's alias, ex: "mygame".</param> /// <param name="environmentCode">The environment to copy the config from, ex: "dev".</param> public void CopyAndReloadConfig(string gameAlias, string environmentCode) { Debug.Log($"SessionManagerWrapper::CopyAndReloadConfig({nameof(gameAlias)}={gameAlias}, {nameof(environmentCode)}={environmentCode})"); ConfigPath configPath = new ConfigPath(gameAlias, environmentCode); if (!File.Exists(configPath.SourceAbsolutePath)) { Logging.LogError($"Source config file does not exist: {configPath.SourceAbsolutePath}"); return; } try { AssetDatabase.ImportAsset(configPath.SourceAssetDatabasePath, ImportAssetOptions.ForceSynchronousImport); AssetDatabase.CopyAsset(configPath.SourceAssetDatabasePath, configPath.DestinationAssetDatabasePath); Logging.LogInfo($"Copied config file from {configPath.SourceAssetDatabasePath} to {configPath.DestinationAssetDatabasePath}"); } catch (Exception e) { Logging.LogException("Error copying config", e); ClearSettings(); return; } ReloadConfig(); } /// <summary> /// Copy the specific environment's config file to the special Mobile package folder that gets deployed to a device. /// </summary> /// <param name="gameAlias">The game's alias, ex: "mygame".</param> /// <param name="environmentCode">The environment to copy the config from, ex: "dev".</param> internal void CopyConfigToMobileAssets(string gameAlias, string environmentCode) { Debug.Log($"SessionManagerWrapper::CopyConfigToMobileAssets({nameof(gameAlias)}={gameAlias}, {nameof(environmentCode)}={environmentCode})"); ConfigPath configPath = new ConfigPath(gameAlias, environmentCode); if (!File.Exists(configPath.SourceAbsolutePath)) { Logging.LogError($"Source config file does not exist: {configPath.SourceAbsolutePath}"); return; } #if UNITY_ANDROID try { string androidLibDirFullPath = Path.Combine(GameKitPaths.Get().ASSETS_FULL_PATH, "Plugins", "Android", "GameKitConfig.androidlib").Replace("\\", "/"); string androidLibRawAssetDirFullPath = Path.Combine(androidLibDirFullPath, "assets", "raw").Replace("\\", "/"); string androidLibDirRelativePath = Path.Combine(GameKitPaths.Get().ASSETS_RELATIVE_PATH, "Plugins", "Android", "GameKitConfig.androidlib").Replace("\\", "/"); string androidLibRawAssetDirRelativePath = Path.Combine(androidLibDirRelativePath, "assets", "raw").Replace("\\", "/"); string androidLibRawAssetConfigPath = Path.Combine(androidLibRawAssetDirRelativePath, ConfigPath.DESTINATION_NAME).Replace("\\", "/"); AssetDatabase.CopyAsset(configPath.DestinationAssetDatabasePath, androidLibRawAssetConfigPath); Logging.LogInfo($"Copied Android config file from {configPath.SourceAssetDatabasePath} to {androidLibRawAssetConfigPath}"); } catch (Exception e) { Logging.LogException("Error copying Mobile config", e); ClearSettings(); return; } #endif } /// <summary> /// Return true if a config file exists for the environment, false otherwise. /// </summary> /// <param name="gameAlias">The game's alias, ex: "mygame".</param> /// <param name="environmentCode">The environment to copy the config from, ex: "dev".</param> public bool DoesConfigFileExist(string gameAlias, string environmentCode) { ConfigPath configPath = new ConfigPath(gameAlias, environmentCode); return File.Exists(configPath.SourceAbsolutePath); } /// <summary> /// Clear out the currently loaded client config settings. /// </summary> private void ClearSettings() { _wrapper.SessionManagerReloadConfigFile(string.Empty); } #endif } }
326
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Utils; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Runtime.Core { public class SessionManagerWrapper : Singleton<SessionManagerWrapper> { // Select the correct source path based on the platform #if UNITY_IPHONE && !UNITY_EDITOR private const string IMPORT = "__Internal"; #else private const string IMPORT = "aws-gamekit-authentication"; #endif // Saved instance private IntPtr _instance = IntPtr.Zero; // DLL loading [DllImport(IMPORT)] private static extern IntPtr GameKitSessionManagerInstanceCreate(string clientConfigFilePath, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern void GameKitSessionManagerInstanceRelease(IntPtr sessionManagerInstance); [DllImport(IMPORT)] private static extern void GameKitSessionManagerSetToken(IntPtr sessionManagerInstance, TokenType tokenType, string value); [DllImport(IMPORT)] private static extern bool GameKitSessionManagerAreSettingsLoaded(IntPtr sessionManagerInstance, FeatureType featureType); [DllImport(IMPORT)] private static extern void GameKitSessionManagerReloadConfigFile(IntPtr sessionManagerInstance, string clientConfigFilePath); [DllImport(IMPORT)] private static extern void GameKitSessionManagerReloadConfigContents(IntPtr sessionManagerInstance, string clientConfigFileContents); /// <summary> /// Gets (and creates if necessary) a GameKitSessionManager instance, which can be used to access the SessionManager API. /// </summary> /// <remarks> /// Make sure to call ReleaseInstance() to destroy the returned object when finished with it. /// </remarks> /// <returns>Pointer to the new GameKitSessionManager instance.</returns> public IntPtr GetInstance() { if (_instance == IntPtr.Zero) { // Start without any config settings loaded. string clientConfigFilePath = string.Empty; _instance = SessionManagerInstanceCreate(clientConfigFilePath, Logging.LogCb); } return _instance; } /// <summary> /// Destroy the GameKitSessionManager instance. /// </summary> public void ReleaseInstance() { SessionManagerInstanceRelease(_instance); _instance = IntPtr.Zero; } public void SessionManagerSetToken(TokenType tokenType, string value) { DllLoader.TryDll(() => GameKitSessionManagerSetToken(GetInstance(), tokenType, value), nameof(GameKitSessionManagerSetToken)); } public bool SessionManagerAreSettingsLoaded(FeatureType featureType) { return DllLoader.TryDll(() => GameKitSessionManagerAreSettingsLoaded(GetInstance(), featureType), nameof(GameKitSessionManagerAreSettingsLoaded), false); } public void SessionManagerReloadConfigFile(string clientConfigFilePath) { DllLoader.TryDll(() => GameKitSessionManagerReloadConfigFile(GetInstance(), clientConfigFilePath), nameof(GameKitSessionManagerReloadConfigFile)); } public void SessionManagerReloadConfigContents(string clientConfigFileContents) { DllLoader.TryDll(() => GameKitSessionManagerReloadConfigContents(GetInstance(), clientConfigFileContents), nameof(GameKitSessionManagerReloadConfigContents)); } private IntPtr SessionManagerInstanceCreate(string clientConfigFilePath, FuncLoggingCallback logCb) { return DllLoader.TryDll(() => GameKitSessionManagerInstanceCreate(clientConfigFilePath, logCb), nameof(GameKitSessionManagerInstanceCreate), IntPtr.Zero); } private void SessionManagerInstanceRelease(IntPtr sessionManagerInstance) { DllLoader.TryDll(() => GameKitSessionManagerInstanceRelease(sessionManagerInstance), nameof(GameKitSessionManagerInstanceRelease)); } } }
96
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Runtime.Exceptions { public class GameKitInstanceNotFound : Exception { public GameKitInstanceNotFound(string message) : base(message) { } } }
17
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Runtime.Exceptions { public class GameKitRuntimeException : Exception { public GameKitRuntimeException(string message) : base(message) { } } }
16
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Runtime.Features.GameKitAchievements { /// <summary> /// Achievements feature. /// </summary> public class Achievements : GameKitFeatureBase<AchievementsWrapper>, IAchievementsProvider { public override FeatureType FeatureType => FeatureType.Achievements; /// <summary> /// Call to get an instance of the GameKit Achievements feature. /// </summary> /// <returns>An instance of the Achievements feature that can be used to call Achievement related methods.</returns> public static Achievements Get() { return GameKitFeature<Achievements>.Get(); } /// <summary> /// Lists non-hidden achievements, and will call delegates after every page.<br/><br/> /// /// Secret achievements will be included, and developers will be responsible for processing those as they see fit.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="listAchievementsDesc">Object containing call preferences</param> /// <param name="callback">Delegate that is called while the function is executing, once for each page of achievements</param> /// <param name="onCompleteCallback">Delegate that is called once the function has finished executing</param> public void ListAchievementsForPlayer(ListAchievementsDesc listAchievementsDesc, Action<AchievementListResult> callback, Action<uint> onCompleteCallback) { Call(Feature.ListAchievements, listAchievementsDesc, callback, onCompleteCallback); } /// <summary> /// Gets the specified achievement for currently logged in user, and passes it to ResultDelegate<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code.<br/> /// - GAMEKIT_ERROR_ACHIEVEMENTS_INVALID_ID: The Achievement ID given is empty or malformed. /// </summary> /// <param name="achievementId">Identifier of the achievement to return</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetAchievementForPlayer(string achievementId, Action<AchievementResult> callback) { Call(Feature.GetAchievement, achievementId, callback); } /// <summary> /// Increments the currently logged in user's progress on a specific achievement.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="updateAchievementDesc">Object containing the identifier of the achievement and how much to increment by</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void UpdateAchievementForPlayer(UpdateAchievementDesc updateAchievementDesc, Action<AchievementResult> callback) { Call(Feature.UpdateAchievement, updateAchievementDesc, callback); } /// <summary> /// Gets the AWS CloudFront url which all achievement icons for this game/environment can be accessed from.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetAchievementIconBaseUrl(Action<StringCallbackResult> callback) { Call(Feature.GetAchievementIconsBaseUrl, callback); } } }
96
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Third Party using Newtonsoft.Json; namespace AWS.GameKit.Runtime.Features.GameKitAchievements { public class ListAchievementsDesc { public uint PageSize; public bool WaitForAllPages; public override string ToString() => $"ListAchievementsDesc(PageSize={PageSize}, WaitForAllPages={WaitForAllPages})"; } public class UpdateAchievementDesc { public string AchievementId; public uint IncrementBy; public override string ToString() => $"UpdateAchievementDesc(AchievementId={AchievementId}, IncrementBy={IncrementBy})"; } [Serializable] public class Achievement { [JsonProperty("achievement_id")] public string AchievementId = string.Empty; [JsonProperty("title")] public string Title = string.Empty; [JsonProperty("locked_description")] public string LockedDescription = string.Empty; [JsonProperty("unlocked_description")] public string UnlockedDescription = string.Empty; [JsonProperty("locked_icon_url")] public string LockedIcon = string.Empty; [JsonProperty("unlocked_icon_url")] public string UnlockedIcon = string.Empty; [JsonProperty("current_value")] public int CurrentValue = 0; [JsonProperty("max_value")] public int RequiredAmount = 0; [JsonProperty("points")] public int Points = 0; [JsonProperty("order_number")] public int OrderNumber = 0; [JsonProperty("is_stateful")] public bool IsStateful => RequiredAmount > 1; [JsonProperty("is_secret")] public bool IsSecret = false; [JsonProperty("is_hidden")] public bool IsHidden = false; [JsonProperty("earned")] public bool IsEarned = false; [JsonProperty("newly_earned")] public bool IsNewlyEarned = false; [JsonProperty("earned_at")] public string EarnedAt = string.Empty; [JsonProperty("updated_at")] public string UpdatedAt = string.Empty; } [Serializable] public class AchievementResult { /// <summary> /// Will be <see cref="Core.GameKitErrors.GAMEKIT_SUCCESS"/> if the API call was successful, otherwise will be a specific value which indicates the kind of error that occurred. /// Consult the API's documentation to find which error codes are possible and their meaning. /// </summary> public uint ResultCode; /// <summary> /// The Achievement that was retrieved or acted upon. Will be a default <see cref="Achievement"/> object when the <see cref="ResultCode"/> is unsuccessful (i.e. not <see cref="Core.GameKitErrors.GAMEKIT_SUCCESS"/>). /// </summary> public Achievement Achievement; } [Serializable] public class AchievementListResult { [JsonProperty("achievements")] public Achievement[] Achievements; } }
105
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; // Third Party using Newtonsoft.Json; namespace AWS.GameKit.Runtime.Features.GameKitAchievements { /// <summary> /// Achievements wrapper for GameKit C++ SDK calls /// </summary> public class AchievementsWrapper : GameKitFeatureWrapperBase { // Select the correct source path based on the platform #if UNITY_IPHONE && !UNITY_EDITOR private const string IMPORT = "__Internal"; #else private const string IMPORT = "aws-gamekit-achievements"; #endif // DLL loading [DllImport(IMPORT)] private static extern IntPtr GameKitAchievementsInstanceCreateWithSessionManager(IntPtr sessionManager, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern void GameKitAchievementsInstanceRelease(IntPtr achievementsInstance); [DllImport(IMPORT)] private static extern uint GameKitListAchievements(IntPtr achievementsInstance, uint pageSize, bool waitForAllPages, IntPtr dispatchReceiver, FuncStringCallback responseCallback); [DllImport(IMPORT)] private static extern uint GameKitUpdateAchievement(IntPtr achievementsInstance, string achievementId, uint incrementBy, IntPtr dispatchReceiver, FuncStringCallback responseCallback); [DllImport(IMPORT)] private static extern uint GameKitGetAchievement(IntPtr achievementsInstance, string achievementId, IntPtr dispatchReceiver, FuncStringCallback responseCallback); [DllImport(IMPORT)] private static extern uint GameKitGetAchievementIconsBaseUrl(IntPtr achievementsInstance, IntPtr dispatchReceiver, FuncStringCallback responseCallback); [AOT.MonoPInvokeCallback(typeof(FuncStringCallback))] public static void AchievementListFromRecurringStringCallback(IntPtr dispatchReceiver, string responseValue) { // parse the string response AchievementListResult result = JsonConvert.DeserializeObject<JsonResponse<AchievementListResult>>(responseValue).data; // get a handle to the result callback from the dispatch receiver Action<AchievementListResult> resultCallback = Marshaller.GetDispatchObject<Action<AchievementListResult>>(dispatchReceiver); // call the callback and pass it the result resultCallback(result); } public uint ListAchievements(ListAchievementsDesc listAchievementsDesc, Action<AchievementListResult> resultCallback) { return DllLoader.TryDll(resultCallback, (IntPtr dispatchReceiver) => GameKitListAchievements( GetInstance(), listAchievementsDesc.PageSize, listAchievementsDesc.WaitForAllPages, dispatchReceiver, AchievementListFromRecurringStringCallback), nameof(GameKitListAchievements), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public AchievementResult UpdateAchievement(UpdateAchievementDesc updateAchievementDesc) { StringCallbackResult result = new StringCallbackResult(); uint status = DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitUpdateAchievement( GetInstance(), updateAchievementDesc.AchievementId, updateAchievementDesc.IncrementBy, dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitUpdateAchievement), GameKitErrors.GAMEKIT_ERROR_GENERAL); return GetAchievementResult(result, status); } public AchievementResult GetAchievement(string achievementId) { StringCallbackResult result = new StringCallbackResult(); uint status = DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitGetAchievement(GetInstance(), achievementId, dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitGetAchievement), GameKitErrors.GAMEKIT_ERROR_GENERAL); return GetAchievementResult(result, status); } public StringCallbackResult GetAchievementIconsBaseUrl() { StringCallbackResult result = new StringCallbackResult(); uint status = DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitGetAchievementIconsBaseUrl(GetInstance(), dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitGetAchievementIconsBaseUrl), GameKitErrors.GAMEKIT_ERROR_GENERAL); result.ResultCode = status; return result; } protected override IntPtr Create(IntPtr sessionManager, FuncLoggingCallback logCb) { return DllLoader.TryDll(() => GameKitAchievementsInstanceCreateWithSessionManager(sessionManager, logCb), nameof(GameKitAchievementsInstanceCreateWithSessionManager), IntPtr.Zero); } protected override void Release(IntPtr instance) { DllLoader.TryDll(() => GameKitAchievementsInstanceRelease(instance), nameof(GameKitAchievementsInstanceRelease)); } private AchievementResult GetAchievementResult(StringCallbackResult stringCallbackResult, uint status) { Achievement achievement = status == GameKitErrors.GAMEKIT_SUCCESS ? JsonConvert.DeserializeObject<JsonResponse<Achievement>>(stringCallbackResult.ResponseValue).data : new Achievement(); return new AchievementResult { Achievement = achievement, ResultCode = status }; } } }
120
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Runtime.Features.GameKitAchievements { /// <summary> /// Interface for the AWS GameKit Achievements feature. /// </summary> public interface IAchievementsProvider { /// <summary> /// Lists non-hidden achievements, and will call delegates after every page.<br/><br/> /// /// Secret achievements will be included, and developers will be responsible for processing those as they see fit.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="listAchievementsDesc">Object containing call preferences</param> /// <param name="callback">Delegate that is called while the function is executing, once for each page of achievements</param> /// <param name="onCompleteCallback">Delegate that is called once the function has finished executing</param> public void ListAchievementsForPlayer(ListAchievementsDesc listAchievementsDesc, Action<AchievementListResult> callback, Action<uint> onCompleteCallback); /// <summary> /// Gets the specified achievement for currently logged in user, and passes it to ResultDelegate<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code.<br/> /// - GAMEKIT_ERROR_ACHIEVEMENTS_INVALID_ID: The Achievement ID given is empty or malformed. /// </summary> /// <param name="achievementId">Identifier of the achievement to return</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetAchievementForPlayer(string achievementId, Action<AchievementResult> callback); /// <summary> /// Increments the currently logged in user's progress on a specific achievement.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="updateAchievementDesc">Object containing the identifier of the achievement and how much to increment by</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void UpdateAchievementForPlayer(UpdateAchievementDesc updateAchievementDesc, Action<AchievementResult> callback); /// <summary> /// Gets the AWS CloudFront url which all achievement icons for this game/environment can be accessed from.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetAchievementIconBaseUrl(Action<StringCallbackResult> callback); } }
70
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Gamekit using AWS.GameKit.Common; using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.FeatureUtils { /// <summary> /// Wrapper around a singleton for defining a GameKitFeature, for use when calling GameKit features within code /// </summary> public abstract class GameKitFeature<T> : Singleton<T> where T : GameKitFeatureBase, new() { } /// <summary> /// Parent class required by all GameKit features /// </summary> public abstract class GameKitFeatureBase { // declare the state of this instance of the feature public bool IsReady => _isReady; public abstract FeatureType FeatureType { get; } protected Threader _threader = new Threader(); private bool _isReady = false; /// <summary> /// Called by the GameKitManager to initialize any requirements of this feature. Called when the <see cref="GameKitManager.EnsureFeaturesAreInitialized"/> is called. /// </summary> public virtual void OnInitialize() { // initialize the threader _threader.Awake(); InitializeFeature(); // declare the state of the singleton as ready _isReady = true; } /// <summary> /// Called by the GameKitManager to clean up the feature. Called when the <see cref="GameKitManager.Dispose"/> is called. /// </summary> public virtual void OnDispose() { // Wait for Threader's pending tasks _threader.WaitForThreadedWork(); // declare the state of the singleton as not ready _isReady = false; // handle any per case requirements before release the feature DestroyFeature(); // release the feature GetFeatureWrapperBase().Release(); } /// <summary> /// Called by the GameKitManager to notify features the game has been paused. Called when <see cref="GameKitManager.OnApplicationPause"/> is called. /// </summary> /// <param name="isPaused">True if the application is paused, else False.</param> public virtual void OnApplicationPause(bool isPaused) { if (_isReady) { NotifyPause(isPaused); } } /// <summary> /// Called by the GameKitManager to notify features the game has been quit. Called when <see cref="GameKitManager.OnApplicationQuit"/> is called. /// </summary> public virtual void OnApplicationQuit() { if (_isReady) { NotifyApplicationQuit(); } } /// <summary> /// Called by the GameKitManager to update any requirements of the feature. Called when <see cref="GameKitManager.Update"/> is called. /// </summary> public virtual void Update() { if (_isReady) { // call any feature specific updates UpdateFeature(); // call all queued callbacks _threader.Update(); } } /// <summary> /// For use within a GameKitFeature for calling a feature's API and wrapping inside of a threader call. Also validates if this feature has been initialized. /// </summary> /// <param name="function">GameKit feature API to wrap inside of the thread</param> /// <param name="callback">Action to call once the thread has completed</param> protected void Call(Action function, Action callback) { if (_isReady) { _threader.Call(function, callback); } else { LogCallNotInitialized(); } } /// <summary> /// For use within a GameKitFeature for calling a feature's API and wrapping inside of a threader call. Also validates if this feature has been initialized. /// </summary> /// <param name="function">GameKit feature API to wrap inside of the thread</param> /// <param name="callback">Action to call once the thread has completed</param> protected void Call<RESULT>(Func<RESULT> function, Action<RESULT> callback) { if (_isReady) { _threader.Call(function, callback); } else { LogCallNotInitialized(); } } /// <summary> /// For use within a GameKitFeature for calling a feature's API and wrapping inside of a threader call. Also validates if this feature has been initialized. /// </summary> /// <param name="function">GameKit feature API to wrap inside of the thread</param> /// <param name="description">DESCRIPTION object required to call the API</param> /// <param name="callback">Action to call once the thread has completed</param> protected void Call<DESCRIPTION, RESULT>(Func<DESCRIPTION, RESULT> function, DESCRIPTION description, Action<RESULT> callback) { if (_isReady) { _threader.Call(function, description, callback); } else { LogCallNotInitialized(); } } /// <summary> /// For use within a GameKitFeature for calling a feature's API and wrapping inside of a threader call. Also validates if this feature has been initialized. /// </summary> /// <param name="function">GameKit feature API to wrap inside of the thread</param> /// <param name="description">DESCRIPTION object required to call the API</param> /// <param name="callback">Action to call whenever the function needs to return information to the caller</param> /// <param name="onCompleteCallback">Action to call on the completion of this method</param> protected void Call<DESCRIPTION, RESULT, RETURN_RESULT>( Func<DESCRIPTION, Action<RESULT>, RETURN_RESULT> function, DESCRIPTION description, Action<RESULT> callback, Action<RETURN_RESULT> onCompleteCallback) { if (_isReady) { _threader.Call(function, description, callback, onCompleteCallback); } else { LogCallNotInitialized(); } } /// <summary> /// For use within a GameKitFeature for calling a feature's API and wrapping inside of a threader call. Also validates if this feature has been initialized. /// </summary> /// <param name="function">GameKit feature API to wrap inside of the thread</param> /// <param name="description">DESCRIPTION object required to call the API</param> /// <param name="callback">Action to call once the thread has completed</param> protected void Call<DESCRIPTION>(Action<DESCRIPTION> function, DESCRIPTION description, Action callback) { if (_isReady) { _threader.Call(function, description, callback); } else { LogCallNotInitialized(); } } /// <summary> /// InitializeFeature is called during the Awake state and is an optional call for the child feature. /// /// This method does nothing by default. It is not necessary to call `base.InitializeFeature()` when overriding this method. /// </summary> protected virtual void InitializeFeature() { // default empty InitializeFeature() call } /// <summary> /// NotifyPause is called whenever the application is paused or unpaused. This can be useful on platforms such as iOS where the application is /// suspended before being paused and shutdown code can be unreliable. /// /// This method does nothing by default. It is not necessary to call `base.NotifyPause()` when overriding this method. /// <param name="isPaused"></param> /// </summary> protected virtual void NotifyPause(bool isPaused) { // default empty NotifyPause() call } /// <summary> /// NotifyApplicationQuit is called whenever the application is quit. NotifyApplicationQuit is called in both Editor and Standalone unlike /// DestroyFeature which is only called when running on a standalone build. /// /// This method does nothing by default. It is not necessary to call `base.NotifyPause()` when overriding this method. /// </summary> protected virtual void NotifyApplicationQuit() { // default empty NotifyApplicationQuit() call } /// <summary> /// UpdateFeature is called during the Update state and is an optional call for the child feature. /// /// This method does nothing by default. It is not necessary to call `base.UpdateFeature()` when overriding this method. /// </summary> protected virtual void UpdateFeature() { // default empty UpdateFeature() call } /// <summary> /// DestroyFeature is called during the OnDestroy state and is an optional call for the child feature. Note DestroyFeature is not called from the Editor. /// Use NotifyApplicationQuit() for cleanup that should be done for both Editor and Standalone. /// /// This method does nothing by default. It is not necessary to call `base.DestroyFeature()` when overriding this method. /// </summary> protected virtual void DestroyFeature() { // default empty DestroyFeature() call } protected abstract GameKitFeatureWrapperBase GetFeatureWrapperBase(); /// <summary> /// Helper method for generating a formatted error log when the related child feature is not initialized /// </summary> private void LogCallNotInitialized() { string featureMethod = new System.Diagnostics.StackTrace().GetFrame(2).GetMethod().Name; string featureClass = new System.Diagnostics.StackTrace().GetFrame(2).GetMethod().DeclaringType.FullName; string callingMethod = new System.Diagnostics.StackTrace().GetFrame(3).GetMethod().Name; string callingClass = new System.Diagnostics.StackTrace().GetFrame(3).GetMethod().DeclaringType.FullName; Logging.LogError( $"The {featureMethod} method of the {featureClass} feature, called in the {callingMethod} method of {callingClass} class" + $", has not been initialized yet. Please make sure {typeof(GameKitManager).FullName} is attached as a component and enabled."); } } /// <summary> /// Abstraction layer around the assignment of the feature wrapper /// </summary> public abstract class GameKitFeatureBase<T> : GameKitFeatureBase where T : GameKitFeatureWrapperBase, new() { public T Feature => _feature; private T _feature = new T(); protected override GameKitFeatureWrapperBase GetFeatureWrapperBase() => _feature; } }
279
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.FeatureUtils { public abstract class GameKitFeatureWrapperBase { // Saved instance private IntPtr _instance = IntPtr.Zero; private readonly object _instanceCreationLock = new object(); public virtual void Release() { if (_instance != IntPtr.Zero) { Release(_instance); _instance = IntPtr.Zero; } } protected abstract IntPtr Create(IntPtr sessionManager, FuncLoggingCallback logCb); protected abstract void Release(IntPtr instance); // used to lazy instantiate the feature, and prevents its instantiation if the feature is not used protected IntPtr GetInstance() { if (_instance != IntPtr.Zero) { return _instance; } lock (_instanceCreationLock) { // If a call was waiting on this lock, this null check will be safeguard in case the pointer has already been created. if (_instance == IntPtr.Zero) { _instance = Create(SessionManagerWrapper.Get().GetInstance(), Logging.LogCb); } } return _instance; } } }
54
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEngine; // Standard Library using System; using System.IO; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.Features.GameKitGameSaving { /// <summary> /// Describes default file actions to be called by the GameKit SDK /// </summary> public class DefaultFileActions { /// <summary> /// Create a FileActions struct. /// </summary> /// <returns>The created FileActions struct.</returns> public static FileActions Make() { FileActions actions; actions.FileWriteCallback = WriteCallback; actions.FileReadCallback = ReadCallback; actions.FileSizeCallback = GetFileSizeCallback; actions.FileWriteDispatchReceiver = IntPtr.Zero; actions.FileReadDispatchReceiver = IntPtr.Zero; actions.FileSizeDispatchReceiver = IntPtr.Zero; return actions; } private static bool WriteDesktopFile(string filePath, byte[] data) { try { // Ensure the parent directory exists - if not, create it now FileInfo fileInfo = new FileInfo(filePath); if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } File.WriteAllBytes(filePath, data); } catch (Exception exception) { Logging.LogException($"Failed to write data to {filePath}", exception); return false; } return true; } private static bool ReadDesktopFile(string filePath, IntPtr data, uint size) { try { byte[] byteData = File.ReadAllBytes(filePath); Marshal.Copy(byteData, 0, data, (int) size); } catch (Exception exception) { Logging.LogException($"Failed to read data from {filePath}", exception); return false; } return true; } private static uint GetDesktopFileSize(string filePath) { try { FileInfo fileInfo = new FileInfo(filePath); return (uint)fileInfo.Length; } catch (Exception exception) { Logging.LogException($"Failed to determine file size of {filePath}", exception); return 0; } } [AOT.MonoPInvokeCallback(typeof(FuncFileWriteCallback))] private static bool WriteCallback(IntPtr dispatchReceiver, string filePath, byte[] data, uint size) { return WriteDesktopFile(filePath, data); } [AOT.MonoPInvokeCallback(typeof(FuncFileReadCallback))] private static bool ReadCallback(IntPtr dispatchReceiver, string filePath, IntPtr data, uint size) { return ReadDesktopFile(filePath, data, size); } [AOT.MonoPInvokeCallback(typeof(FuncFileGetSizeCallback))] private static uint GetFileSizeCallback(IntPtr dispatchReceiver, string filePath) { return GetDesktopFileSize(filePath); } } }
107
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Runtime.Features.GameKitGameSaving { /// <summary> /// Describes the default Game Saving model to be used by the GameKit SDK /// </summary> public class DefaultGameSavingModel { /// <summary> /// Create a GameSavingModel struct. /// </summary> /// <returns>The created GameSavingModel struct.</returns> public static GameSavingModel Make() { GameSavingModel model = new GameSavingModel(); model.SlotName = string.Empty; model.Metadata = string.Empty; model.EpochTime = 0; model.OverrideSync = false; model.Data = IntPtr.Zero; model.DataSize = 0; model.UrlTimeToLive = GameSavingConstants.S3_PRE_SIGNED_URL_DEFAULT_TIME_TO_LIVE_SECONDS; model.ConsistentRead = true; return model; } } }
33
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.FeatureUtils; namespace AWS.GameKit.Runtime.Features.GameKitGameSaving { /// <summary> /// This class provides APIs for storing game save files in the cloud and synchronizing them with local devices. /// </summary> /// <remarks> /// /// [Initialization] /// <para> /// The SetFileActions() can be called at the start of your program to provide custom file I/O to the Game Saving singleton. This is an optional call and can also be called more than once, however /// it is recommended to only call one time at the start of your program if needed. /// /// Each time a user logs in, GameKitClearSyncedSlots(), GameKitAddLocalSlots(), and GameKitGetAllSlotSyncStatuses() must be called in that order to ensure all local and cloud slots are up to date. /// The GameKitClearSyncedSlots() can optionally be called after a user logs out instead of being called before GameKitAddLocalSlots(). /// <list type="bullet"> /// <item>SetFileActions() is optional. It lets you provide custom file I/O in case the default I/O functions provided by Unity don't support your target platform(s). </item> /// <item>ClearSyncedSlots() can be called during the initialization step, before AddLocalSlots() is called. Alternatively it can be called after a user logs out to ensure no cached slots remain.</item> /// <item>AddLocalSlots() ensures Game Saving knows about local saves on the device that exist from previous times the game was played. </item> /// <item>GetAllSlotSyncStatuses() ensures Game Saving has the latest information about the cloud saves, knows which local saves are synchronized /// with the cloud, and which saves should be uploaded, downloaded, or need manual conflict resolution. </item> /// </list> /// </para> /// /// [Offline Mode] /// <para> /// If your game is being played without internet, you must still call SaveSlot() and DeleteSlot() each time you would normally call these methods. /// Otherwise, there is a risk that the progress made while playing offline will be overwritten the next time the game is played on this device with /// an internet connection if a newer save has since been uploaded from another device. /// </para> /// /// [Save Slots] /// <para> /// Save files that are uploaded/downloaded/tracked through this API are each associated with a named "save slot" for the player. /// /// When you deploy the Game Saving feature, you can configure the maximum number of cloud saves slots to provide each player. This limit can /// prevent malicious players from storing too much data in the cloud. You can change this limit by doing another deployment through the Plugin UI. /// </para> /// /// [Slot Information] /// <para> /// The local and cloud attributes for a save slot are collectively known as "slot information" and are stored in the Slot class. /// </para> /// /// [Cached Slots] /// <para> /// This library maintains a cache of slot information for all slots it interacts with (both locally and in the cloud). /// The cached slots are updated on every API call, and are also returned in the delegate of most API calls. /// </para> /// /// [SaveInfo.json Files] /// <para> /// This library creates "SaveInfo.json" files on the device every time save files are uploaded/downloaded through the SaveSlot() and LoadSlot() APIs. /// /// The exact filenames and locations are provided by you. We highly recommended you store the SaveInfo.json files alongside their corresponding /// save file to help developers and curious players to understand these files go together. /// /// The SaveInfo.json files are loaded during game startup by calling AddLocalSlots(). This informs the library about any save files that exist on the /// device from previous game sessions. /// </para> /// </remarks> public class GameSaving : GameKitFeatureBase<GameSavingWrapper>, IGameSavingProvider { public override FeatureType FeatureType => FeatureType.GameStateCloudSaving; /// <summary> /// Call to get an instance of the GameKit GameSaving feature. /// </summary> /// <returns>An instance of the GameSaving feature that can be used to call GameSaving related methods.</returns> public static GameSaving Get() { return GameKitFeature<GameSaving>.Get(); } /// <summary> /// Asynchronously load slot information for all of the player's local saves on the device.<br/><br/> /// /// This should be the first method you call on the Game Saving library (except optionally SetFileActions() and ClearSyncedSlots()) and /// you should call it exactly once per user that is logged in. Afterwards, you should call GetAllSlotSyncStatuses(). /// See the class level documentation for more details on initialization.<br/><br/> /// /// This method loads the SaveInfo.json files that were created on the device during previous game sessions when calling SaveSlot() and LoadSlot(). /// This overwrites any cached slots in memory which have the same slot name as the slots loaded from the SaveInfo.json files. /// </summary> /// <param name="addSlotsDesc">Object containing a list of files to load when the game starts. /// Each file should contain the slot information for the locally saved slot and should be the file generated automatically by the SaveSlot()/LoadSlot() methods.</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void AddLocalSlots(AddLocalSlotsDesc addSlotsDesc, Action callback) { Call(Feature.AddLocalSlots, addSlotsDesc, callback); } /// <summary> /// This method will immediately clear the slots that are cached in the GameKit backend. /// /// ClearSyncedSlots() should be called immediately after a user logs out or immediately before AddLocalSlots() is called. This /// will ensure that any slots that were synced for a previous user are cleared out. /// </summary> public void ClearSyncedSlots() { Feature.ClearSyncedSlots(); } /// <summary> /// Asynchronously change the file I/O callbacks used by this library.<br/><br/> /// /// If you call this method, it should be the first method called on the library(even before AddLocalSlots()).<br/><br/> /// /// By default, this library uses the DefaultFileActions documented in AwsGameKitGameSavingWrapper.h /// These use Unity-provided file I/O methods and may not work on all platforms. /// Call this method to provide your own file I/O methods which support the necessary platform(s). /// </summary> /// <param name="fileActions">Object containing delegates for file IO</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void SetFileActions(FileActions fileActions, Action callback) { Call(Feature.SetFileActions, fileActions, callback); } /// <summary> /// Asynchronously get a complete and updated view of the player's save slots (both local and cloud).<br/><br/> /// /// Call this method during initialization (see class level documentation) and any time you suspect the cloud saves may have /// been updated from another device.<br/><br/> /// /// This method adds cached slots for all cloud saves not currently on the device, updates all cached slots with accurate cloud attributes, /// and marks the SlotSyncStatus member of all cached slots with the recommended syncing action you should take.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen.If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="callback">Delegate called once this method completes. It contains information about each cloud save slot and known local slot. /// Additionally it contains the result status code for the call.</param> public void GetAllSlotSyncStatuses(Action<SlotListResult> callback) { Call(Feature.GetAllSlotSyncStatuses, callback); } /// <summary> /// Asynchronously get an updated view and recommended syncing action for the player's specific save slot.<br/><br/> /// /// This method updates the specific save slot's cloud attributes and marks the SlotSyncStatus member with the recommended syncing action you should take.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME: The provided slot name is malformed.Check the logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND: The provided slot name was not found in the cached slots.This either means you have a typo in the slot name, /// or the slot only exists in the cloud and you need to call GetAllSlotSyncStatuses() first before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="slotName">String identifier for the save slot</param> /// <param name="callback">Delegate called once this method completes. It contains information about the slot in question. Additionally it contains the result status code for the call.</param> public void GetSlotSyncStatus(string slotName, Action<SlotActionResult> callback) { Call(Feature.GetSlotSyncStatus, slotName, callback); } /// <summary> /// Asynchronously delete the player's cloud save slot and remove it from the cached slots.<br/><br/> /// /// No local files are deleted from the device. Data is only deleted from the cloud and from memory(the cached slot).<br/><br/> /// /// After calling DeleteSlot(), you'll probably want to delete the local save file and corresponding SaveInfo.json file from the device. /// If you keep the SaveInfo.json file, then next time the game boots up this library will recommend re-uploading the save file to the cloud when /// you call GetAllSlotSyncStatuses() or GetSlotSyncStatus().<br/><br/> /// /// If your game is being played without internet, you must still call this method and delete the SaveInfo.json file as normal to avoid the risk /// of having the offline progress be overwritten when internet connectivity is restored.See the "Offline Mode" section in the file level documentation for more details.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME: The provided slot name is malformed.Check the logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND: The provided slot name was not found in the cached slots.This either means you have a typo in the slot name, /// or the slot only exists in the cloud and you need to call GetAllSlotSyncStatuses() first before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="slotName">String identifier for the save slot</param> /// <param name="callback">Delegate called once this method completes. It contains information about the slot that was deleted. Additionally it contains the result status code for the call.</param> public void DeleteSlot(string slotName, Action<SlotActionResult> callback) { Call(Feature.DeleteSlot, slotName, callback); } /// <summary> /// Asynchronously upload a data buffer to the cloud, overwriting the player's cloud slot if it already exists.<br/><br/> /// /// Also write the slot's information to a SaveInfo.json file on the device, and add the slot to the cached slots if it doesn't already exist. /// This SaveInfo.json file should be passed into AddLocalSlots() when you initialize the Game Saving library in the future.<br/><br/> /// /// If your game is being played without internet, you must still call this method as normal to avoid the risk of having the offline progress be /// overwritten when internet connectivity is restored.See the "Offline Mode" section in the file level documentation for more details.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method. <br/> /// - GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME: The provided slot name is malformed.Check the logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_FILE_WRITE_FAILED: The SaveInfo.json file was unable to be written to the device.If using the default file I/O callbacks, /// check the logs to see the root cause.If the platform is not supported by the default file I/O callbacks, /// use SetFileActions() to provide your own callbacks.See SetFileActions() for more details.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MAX_CLOUD_SLOTS_EXCEEDED: The upload was cancelled because it would have caused the player to exceed their "maximum cloud save slots limit". This limit /// was configured when you deployed the Game Saving feature and can be changed by doing another deployment through the Plugin UI.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_EXCEEDED_MAX_SIZE: The Metadata member of your Request object is too large. Please see the documentation on FGameSavingSaveSlotRequest::Metadata for details.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT: The upload was cancelled to prevent overwriting the player's progress. This most likely indicates the player has played on multiple /// devices without having their progress properly synced with the cloud at the start and end of their play sessions.We recommend you inform /// the player of this conflict and present them with a choice - keep the cloud save or keep the local save.Then call SaveSlot() or LoadSlot() /// with OverrideSync= true to override the cloud/local file.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_CLOUD_SLOT_IS_NEWER: The upload was cancelled because the cloud save file is newer than the file you attempted to upload. Treat this like a /// GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT because the local and cloud save might have non-overlapping game progress.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="saveSlotDesc">Object containing the required information about the slot that needs to be saved(uploaded) to cloud storage</param> /// <param name="callback">Delegate called once this method completes. It contains information about the newly saved slot. Additionally it contains the result status code for the call.</param> public void SaveSlot(SaveSlotDesc saveSlotDesc, Action<SlotActionResult> callback) { Call(Feature.SaveSlot, saveSlotDesc, callback); } /// <summary> /// Asynchronously download the player's cloud slot into a local data buffer. /// /// Also write the slot's information to a SaveInfo.json file on the device. /// This SaveInfo.json file should be passed into AddLocalSlots() when you initialize the Game Saving library in the future.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME: The provided slot name is malformed.Check the logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND: The provided slot name was not found in the cached slots.This either means you have a typo in the slot name, /// or the slot only exists in the cloud and you need to call GetAllSlotSyncStatuses() first before calling this method.<br/> /// - GAMEKIT_ERROR_FILE_WRITE_FAILED: The SaveInfo.json file was unable to be written to the device. If using the default file I/O callbacks, /// check the logs to see the root cause.If the platform is not supported by the default file I/O callbacks, /// use SetFileActions() to provide your own callbacks.See SetFileActions() for more details.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT: The download was cancelled to prevent overwriting the player's progress. This most likely indicates the player has played on multiple /// devices without having their progress properly synced with the cloud at the start and end of their play sessions.We recommend you inform /// the player of this conflict and present them with a choice - keep the cloud save or keep the local save.Then call SaveSlot() or LoadSlot() /// with OverrideSync= true to override the cloud/local file.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_LOCAL_SLOT_IS_NEWER: The download was cancelled because the local save file is newer than the cloud file you attempted to download.Treat this like a /// GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT because the local and cloud save might have non-overlapping game progress.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_UNKNOWN_SYNC_STATUS: The download was cancelled because the sync status could not be determined. Treat this like a GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MISSING_SHA: The S3 file is missing a SHA-256 metadata attribute and therefore the validity of the file could not be determined.This should not happen. If it does, /// this indicates there is a bug in the backend code.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_TAMPERED: The SHA-256 hash of the downloaded file does not match the SHA-256 hash of the original file that was uploaded to S3. This indicates the downloaded /// file was corrupted or tampered with. You should try downloading again to rule out the possibility of random corruption.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_BUFFER_TOO_SMALL: The data buffer you provided in the Request object is not large enough to hold the downloaded S3 file.This likely means a newer version of the /// cloud file was uploaded from another device since the last time you called GetAllSlotSyncStatuses() or GetSlotSyncStatus() on this device.To resolve, /// call GetSlotSyncStatus() to get the up-to-date size of the cloud file.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="loadSlotDesc">Object containing the required information about the slot that needs to be loaded(downloaded) from cloud storage</param> /// <param name="callback">Delegate called once this method completes. It contains information about the slot loaded and a buffer to the data downloaded from cloud storage for the slot. /// Additionally it contains the result status code for the call.</param> public void LoadSlot(LoadSlotDesc loadSlotDesc, Action<SlotDataResult> callback) { Call(Feature.LoadSlot, loadSlotDesc, callback); } } }
276
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; namespace AWS.GameKit.Runtime.Features.GameKitGameSaving { public static class GameSavingConstants { public const uint S3_PRE_SIGNED_URL_DEFAULT_TIME_TO_LIVE_SECONDS = 120; public const uint GET_ALL_SLOT_SYNC_STATUSES_DEFAULT_PAGE_SIZE = 0; public const string SAVE_INFO_FILE_EXTENSION = ".SaveInfo.json"; } public enum SlotSyncStatus : uint { UNKNOWN = 0, SYNCED = 1, SHOULD_DOWNLOAD_CLOUD = 2, SHOULD_UPLOAD_LOCAL = 3, IN_CONFLICT = 4 } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncGameSavingResponseCallback(IntPtr dispatchReceiver, IntPtr cachedSlots, uint slotCount, bool complete, uint callStatus); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncGameSavingSlotActionResponseCallback(IntPtr dispatchReceiver, IntPtr cachedSlots, uint slotCount, IntPtr activeSlot, uint callStatus); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncGameSavingDataResponseCallback(IntPtr dispatchReceiver, IntPtr cachedSlots, uint slotCount, IntPtr slot, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] data, uint dataSize, uint callStatus); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate bool FuncFileWriteCallback(IntPtr dispatchReceiver, string filePath, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] data, uint size); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate bool FuncFileReadCallback(IntPtr dispatchReceiver, string filePath, IntPtr data, uint size); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate uint FuncFileGetSizeCallback(IntPtr dispatchReceiver, string filePath); [StructLayout(LayoutKind.Sequential)] public struct FileActions { public FuncFileWriteCallback FileWriteCallback; public FuncFileReadCallback FileReadCallback; public FuncFileGetSizeCallback FileSizeCallback; public IntPtr FileWriteDispatchReceiver; public IntPtr FileReadDispatchReceiver; public IntPtr FileSizeDispatchReceiver; } [StructLayout(LayoutKind.Sequential)] public struct GameSavingModel { public string SlotName; public string Metadata; public long EpochTime; [MarshalAs(UnmanagedType.U1)] public bool OverrideSync; public IntPtr Data; public uint DataSize; public string LocalSlotInformationFilePath; public uint UrlTimeToLive; [MarshalAs(UnmanagedType.U1)] public bool ConsistentRead; } [Serializable] [StructLayout(LayoutKind.Sequential)] public class Slot { public string SlotName; public string MetadataLocal = string.Empty; public string MetadataCloud = string.Empty; public long SizeLocal = 0; public long SizeCloud = 0; public long LastModifiedLocal = 0; public long LastModifiedCloud = 0; public long LastSync = 0; public byte SlotSyncStatus = (byte)GameKitGameSaving.SlotSyncStatus.UNKNOWN; } public class SlotListResult { public uint ResultCode; public Slot[] CachedSlots = new Slot[0]; } public class SlotActionResult { public uint ResultCode; public Slot[] CachedSlots = new Slot[0]; public Slot ActionedSlot; } public class SlotDataResult { public uint ResultCode; public Slot[] CachedSlots = new Slot[0]; public Slot ActionedSlot; public byte[] Data = new byte[0]; public uint DataSize = 0; } public class AddLocalSlotsDesc { public string[] LocalSlotInformationFilePaths = new string[0]; public override string ToString() => $"AddLocalSlotDesc(LocalSlotInformationFilePaths=[{string.Join(",", LocalSlotInformationFilePaths)}])"; } public class SaveSlotDesc { public string SlotName; public string SaveInfoFilePath; public byte[] Data = new byte[0]; public string Metadata; public long EpochTime = 0; public bool OverrideSync = false; public override string ToString() => $"SaveSlotDesc(SlotName={SlotName}, SaveInfoFilePath={SaveInfoFilePath}, Data=<{Data.Length} bytes>, Metadata={Metadata}, EpochTime={EpochTime}, OverrideSync={OverrideSync})"; } public class LoadSlotDesc { public string SlotName; public string SaveInfoFilePath; public byte[] Data = new byte[0]; public bool OverrideSync = false; public override string ToString() => $"LoadSlotDesc(SlotName={SlotName}, SaveInfoFilePath={SaveInfoFilePath}, Data=<{Data.Length} bytes>, OverrideSync={OverrideSync})"; } }
140
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.Features.GameKitGameSaving { /// <summary> /// Game Saving wrapper for GameKit C++ SDK calls /// </summary> public class GameSavingWrapper : GameKitFeatureWrapperBase { // Select the correct source path based on the platform #if UNITY_IPHONE && !UNITY_EDITOR private const string IMPORT = "__Internal"; #else private const string IMPORT = "aws-gamekit-game-saving"; #endif // DLL loading [DllImport(IMPORT)] private static extern IntPtr GameKitGameSavingInstanceCreateWithSessionManager(IntPtr sessionManager, FuncLoggingCallback logCb, string[] localSlotInformationFilePaths, uint arraySize, FileActions fileActions); [DllImport(IMPORT)] private static extern void GameKitGameSavingInstanceRelease(IntPtr gameSavingInstance); [DllImport(IMPORT)] private static extern void GameKitAddLocalSlots(IntPtr gameSavingInstance, string[] localSlotInformationFilePaths, uint arraySize); [DllImport(IMPORT)] private static extern void GameKitClearSyncedSlots(IntPtr gameSavingInstance); [DllImport(IMPORT)] private static extern void GameKitSetFileActions(IntPtr gameSavingInstance, FileActions fileActions); [DllImport(IMPORT)] private static extern uint GameKitGetAllSlotSyncStatuses(IntPtr gameSavingInstance, IntPtr dispatchReceiver, FuncGameSavingResponseCallback resultCb, bool waitForAllPages, uint pageSize); [DllImport(IMPORT)] private static extern uint GameKitGetSlotSyncStatus(IntPtr gameSavingInstance, IntPtr dispatchReceiver, FuncGameSavingSlotActionResponseCallback resultCb, string slotName); [DllImport(IMPORT)] private static extern uint GameKitDeleteSlot(IntPtr gameSavingInstance, IntPtr dispatchReceiver, FuncGameSavingSlotActionResponseCallback resultCb, string slotName); [DllImport(IMPORT)] private static extern uint GameKitSaveSlot(IntPtr gameSavingInstance, IntPtr dispatchReceiver, FuncGameSavingSlotActionResponseCallback resultCb, GameSavingModel model); [DllImport(IMPORT)] private static extern uint GameKitLoadSlot(IntPtr gameSavingInstance, IntPtr dispatchReceiver, FuncGameSavingDataResponseCallback resultCb, GameSavingModel model); [AOT.MonoPInvokeCallback(typeof(FuncGameSavingResponseCallback))] protected static void GameSavingResponseCallback(IntPtr dispatchReceiver, IntPtr cachedSlots, uint slotCount, bool complete, uint callStatus) { // retrieve SlotListResult object reference from encoded IntPtr SlotListResult result = Marshaller.GetDispatchObject<SlotListResult>(dispatchReceiver); // handle assignments to the result object result.CachedSlots = Marshaller.IntPtrToArray<Slot>(cachedSlots, slotCount); // copy the GK Error status result.ResultCode = callStatus; } [AOT.MonoPInvokeCallback(typeof(FuncGameSavingSlotActionResponseCallback))] protected static void GameSavingSlotActionResponseCallback(IntPtr dispatchReceiver, IntPtr cachedSlots, uint slotCount, IntPtr activeSlot, uint callStatus) { // retrieve SlotActionResult object reference from encoded IntPtr SlotActionResult result = Marshaller.GetDispatchObject<SlotActionResult>(dispatchReceiver); // handle assignments to the result object result.CachedSlots = Marshaller.IntPtrToArray<Slot>(cachedSlots, slotCount); result.ActionedSlot = Marshal.PtrToStructure<Slot>(activeSlot); // copy the GK Error status result.ResultCode = callStatus; } [AOT.MonoPInvokeCallback(typeof(FuncGameSavingDataResponseCallback))] protected static void GameSavingDataResponseCallback(IntPtr dispatchReceiver, IntPtr cachedSlots, uint slotCount, IntPtr slot, byte[] data, uint dataSize, uint callStatus) { // retrieve SlotDataResult object reference from encoded IntPtr SlotDataResult result = Marshaller.GetDispatchObject<SlotDataResult>(dispatchReceiver); // handle assignments to the result object result.CachedSlots = Marshaller.IntPtrToArray<Slot>(cachedSlots, slotCount); result.ActionedSlot = Marshal.PtrToStructure<Slot>(slot); result.Data = data; result.DataSize = dataSize; // copy the GK Error status result.ResultCode = callStatus; } public void AddLocalSlots(AddLocalSlotsDesc addSlotDesc) { DllLoader.TryDll(() => GameKitAddLocalSlots(GetInstance(), addSlotDesc.LocalSlotInformationFilePaths, (uint)addSlotDesc.LocalSlotInformationFilePaths.Length), nameof(GameKitAddLocalSlots)); } public void ClearSyncedSlots() { DllLoader.TryDll(() => GameKitClearSyncedSlots(GetInstance()), nameof(GameKitClearSyncedSlots)); } public void SetFileActions(FileActions fileActions) { DllLoader.TryDll(() => GameKitSetFileActions(GetInstance(), fileActions), nameof(GameKitSetFileActions)); } public SlotListResult GetAllSlotSyncStatuses() { SlotListResult result = new SlotListResult(); DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitGetAllSlotSyncStatuses(GetInstance(), dispatchReceiver, GameSavingResponseCallback, true, GameSavingConstants.GET_ALL_SLOT_SYNC_STATUSES_DEFAULT_PAGE_SIZE), nameof(GameKitGetAllSlotSyncStatuses)); return result; } public SlotActionResult GetSlotSyncStatus(string slotName) { SlotActionResult result = new SlotActionResult(); DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitGetSlotSyncStatus(GetInstance(), dispatchReceiver, GameSavingSlotActionResponseCallback, slotName), nameof(GameKitGetSlotSyncStatus)); return result; } public SlotActionResult DeleteSlot(string slotName) { SlotActionResult result = new SlotActionResult(); DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitDeleteSlot(GetInstance(), dispatchReceiver, GameSavingSlotActionResponseCallback, slotName), nameof(GameKitDeleteSlot)); return result; } public SlotActionResult SaveSlot(SaveSlotDesc saveSlotDesc) { SlotActionResult result = new SlotActionResult(); GCHandle dataPinHandle = GCHandle.Alloc(saveSlotDesc.Data, GCHandleType.Pinned); GameSavingModel gameSavingModel = DefaultGameSavingModel.Make(); gameSavingModel.SlotName = saveSlotDesc.SlotName; gameSavingModel.Metadata = saveSlotDesc.Metadata; gameSavingModel.EpochTime = saveSlotDesc.EpochTime; gameSavingModel.OverrideSync = saveSlotDesc.OverrideSync; gameSavingModel.Data = dataPinHandle.AddrOfPinnedObject(); gameSavingModel.DataSize = (uint)saveSlotDesc.Data.Length; gameSavingModel.LocalSlotInformationFilePath = saveSlotDesc.SaveInfoFilePath; DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitSaveSlot(GetInstance(), dispatchReceiver, GameSavingSlotActionResponseCallback, gameSavingModel), nameof(GameKitSaveSlot)); dataPinHandle.Free(); return result; } public SlotDataResult LoadSlot(LoadSlotDesc loadSlotDesc) { SlotDataResult result = new SlotDataResult(); GCHandle dataPinHandle = GCHandle.Alloc(loadSlotDesc.Data, GCHandleType.Pinned); GameSavingModel gameSavingModel = DefaultGameSavingModel.Make(); gameSavingModel.SlotName = loadSlotDesc.SlotName; gameSavingModel.OverrideSync = loadSlotDesc.OverrideSync; gameSavingModel.Data = dataPinHandle.AddrOfPinnedObject(); gameSavingModel.DataSize = (uint)loadSlotDesc.Data.Length; gameSavingModel.LocalSlotInformationFilePath = loadSlotDesc.SaveInfoFilePath; DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitLoadSlot(GetInstance(), dispatchReceiver, GameSavingDataResponseCallback, gameSavingModel), nameof(GameKitLoadSlot)); dataPinHandle.Free(); return result; } protected override IntPtr Create(IntPtr sessionManager, FuncLoggingCallback logCb) { return DllLoader.TryDll(() => GameKitGameSavingInstanceCreateWithSessionManager(sessionManager, logCb, new string[] { }, 0, DefaultFileActions.Make()), nameof(GameKitGameSavingInstanceCreateWithSessionManager), IntPtr.Zero); } protected override void Release(IntPtr instance) { DllLoader.TryDll(() => GameKitGameSavingInstanceRelease(instance), nameof(GameKitGameSavingInstanceRelease)); } } }
177
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Runtime.Features.GameKitGameSaving { /// <summary> /// This class provides APIs for storing game save files in the cloud and synchronizing them with local devices. /// </summary> /// <remarks> /// /// [Initialization] /// <para> /// The Game Saving library will be automatically initialized, optionally the SetFileActions() can be called immediately after initialization. This initialization must be done before calling any other Game Saving APIs, and should /// only be done once in the lifetime of your program because the Game Saving library internally uses a singleton. /// /// After the library is initialized, each time a user logs in, GameKitClearSyncedSlots(), GameKitAddLocalSlots(), and GameKitGetAllSlotSyncStatuses() must be called in that order to ensure all local and cloud slots are up to date. /// The GameKitClearSyncedSlots() can optionally be called after a user logs out instead of being called before GameKitAddLocalSlots(). /// <list type="bullet"> /// <item>SetFileActions() is optional. It lets you provide custom file I/O in case the default I/O functions provided by Unity don't support your target platform(s). </item> /// <item>ClearSyncedSlots can be called during the initialization step, before AddLocalSlots() is called. Alternatively it can be called after a user logs out to ensure no cached slots remain.</item> /// <item>AddLocalSlots() ensures Game Saving knows about local saves on the device that exist from previous times the game was played. </item> /// <item>GetAllSlotSyncStatuses() ensures Game Saving has the latest information about the cloud saves, knows which local saves are synchronized /// with the cloud, and which saves should be uploaded, downloaded, or need manual conflict resolution. </item> /// </list> /// </para> /// /// [Offline Mode] /// <para> /// If your game is being played without internet, you must still call SaveSlot() and DeleteSlot() each time you would normally call these methods. /// Otherwise, there is a risk that the progress made while playing offline will be overwritten the next time the game is played on this device with /// an internet connection if a newer save has since been uploaded from another device. /// </para> /// /// [Save Slots] /// <para> /// Save files that are uploaded/downloaded/tracked through this API are each associated with a named "save slot" for the player. /// /// When you deploy the Game Saving feature, you can configure the maximum number of cloud saves slots to provide each player. This limit can /// prevent malicious players from storing too much data in the cloud. You can change this limit by doing another deployment through the AWS GameKit Settings UI. /// </para> /// /// [Save Information] /// <para> /// The local and cloud attributes for a save slot are collectively known as "save information" and are stored in the Slot class. /// </para> /// /// [Cached Slots] /// <para> /// This library maintains a cache of slot information for all slots it interacts with (both locally and in the cloud). /// The cached slots are updated on every API call, and are also returned in the delegate of most API calls. /// </para> /// /// [SaveInfo.json Files] /// <para> /// This library creates "SaveInfo.json" files on the device every time save files are uploaded/downloaded through the SaveSlot() and LoadSlot() APIs. /// /// The exact filenames and locations are provided by you. We highly recommended you store the SaveInfo.json files alongside their corresponding /// save file to help developers and curious players to understand these files go together. /// /// The SaveInfo.json files are loaded during game startup by calling AddLocalSlots(). This informs the library about any save files that exist on the /// device from previous game sessions. /// </para> /// </remarks> public interface IGameSavingProvider { /// <summary> /// Asynchronously load slot information for all of the player's local saves on the device.<br/><br/> /// /// This should be the first method you call on the Game Saving library (except optionally SetFileActions() and ClearSyncedSlots()) and /// you should call it exactly once per user that is logged in. Afterwards, you should call GetAllSlotSyncStatuses(). /// See the class level documentation for more details on initialization.<br/><br/> /// /// This method loads the SaveInfo.json files that were created on the device during previous game sessions when calling SaveSlot() and LoadSlot(). /// This overwrites any cached slots in memory which have the same slot name as the slots loaded from the SaveInfo.json files. /// </summary> /// <param name="addSlotsDesc">Object containing a list of files to load when the game starts. /// Each file should contain the slot information for the locally saved slot and should be the file generated automatically by the SaveSlot()/LoadSlot() methods.</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void AddLocalSlots(AddLocalSlotsDesc addSlotsDesc, Action callback); /// <summary> /// This method will immediately clear the slots that are cached in the GameKit backend. /// /// ClearSyncedSlots() should be called immediately after a user logs out or immediately before AddLocalSlots() is called. This /// will ensure that any slots that were synced for a previous user are cleared out. /// </summary> public void ClearSyncedSlots(); /// <summary> /// Asynchronously change the file I/O callbacks used by this library.<br/><br/> /// /// If you call this method, it should be the first method called on the library(even before AddLocalSlots()).<br/><br/> /// /// By default, this library uses the DefaultFileActions documented in AwsGameKitGameSavingWrapper.h /// These use Unity-provided file I/O methods and may not work on all platforms. /// Call this method to provide your own file I/O methods which support the necessary platform(s). /// </summary> /// <param name="fileActions">Object containing delegates for file IO</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void SetFileActions(FileActions fileActions, Action callback); /// <summary> /// Asynchronously get a complete and updated view of the player's save slots (both local and cloud).<br/><br/> /// /// Call this method during initialization (see class level documentation) and any time you suspect the cloud saves may have /// been updated from another device.<br/><br/> /// /// This method adds cached slots for all cloud saves not currently on the device, updates all cached slots with accurate cloud attributes, /// and marks the SlotSyncStatus member of all cached slots with the recommended syncing action you should take.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen.If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="callback">Delegate called once this method completes. It contains information about each cloud save slot and known local slot. /// Additionally it contains the result status code for the call.</param> public void GetAllSlotSyncStatuses(Action<SlotListResult> callback); /// <summary> /// Asynchronously get an updated view and recommended syncing action for the player's specific save slot.<br/><br/> /// /// This method updates the specific save slot's cloud attributes and marks the SlotSyncStatus member with the recommended syncing action you should take.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME: The provided slot name is malformed.Check the logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND: The provided slot name was not found in the cached slots.This either means you have a typo in the slot name, /// or the slot only exists in the cloud and you need to call GetAllSlotSyncStatuses() first before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="slotName">String identifier for the save slot</param> /// <param name="callback">Delegate called once this method completes. It contains information about the slot in question. Additionally it contains the result status code for the call.</param> public void GetSlotSyncStatus(string slotName, Action<SlotActionResult> callback); /// <summary> /// Asynchronously delete the player's cloud save slot and remove it from the cached slots.<br/><br/> /// /// No local files are deleted from the device. Data is only deleted from the cloud and from memory(the cached slot).<br/><br/> /// /// After calling DeleteSlot(), you'll probably want to delete the local save file and corresponding SaveInfo.json file from the device. /// If you keep the SaveInfo.json file, then next time the game boots up this library will recommend re-uploading the save file to the cloud when /// you call GetAllSlotSyncStatuses() or GetSlotSyncStatus().<br/><br/> /// /// If your game is being played without internet, you must still call this method and delete the SaveInfo.json file as normal to avoid the risk /// of having the offline progress be overwritten when internet connectivity is restored.See the "Offline Mode" section in the file level documentation for more details.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME: The provided slot name is malformed.Check the logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND: The provided slot name was not found in the cached slots.This either means you have a typo in the slot name, /// or the slot only exists in the cloud and you need to call GetAllSlotSyncStatuses() first before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="slotName">String identifier for the save slot</param> /// <param name="callback">Delegate called once this method completes. It contains information about the slot that was deleted. Additionally it contains the result status code for the call.</param> public void DeleteSlot(string slotName, Action<SlotActionResult> callback); /// <summary> /// Asynchronously upload a data buffer to the cloud, overwriting the player's cloud slot if it already exists.<br/><br/> /// /// Also write the slot's information to a SaveInfo.json file on the device, and add the slot to the cached slots if it doesn't already exist. /// This SaveInfo.json file should be passed into AddLocalSlots() when you initialize the Game Saving library in the future.<br/><br/> /// /// If your game is being played without internet, you must still call this method as normal to avoid the risk of having the offline progress be /// overwritten when internet connectivity is restored.See the "Offline Mode" section in the file level documentation for more details.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method. <br/> /// - GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME: The provided slot name is malformed.Check the logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_FILE_WRITE_FAILED: The SaveInfo.json file was unable to be written to the device.If using the default file I/O callbacks, /// check the logs to see the root cause.If the platform is not supported by the default file I/O callbacks, /// use SetFileActions() to provide your own callbacks.See SetFileActions() for more details.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MAX_CLOUD_SLOTS_EXCEEDED: The upload was cancelled because it would have caused the player to exceed their "maximum cloud save slots limit". This limit /// was configured when you deployed the Game Saving feature and can be changed by doing another deployment through the Plugin UI.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_EXCEEDED_MAX_SIZE: The Metadata member of your Request object is too large. Please see the documentation on FGameSavingSaveSlotRequest::Metadata for details.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT: The upload was cancelled to prevent overwriting the player's progress. This most likely indicates the player has played on multiple /// devices without having their progress properly synced with the cloud at the start and end of their play sessions.We recommend you inform /// the player of this conflict and present them with a choice - keep the cloud save or keep the local save.Then call SaveSlot() or LoadSlot() /// with OverrideSync= true to override the cloud/local file.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_CLOUD_SLOT_IS_NEWER: The upload was cancelled because the cloud save file is newer than the file you attempted to upload. Treat this like a /// GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT because the local and cloud save might have non-overlapping game progress.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="saveSlotDesc">Object containing the required information about the slot that needs to be saved(uploaded) to cloud storage</param> /// <param name="callback">Delegate called once this method completes. It contains information about the newly saved slot. Additionally it contains the result status code for the call.</param> public void SaveSlot(SaveSlotDesc saveSlotDesc, Action<SlotActionResult> callback); /// <summary> /// Asynchronously download the player's cloud slot into a local data buffer. /// /// Also write the slot's information to a SaveInfo.json file on the device. /// This SaveInfo.json file should be passed into AddLocalSlots() when you initialize the Game Saving library in the future.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature(AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME: The provided slot name is malformed.Check the logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND: The provided slot name was not found in the cached slots.This either means you have a typo in the slot name, /// or the slot only exists in the cloud and you need to call GetAllSlotSyncStatuses() first before calling this method.<br/> /// - GAMEKIT_ERROR_FILE_WRITE_FAILED: The SaveInfo.json file was unable to be written to the device. If using the default file I/O callbacks, /// check the logs to see the root cause.If the platform is not supported by the default file I/O callbacks, /// use SetFileActions() to provide your own callbacks.See SetFileActions() for more details.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT: The download was cancelled to prevent overwriting the player's progress. This most likely indicates the player has played on multiple /// devices without having their progress properly synced with the cloud at the start and end of their play sessions.We recommend you inform /// the player of this conflict and present them with a choice - keep the cloud save or keep the local save.Then call SaveSlot() or LoadSlot() /// with OverrideSync= true to override the cloud/local file.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_LOCAL_SLOT_IS_NEWER: The download was cancelled because the local save file is newer than the cloud file you attempted to download.Treat this like a /// GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT because the local and cloud save might have non-overlapping game progress.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_UNKNOWN_SYNC_STATUS: The download was cancelled because the sync status could not be determined. Treat this like a GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_MISSING_SHA: The S3 file is missing a SHA-256 metadata attribute and therefore the validity of the file could not be determined.This should not happen. If it does, /// this indicates there is a bug in the backend code.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_SLOT_TAMPERED: The SHA-256 hash of the downloaded file does not match the SHA-256 hash of the original file that was uploaded to S3. This indicates the downloaded /// file was corrupted or tampered with. You should try downloading again to rule out the possibility of random corruption.<br/> /// - GAMEKIT_ERROR_GAME_SAVING_BUFFER_TOO_SMALL: The data buffer you provided in the Request object is not large enough to hold the downloaded S3 file.This likely means a newer version of the /// cloud file was uploaded from another device since the last time you called GetAllSlotSyncStatuses() or GetSlotSyncStatus() on this device.To resolve, /// call GetSlotSyncStatus() to get the up-to-date size of the cloud file.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed.Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload.This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="loadSlotDesc">Object containing the required information about the slot that needs to be loaded(downloaded) from cloud storage</param> /// <param name="callback">Delegate called once this method completes. It contains information about the slot loaded and a buffer to the data downloaded from cloud storage for the slot. /// Additionally it contains the result status code for the call.</param> public void LoadSlot(LoadSlotDesc loadSlotDesc, Action<SlotDataResult> callback); } }
236
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Runtime.Features.GameKitIdentity { /// <summary> /// Identity feature. /// </summary> public class Identity : GameKitFeatureBase<IdentityWrapper>, IIdentityProvider { public override FeatureType FeatureType => FeatureType.Identity; const string LOGIN_URL_KEY = "loginUrl"; const string REQUEST_ID_KEY = "requestId"; /// <summary> /// Call to get an instance of the GameKit Identity feature. /// </summary> /// <returns>An instance of the Identity feature that can be used to call Identity related methods.</returns> public static Identity Get() { return GameKitFeature<Identity>.Get(); } /// <summary> /// Register a new player for email and password based sign in.<br/><br/> /// /// After calling this method, you must call ConfirmRegistration() to confirm the player's identity.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_MALFORMED_PASSWORD: The provided Password is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_METHOD_NOT_IMPLEMENTED: You attempted to register a guest, which is not yet supported. To fix, make sure the request's FUserRegistrationRequest::UserId field is empty.<br/> /// - GAMEKIT_ERROR_REGISTER_USER_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="userRegistration">Object containing the information about the user to register</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void Register(UserRegistration userRegistration, Action<uint> callback) { Call(Feature.IdentityRegister, userRegistration, callback); } /// <summary> /// Confirm registration of a new player that was registered through Register().<br/><br/> /// /// The confirmation code is sent to the player's email and can be re-sent by calling ResendConfirmationCode().<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_CONFIRM_REGISTRATION_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="request">Object containing the required username and code to confirm the registration</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ConfirmRegistration(ConfirmRegistrationRequest request, Action<uint> callback) { Call(Feature.IdentityConfirmRegistration, request, callback); } /// <summary> /// Resend the registration confirmation code to the player's email.<br/><br/> /// /// This resends the confirmation code that was sent by calling Register() or ResendConfirmationCode().<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_RESEND_CONFIRMATION_CODE_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="request">Object containing the username of the user requesting the resend</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ResendConfirmationCode(ResendConfirmationCodeRequest request, Action<uint> callback) { Call(Feature.IdentityResendConfirmationCode, request, callback); } /// <summary> /// Send a password reset code to the player's email.<br/><br/> /// /// After calling this method, you must call ConfirmForgotPassword() to complete the password reset.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_FORGOT_PASSWORD_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="request">Object containing the username of the user requesting a password reset</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ForgotPassword(ForgotPasswordRequest request, Action<uint> callback) { Call(Feature.IdentityForgotPassword, request, callback); } /// <summary> /// Set the player's new password.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_MALFORMED_PASSWORD: The provided Password is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_CONFIRM_FORGOT_PASSWORD_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="request">Object containing the username and required new password information</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ConfirmForgotPassword(ConfirmForgotPasswordRequest request, Action<uint> callback) { Call(Feature.IdentityConfirmForgotPassword, request, callback); } /// <summary> /// Retrieves a login/signup URL for the specified federated identity provider.<br/><br/> /// /// Players will be able to register and/or sign in when the URL opens in a web browser.<br/><br/> /// /// This method will automatically start polling for login completion with PollAndRetrieveFederatedTokens() /// after the login url has been opened. /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: Http request to get Federated login url failed. /// - GAMEKIT_ERROR_INVALID_FEDERATED_IDENTITY_PROVIDER: The specified federated identity provider is invalid or is not yet supported. /// </summary> /// <param name="identityProvider">enum for the identity provider</param> /// <param name="loginUrlRetrievedCallback">Delegate that is called once a login url for the federated provider is available.</param> /// <param name="loginCompletionCallback">Delegate that is called once the player has finished logging in, and the token has been cached, uint argument is the gamekit status code from polling for login completion.</param> /// <param name="loginTimeout">How long the player has to login before polling for completion stops.</param> public void FederatedLogin(FederatedIdentityProvider identityProvider, Action<MultiKeyValueStringCallbackResult> loginUrlRetrievedCallback, Action<uint> loginCompletionCallback, int loginTimeout) { // implement default callbacks that will open the login url, start polling for completed login, and cache the token. if (loginCompletionCallback == null) { loginCompletionCallback = (uint result) => { Debug.Log("Finished polling for federated login, token retrieved."); }; } Action<MultiKeyValueStringCallbackResult> wrappedLoginUrlRetrievedCallback = (MultiKeyValueStringCallbackResult resultCb) => { for (int i = 0; i < resultCb.ResponseKeys.Length; i++) { if (String.Equals(resultCb.ResponseKeys[i], LOGIN_URL_KEY)) { Application.OpenURL(resultCb.ResponseValues[i]); } else if (String.Equals(resultCb.ResponseKeys[i], REQUEST_ID_KEY)) { PollAndRetrieveFederatedTokensDesc pollRequest = new PollAndRetrieveFederatedTokensDesc { IdentityProvider = identityProvider, RequestId = resultCb.ResponseValues[i], Timeout = loginTimeout }; PollAndRetrieveFederatedTokens(pollRequest, loginCompletionCallback); } } loginUrlRetrievedCallback.Invoke(resultCb); }; Call(Feature.GetFederatedLoginUrl, identityProvider, wrappedLoginUrlRetrievedCallback); } /// <summary> /// Continually check if the player has completed signing in with the federated identity provider, then store their access tokens in the AwsGameKitSessionManager.<br/><br/> /// /// After calling this method, the player will be signed in and you'll be able to call the other GameKit APIs. /// This method stores the player's authorized access tokens in the AWS GameKit Session Manager, which automatically refreshes them before they expire.<br/><br/> /// /// To call this method, you must first call GetFederatedLoginUrl() to get a unique request ID.<br/><br/> /// /// This method will timeout after the specified limit, in which case the player is not logged in. /// You can call GetFederatedIdToken() to check if the login was successful.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </summary> /// <param name="pollAndRetrieveFederatedTokensDesc">Object containing details for the request such as timeout and provider</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void PollAndRetrieveFederatedTokens(PollAndRetrieveFederatedTokensDesc pollAndRetrieveFederatedTokensDesc, Action<uint> callback) { Call(Feature.PollAndRetrieveFederatedTokens, pollAndRetrieveFederatedTokensDesc, callback); } /// <summary> /// Get the player's authorized Id token for the specified federated identity provider.<br/><br/> /// /// The returned access token will be empty if the player is not logged in with the federated identity provider.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_INVALID_FEDERATED_IDENTITY_PROVIDER: The specified federated identity provider is invalid or is not yet supported. /// </summary> /// <param name="identityProvider">enum for the identity provider</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetFederatedIdToken(FederatedIdentityProvider identityProvider, Action<StringCallbackResult> callback) { Call(Feature.GetFederatedIdToken, identityProvider, callback); } /// <summary> /// Sign in the player through email and password.<br/><br/> /// /// After calling this method, the player will be signed in and you'll be able to call the other GameKit APIs. /// This method stores the player's authorized access tokens in the AwsGameKitSessionManager, and automatically refreshes them before they expire.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </summary> /// <param name="userLogin">Object containing login information</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void Login(UserLogin userLogin, Action<uint> callback) { Call(Feature.IdentityLogin, userLogin, callback); } /// <summary> /// Sign out the currently logged in player.<br/><br/> /// /// This revokes the player's access tokens and clears them from the AwsGameKitSessionManager.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void Logout(Action<uint> callback) { Call(Feature.IdentityLogout, callback); } /// <summary> /// Get information about the currently logged in player.<br/><br/> /// /// The response is a JSON string containing the following information (or an empty string if the call failed):<br/> /// - The date time when the player was registered.<br/> /// - The date time of the last time the player's identity information was modified.<br/> /// - The player's GameKit ID.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the output logs to see what the HTTP response code was<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetUser(Action<GetUserResult> callback) { Call(Feature.IdentityGetUser, callback); } } }
265
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; namespace AWS.GameKit.Runtime.Features.GameKitIdentity { public enum FederatedIdentityProvider { FACEBOOK = 0, }; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncIdentityGetUserResponseCallback(IntPtr dispatchReceiver, IntPtr getUserResponse); [StructLayout(LayoutKind.Sequential)] public struct IdentityInfo { public string CognitoAppClientId; public string Region; }; [StructLayout(LayoutKind.Sequential)] public struct UserRegistration { public string UserName; public string Password; public string Email; public string UserId; public string UserIdHash; public readonly override string ToString() => $"UserRegistration(UserName={UserName}, Password=<Hidden>, Email={Email}, UserId={UserId}, UserIdHash={UserIdHash})"; }; [StructLayout(LayoutKind.Sequential)] public struct ConfirmRegistrationRequest { public string UserName; public string ConfirmationCode; public readonly override string ToString() => $"ConfirmRegistrationRequest(UserName={UserName}, ConfirmationCode={ConfirmationCode})"; }; [StructLayout(LayoutKind.Sequential)] public struct ResendConfirmationCodeRequest { public string UserName; public readonly override string ToString() => $"ResendConfirmationCodeRequest(UserName={UserName})"; }; [StructLayout(LayoutKind.Sequential)] public struct UserLogin { public string UserName; public string Password; public readonly override string ToString() => $"UserLogin(UserName={UserName}, Password=<Hidden>)"; }; [StructLayout(LayoutKind.Sequential)] public struct ForgotPasswordRequest { public string UserName; public readonly override string ToString() => $"ForgotPasswordRequest(UserName={UserName})"; }; [StructLayout(LayoutKind.Sequential)] public struct ConfirmForgotPasswordRequest { public string UserName; public string NewPassword; public string ConfirmationCode; public readonly override string ToString() => $"ConfirmForgotPasswordRequest(UserName={UserName}, NewPassword=<Hidden>, ConfirmationCode={ConfirmationCode})"; }; [StructLayout(LayoutKind.Sequential)] public struct GetUserResponse { public string UserId; public string UpdatedAt; public string CreatedAt; public string FacebookExternalId; public string FacebookRefId; public string UserName; public string Email; public readonly override string ToString() => $"GetUserResponse(UserId={UserId}, UserName={UserName}, Email={Email}, UpdatedAt={UpdatedAt}, CreatedAt={CreatedAt}, FacebookExternalId={FacebookExternalId}, FacebookRefId={FacebookRefId})"; }; public class PollAndRetrieveFederatedTokensDesc { public FederatedIdentityProvider IdentityProvider; public string RequestId; public int Timeout; } public class GetUserResult { public uint ResultCode; public GetUserResponse Response; } }
108
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.Features.GameKitIdentity { /// <summary> /// Identity wrapper for GameKit C++ SDK calls /// </summary> public class IdentityWrapper : GameKitFeatureWrapperBase { // Select the correct source path based on the platform #if UNITY_IPHONE && !UNITY_EDITOR private const string IMPORT = "__Internal"; #else private const string IMPORT = "aws-gamekit-identity"; #endif // DLL loading [DllImport(IMPORT)] private static extern IntPtr GameKitIdentityInstanceCreateWithSessionManager(IntPtr sessionManager, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern void GameKitIdentityInstanceRelease(IntPtr identityInstance); [DllImport(IMPORT)] private static extern uint GameKitIdentityRegister(IntPtr identityInstance, UserRegistration userRegistration); [DllImport(IMPORT)] private static extern uint GameKitIdentityConfirmRegistration(IntPtr identityInstance, ConfirmRegistrationRequest request); [DllImport(IMPORT)] private static extern uint GameKitIdentityResendConfirmationCode(IntPtr identityInstance, ResendConfirmationCodeRequest request); [DllImport(IMPORT)] private static extern uint GameKitIdentityLogin(IntPtr identityInstance, UserLogin userLogin); [DllImport(IMPORT)] private static extern uint GameKitIdentityLogout(IntPtr identityInstance); [DllImport(IMPORT)] private static extern uint GameKitIdentityGetUser(IntPtr identityInstance, IntPtr dispatchReceiver, FuncIdentityGetUserResponseCallback responseCallback); [DllImport(IMPORT)] private static extern uint GameKitIdentityForgotPassword(IntPtr identityInstance, ForgotPasswordRequest request); [DllImport(IMPORT)] private static extern uint GameKitIdentityConfirmForgotPassword(IntPtr identityInstance, ConfirmForgotPasswordRequest request); [DllImport(IMPORT)] private static extern uint GameKitGetFederatedLoginUrl(IntPtr identityInstance, FederatedIdentityProvider identityProvider, IntPtr dispatchReceiver, FuncKeyValueStringCallback responseCallback); [DllImport(IMPORT)] private static extern uint GameKitPollAndRetrieveFederatedTokens(IntPtr identityInstance, FederatedIdentityProvider identityProvider, string requestId, int timeout); [DllImport(IMPORT)] private static extern uint GameKitGetFederatedIdToken(IntPtr identityInstance, FederatedIdentityProvider identityProvider, IntPtr dispatchReceiver, FuncStringCallback responseCallback); [AOT.MonoPInvokeCallback(typeof(FuncIdentityGetUserResponseCallback))] protected static void IdentityGetUserResponseCallback(IntPtr dispatchReceiver, IntPtr getUserResponse) { // recover object reference from dispatchReceiver GetUserResult result = Marshaller.GetDispatchObject<GetUserResult>(dispatchReceiver); // handle assignments to the result object result.Response = Marshal.PtrToStructure<GetUserResponse>(getUserResponse); } public uint IdentityRegister(UserRegistration userRegistration) { return DllLoader.TryDll(() => GameKitIdentityRegister(GetInstance(), userRegistration), nameof(GameKitIdentityRegister), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint IdentityConfirmRegistration(ConfirmRegistrationRequest request) { return DllLoader.TryDll(() => GameKitIdentityConfirmRegistration(GetInstance(), request), nameof(GameKitIdentityConfirmRegistration), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint IdentityResendConfirmationCode(ResendConfirmationCodeRequest request) { return DllLoader.TryDll(() => GameKitIdentityResendConfirmationCode(GetInstance(), request), nameof(GameKitIdentityResendConfirmationCode), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint IdentityLogin(UserLogin userLogin) { return DllLoader.TryDll(() => GameKitIdentityLogin(GetInstance(), userLogin), nameof(GameKitIdentityLogin), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint IdentityLogout() { return DllLoader.TryDll(() => GameKitIdentityLogout(GetInstance()), nameof(GameKitIdentityLogout), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public GetUserResult IdentityGetUser() { GetUserResult result = new GetUserResult(); uint status = DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitIdentityGetUser(GetInstance(), dispatchReceiver, IdentityGetUserResponseCallback), nameof(GameKitIdentityGetUser), GameKitErrors.GAMEKIT_ERROR_GENERAL); result.ResultCode = status; return result; } public uint IdentityForgotPassword(ForgotPasswordRequest request) { return DllLoader.TryDll(() => GameKitIdentityForgotPassword(GetInstance(), request), nameof(GameKitIdentityForgotPassword), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint IdentityConfirmForgotPassword(ConfirmForgotPasswordRequest request) { return DllLoader.TryDll(() => GameKitIdentityConfirmForgotPassword(GetInstance(), request), nameof(GameKitIdentityConfirmForgotPassword), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public MultiKeyValueStringCallbackResult GetFederatedLoginUrl(FederatedIdentityProvider identityProvider) { MultiKeyValueStringCallbackResult result = new MultiKeyValueStringCallbackResult(); uint status = DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitGetFederatedLoginUrl(GetInstance(), identityProvider, dispatchReceiver, GameKitCallbacks.MultiKeyValueStringCallback), nameof(GameKitGetFederatedLoginUrl), GameKitErrors.GAMEKIT_ERROR_GENERAL); result.ResultCode = status; return result; } public uint PollAndRetrieveFederatedTokens(PollAndRetrieveFederatedTokensDesc pollAndRetrieveFederatedTokensDesc) { return DllLoader.TryDll(() => GameKitPollAndRetrieveFederatedTokens( GetInstance(), pollAndRetrieveFederatedTokensDesc.IdentityProvider, pollAndRetrieveFederatedTokensDesc.RequestId, pollAndRetrieveFederatedTokensDesc.Timeout), nameof(GameKitPollAndRetrieveFederatedTokens), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public StringCallbackResult GetFederatedIdToken(FederatedIdentityProvider identityProvider) { StringCallbackResult result = new StringCallbackResult(); uint status = DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitGetFederatedIdToken(GetInstance(), identityProvider, dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitGetFederatedIdToken), GameKitErrors.GAMEKIT_ERROR_GENERAL); result.ResultCode = status; return result; } protected override IntPtr Create(IntPtr sessionManager, FuncLoggingCallback logCb) { return DllLoader.TryDll(() => GameKitIdentityInstanceCreateWithSessionManager(sessionManager, logCb), nameof(GameKitIdentityInstanceCreateWithSessionManager), IntPtr.Zero); } protected override void Release(IntPtr instance) { DllLoader.TryDll(() => GameKitIdentityInstanceRelease(instance), nameof(GameKitIdentityInstanceRelease)); } } }
142
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Runtime.Features.GameKitIdentity { /// <summary> /// Interface for the AWS GameKit Identity feature. /// </summary> public interface IIdentityProvider { /// <summary> /// Register a new player for email and password based sign in.<br/><br/> /// /// After calling this method, you must call ConfirmRegistration() to confirm the player's identity.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_MALFORMED_PASSWORD: The provided Password is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_METHOD_NOT_IMPLEMENTED: You attempted to register a guest, which is not yet supported. To fix, make sure the request's FUserRegistrationRequest::UserId field is empty.<br/> /// - GAMEKIT_ERROR_REGISTER_USER_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="userRegistration">Object containing the information about the user to register</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void Register(UserRegistration userRegistration, Action<uint> callback); /// <summary> /// Confirm registration of a new player that was registered through Register().<br/><br/> /// /// The confirmation code is sent to the player's email and can be re-sent by calling ResendConfirmationCode().<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_CONFIRM_REGISTRATION_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="request">Object containing the required username and code to confirm the registration</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ConfirmRegistration(ConfirmRegistrationRequest request, Action<uint> callback); /// <summary> /// Resend the registration confirmation code to the player's email.<br/><br/> /// /// This resends the confirmation code that was sent by calling Register() or ResendConfirmationCode().<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_RESEND_CONFIRMATION_CODE_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="request">Object containing the username of the user requesting the resend</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ResendConfirmationCode(ResendConfirmationCodeRequest request, Action<uint> callback); /// <summary> /// Send a password reset code to the player's email.<br/><br/> /// /// After calling this method, you must call ConfirmForgotPassword() to complete the password reset.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_FORGOT_PASSWORD_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="request">Object containing the username of the user requesting a password reset</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ForgotPassword(ForgotPasswordRequest request, Action<uint> callback); /// <summary> /// Set the player's new password.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_MALFORMED_USERNAME: The provided UserName is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_MALFORMED_PASSWORD: The provided Password is malformed. Check the output logs to see what the required format is.<br/> /// - GAMEKIT_ERROR_CONFIRM_FORGOT_PASSWORD_FAILED: The backend web request failed. Check the output logs to see what the error was. /// </summary> /// <param name="request">Object containing the username and required new password information</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ConfirmForgotPassword(ConfirmForgotPasswordRequest request, Action<uint> callback); /// <summary> /// Retrieves a login/signup URL for the specified federated identity provider.<br/><br/> /// /// Players will be able to register and/or sign in when the URL opens in a web browser.<br/><br/> /// /// This method will automatically start polling for login completion with PollAndRetrieveFederatedTokens() /// after the login url has been opened. /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_INVALID_FEDERATED_IDENTITY_PROVIDER: The specified federated identity provider is invalid or is not yet supported. /// </summary> /// <param name="identityProvider">enum for the identity provider</param> /// <param name="loginUrlRetrievedCallback">Delegate that is called once a login url for the federated provider is available.</param> /// <param name="loginCompletionCallback">Delegate that is called once the player has finished logging in, and the token has been cached.</param> /// <param name="loginTimeout">How long the player has to login before polling for completion stops.</param> /// <param name="loginTimeout">How long the player has to login and polling for completion stops.</param> public void FederatedLogin(FederatedIdentityProvider identityProvider, Action<MultiKeyValueStringCallbackResult> loginUrlRetrievedCallback, Action<uint> loginCompletionCallback = null, int loginTimeout = 90); /// <summary> /// Continually check if the player has completed signing in with the federated identity provider, then store their access tokens in the AwsGameKitSessionManager.<br/><br/> /// /// After calling this method, the player will be signed in and you'll be able to call the other GameKit APIs. /// This method stores the player's authorized access tokens in the AWS GameKit Session Manager, which automatically refreshes them before they expire.<br/><br/> /// /// To call this method, you must first call GetFederatedLoginUrl() to get a unique request ID.<br/><br/> /// /// This method will timeout after the specified limit, in which case the player is not logged in. /// You can call GetFederatedIdToken() to check if the login was successful.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </summary> /// <param name="pollAndRetrieveFederatedTokensDesc">Object containing details for the request such as timeout and provider</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void PollAndRetrieveFederatedTokens(PollAndRetrieveFederatedTokensDesc pollAndRetrieveFederatedTokensDesc, Action<uint> callback); /// <summary> /// Get the player's authorized Id token for the specified federated identity provider.<br/><br/> /// /// The returned access token will be empty if the player is not logged in with the federated identity provider.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_INVALID_FEDERATED_IDENTITY_PROVIDER: The specified federated identity provider is invalid or is not yet supported. /// </summary> /// <param name="identityProvider">enum for the identity provider</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetFederatedIdToken(FederatedIdentityProvider identityProvider, Action<StringCallbackResult> callback); /// <summary> /// Sign in the player through email and password.<br/><br/> /// /// After calling this method, the player will be signed in and you'll be able to call the other GameKit APIs. /// This method stores the player's authorized access tokens in the AwsGameKitSessionManager, and automatically refreshes them before they expire.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </summary> /// <param name="userLogin">Object containing login information</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void Login(UserLogin userLogin, Action<uint> callback); /// <summary> /// Sign out the currently logged in player.<br/><br/> /// /// This revokes the player's access tokens and clears them from the AwsGameKitSessionManager.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// - GAMEKIT_ERROR_LOGIN_FAILED: There was no user logged in or an exception occurred while revoking the user's tokens. For the second case, please check the logs for details. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void Logout(Action<uint> callback); /// <summary> /// Get information about the currently logged in player.<br/><br/> /// /// The response is a JSON string containing the following information (or an empty string if the call failed):<br/> /// - The date time when the player was registered.<br/> /// - The date time of the last time the player's identity information was modified.<br/> /// - The player's GameKit ID.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the output logs to see what the HTTP response code was<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetUser(Action<GetUserResult> callback); } }
181
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Runtime.Features.GameKitUserGameplayData { /// <summary> /// Interface for the AWS GameKit User Gameplay Data feature. /// </summary> public interface IUserGameplayDataProvider { /// <summary> /// Creates a new bundle or updates BundleItems within a specific bundle for the calling user.<br/><br/> /// /// <remarks> /// AddBundle should only be called the first time bundle items are created called to prevent excessive server use. /// </remarks><br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name of userGameplayDataBundle is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY: At least one of the bundle keys of userGameplayData are malformed. If this error is received, Check the output log for more details on which item keys are not valid.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason. <br/> /// </summary> /// <param name="addUserGameplayDataDesc">Object containing a map of game play data to add</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void AddBundle(AddUserGameplayDataDesc addUserGameplayDataDesc, Action<AddUserGameplayDataResults> callback); /// <summary> /// Applies the settings to the User Gameplay Data Client. Should be called immediately after the instance has been created and before any other API calls. /// </summary> /// <param name="userGameplayDataClientSettings">Object containing client settings</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void SetClientSettings(UserGameplayDataClientSettings userGameplayDataClientSettings, Action callback); /// <summary> /// Lists the bundle name of every bundle that the calling user owns.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The response body from the backend could not be parsed successfully<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ListBundles(Action<MultiStringCallbackResult> callback); /// <summary> /// Gets all items that are associated with a certain bundle for the calling user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name of UserGameplayDataBundleName is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The response body from the backend could not be parsed successfully<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="bundleName">Name of the data bundle items to fetch</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetBundle(string bundleName, Action<GetUserGameplayDataBundleResults> callback); /// <summary> /// Gets a single item that is associated with a certain bundle for a user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name in userGameplayDataBundleItem is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY: The bundle key in userGameplayDataBundleItem is malformed. If this error is received, Check the output log for more details on which item keys are not valid.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="userGameplayDataBundleItem">Object containing needed inforamtion for fetching the bundle item</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetBundleItem(UserGameplayDataBundleItem userGameplayDataBundleItem, Action<StringCallbackResult> callback); /// <summary> /// Updates the value of an existing item inside a bundle with new item data.<br/><br/> /// /// <remarks> /// To prevent excessive server use, UpdateItem should be used intermittently on data that is being stored locally. Ex. Calling UpdateItem for a players coins after the level ends instead of each time they collect a coin. /// </remarks><br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name in userGameplayDataBundleItem is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY: The bundle key in userGameplayDataBundleItem is malformed. If this error is received, Check the output log for more details on which item keys are not valid.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="userGameplayDataBundleItemValue">Object containing information for the bundle item update and what to update it with</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void UpdateItem(UserGameplayDataBundleItemValue userGameplayDataBundleItemValue, Action<uint> callback); /// <summary> /// Permanently deletes all bundles associated with a user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void DeleteAllData(Action<uint> callback); /// <summary> /// Permanently deletes an entire bundle, along with all corresponding items, associated with a user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name in UserGameplayDataBundleName is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="bundleName">name of the bundle to delete</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void DeleteBundle(string bundleName, Action<uint> callback); /// <summary> /// Permanently deletes a list of items inside of a bundle associated with a user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name in userGameplayDataBundleItemsDeleteRequest is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY: The bundle key in userGameplayDataBundleItemsDeleteRequest is malformed. If this error is received, Check the output log for more details on which item keys are not valid.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="deleteUserGameplayDataBundleItemsDesc">Object containing the bundle and list of items to delete</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void DeleteBundleItems(DeleteUserGameplayDataBundleItemsDesc deleteUserGameplayDataBundleItemsDesc, Action<uint> callback); /// <summary> /// Enables automatic offline mode, including persisting all failed calls in the retry thread to a cache file at the end of program.<br/><br/> /// If the cache needs to be persisted before the application is closed it is recommended to use StopRetryBackgroundThread() to stop the thread and PersistToCache to save the cache manually, then EnableAutomaticOfflineModeWithCaching can be restarted. <br/><br/> /// /// Note: Methods such as DropAllCachedEvents, SetNetworkChangeDelegate, SetCacheProcessedDelegate and SetClientSettings are not handled by this method and should be called independently. /// </summary> /// <param name="offlineCacheFile">The location of the offline cache file. All persisted calls in the cache will automatically be loaded into the queue. Any failed calls in the queue at the end of the program will be cached in this file.</param> public void EnableAutomaticOfflineModeWithCaching(string offlineCacheFile); /// <summary> /// Start the Retry background thread.<br/><br/> /// /// The DestroyFeature() method, which is automatically called when the application is closing, will handle stopping the thread.<br/> /// However, if you need to persist the files during play it is recommended that you call StopRetryBackgroundThread() and Save/Load to Cache manually.<br/><br/> /// /// Note: If you are Caching your offline calls, StartRetryBackgroundThread() should be called after loading from cache. /// </summary> public void StartRetryBackgroundThread(); /// <summary> /// Stop the Retry background thread.<br/><br/> /// /// Note: If you are caching your offline calls, StopRetryBackgroundThread() should be called before saving to cache. /// </summary> public void StopRetryBackgroundThread(); /// <summary> /// Return information about the running state of the background thread. /// </summary> /// <returns>True if it is running, false otherwise</returns> public bool IsBackgroundThreadRunning(); /// <summary> /// Clear all pending events from the user's cache. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void DropAllCachedEvents(Action callback); /// <summary> /// Set the callback to invoke when the network state changes. /// </summary> /// <param name="callback">Delegate that should be called whenever there is a network change.</param> public void SetNetworkChangeDelegate(UserGameplayData.NetworkChangedDelegate callback); /// <summary> /// Get the last known state of network connectivity. /// </summary> /// <returns>The last known state of connectivity. True means healthy, False means unhealthy</returns> public bool GetLastNetworkHealthState(); /// <summary> /// Forces an immediate retry of the calls that are in the queue. /// </summary> /// <remarks>The Network state can transiton from Unhealthy to Healthy as a side effect of this.</remarks> /// <param name="resultCallback">Callback invoked then the retry finishes. Returns success or failure.</param> public void ForceRetry(Action<bool> resultCallback); /// <summary> /// Attempts to synchronize data in the queue with the backend and, if successful, executes another User Gameplay Data API. /// Use this when you want to be sure that the data in the backend is updated before making subsequent calls. /// </summary> /// <param name="gameplayDataApiCall">The User Gameplay Data API to call (for example GetBundle(), GetBundleItem(), ListBundles(), or other APIs)</param> /// <param name="onErrorAction">Action to execute in case of error. Error can happen if the device is still offline or if the backend is experiencing problems.</param> public void TryForceSynchronizeAndExecute(Action gameplayDataApiCall, Action onErrorAction); /// <summary> /// Set the callback to invoke when the offline cache finishes processing. /// </summary> /// <param name="callback">Delegate that should be called whenever the cache has been successfully processed.</param> public void SetCacheProcessedDelegate(UserGameplayData.CacheProcessedDelegate callback); /// <summary> /// Write the pending API calls to cache.<br/><br/> /// /// Pending API calls are requests that could not be sent due to network being offline or other failures.<br/> /// The internal queue of pending calls is cleared. It is recommended to stop the background thread before calling this method.<br/><br/> /// /// This is the non-blocking version persist to cache call and should be used when saving during play, if you need to persist to cache on application close the blocking version, ImmediatePersistToCache() is recommended.<br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_WRITE_FAILED: There was an issue writing the queue to the offline cache file.<br/> /// </summary> /// <param name="offlineCacheFile">Path to the offline cache file.</param> /// <param name="callback">Delegate that is called once the function has finished executing.</param> public void PersistToCache(string offlineCacheFile, Action<uint> callback); /// <summary> /// Write the pending API calls to cache.<br/><br/> /// /// Pending API calls are requests that could not be sent due to network being offline or other failures.<br/> /// The internal queue of pending calls is cleared. It is recommended to stop the background thread before calling this method.<br/><br/> /// /// This is the blocking version of the call and should be used on application close. PersistToCache() is recommended for saving to cache during play.<br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_WRITE_FAILED: There was an issue writing the queue to the offline cache file.<br/> /// </summary> /// <param name="offlineCacheFile">Path to the offline cache file.</param> /// <returns>The result code of persisting the queue to cache.</returns> public uint ImmediatePersistToCache(string offlineCacheFile); /// <summary> /// Read the pending API calls from cache.<br/><br/> /// /// The calls will be enqueued and retried as soon as the Retry background thread is started and network connectivity is up.<br/> /// The contents of the cache are deleted.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_READ_FAILED: There was an issue loading the offline cache file to the queue.<br/> /// </summary> /// <param name="offlineCacheFile">path to the offline cache file.</param> /// <param name="callback">Delegate that is called once the function has finished executing.</param> public void LoadFromCache(string offlineCacheFile, Action<uint> callback); } }
287
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.Features.GameKitUserGameplayData { /// <summary> /// User Gameplay Data feature. /// </summary> public class UserGameplayData : GameKitFeatureBase<UserGameplayDataWrapper>, IUserGameplayDataProvider { public override FeatureType FeatureType => FeatureType.UserGameplayData; private static FileManager _fileManager; // Automatic offline state private bool _isOfflineCacheRunning = false; private string _offlineCacheFile = string.Empty; #if UNITY_IOS private bool _shouldAutoRestartCache = false; #endif // Delegates public delegate void NetworkChangedDelegate(NetworkStatusChangeResults results); public delegate void CacheProcessedDelegate(CacheProcessedResults results); /// <summary> /// Call to get an instance of the GameKit UserGameplayData feature. /// </summary> /// <returns>An instance of the UserGameplayData feature that can be used to call UserGameplayData related methods.</returns> public static UserGameplayData Get() { _fileManager = new FileManager(); return GameKitFeature<UserGameplayData>.Get(); } /// <summary> /// Used to trigger any functionality that should happen when the applications pause status is changed. /// </summary> /// <param name="isPaused">True if the application is paused, else False.</param> protected override void NotifyPause(bool isPaused) { #if UNITY_IOS // On iOS shutdown code can sometimes be unreliable since each application is paused before being shut down. // In order to ensure the users cache is being saved properly we can save when the application is suspended and reload when its opened again if (isPaused && _isOfflineCacheRunning) { OfflineSupportCleanup(); _shouldAutoRestartCache = true; } else if (!isPaused && _shouldAutoRestartCache) { if (!string.IsNullOrEmpty(_offlineCacheFile) && _fileManager.FileExists(_offlineCacheFile)) { LoadFromCache(_offlineCacheFile, result => { Logging.LogInfo($"User Gameplay Data LoadFromCache completed with result: {result}"); if (result == 0) { StartRetryBackgroundThread(); } else { Logging.LogInfo($"Since LoadFromCache was not successful, the retry thread will not be restarted to ensure calls are not overwritten."); } }); } else { StartRetryBackgroundThread(); } _shouldAutoRestartCache = false; } #endif } /// <summary> /// Used to trigger any functionality that should happen when the applications quits, before OnDispose is called. /// /// NotifyApplicationQuit is from both the Editor and Standalone whereas DestroyFeature() is only called during runtime. /// </summary> protected override void NotifyApplicationQuit() { #if !UNITY_IOS // For iOS this is handled NotifyPause OfflineSupportCleanup(); #endif } /// <summary> /// Handles stopping the retry thread, if it is running, when the User Gameplay Data feature is being destroyed. /// If automatic caching has been set up will also persist the current queue to the cache file. /// </summary> private void OfflineSupportCleanup() { if (_isOfflineCacheRunning) { StopRetryBackgroundThread(); if (!string.IsNullOrEmpty(_offlineCacheFile)) { uint result = ImmediatePersistToCache(_offlineCacheFile); Logging.LogInfo($"User Gameplay Data PersistToCache completed with result: {result}"); } } } /// <summary> /// Creates a new bundle or updates BundleItems within a specific bundle for the calling user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name of userGameplayDataBundle is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY: At least one of the bundle keys of userGameplayData are malformed. If this error is received, Check the output log for more details on which item keys are not valid.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason. <br/> /// </summary> /// <param name="addUserGameplayDataDesc">Object containing a map of game play data to add</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void AddBundle(AddUserGameplayDataDesc addUserGameplayDataDesc, Action<AddUserGameplayDataResults> callback) { Call(Feature.AddUserGameplayData, addUserGameplayDataDesc, callback); } /// <summary> /// Applies the settings to the User Gameplay Data Client. Should be called immediately after the instance has been created and before any other API calls. /// </summary> /// <param name="userGameplayDataClientSettings">Object containing client settings</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void SetClientSettings(UserGameplayDataClientSettings userGameplayDataClientSettings, Action callback) { Call(Feature.SetUserGameplayDataClientSettings, userGameplayDataClientSettings, callback); } /// <summary> /// Lists the bundle name of every bundle that the calling user owns.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The response body from the backend could not be parsed successfully<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ListBundles(Action<MultiStringCallbackResult> callback) { Call(Feature.ListUserGameplayDataBundles, callback); } /// <summary> /// Gets all items that are associated with a certain bundle for the calling user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name of UserGameplayDataBundleName is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The response body from the backend could not be parsed successfully<br/> /// - GAMEKIT_ERROR_GENERAL: The bundle name does not exist or the request has failed for unknown reason.<br/> /// </summary> /// <param name="bundleName">Name of the data bundle items to fetch</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetBundle(string bundleName, Action<GetUserGameplayDataBundleResults> callback) { // Callback wrapper for zero bundles returned Call(Feature.GetUserGameplayDataBundle, bundleName, (GetUserGameplayDataBundleResults result) => { if (result.ResultCode == GameKitErrors.GAMEKIT_SUCCESS && result.Bundles.Count == 0) { Logging.LogError($"UserGameplayData.GetBundle() failed with result code {GameKitErrors.GAMEKIT_ERROR_GENERAL}. No bundles found with name {bundleName}"); result.ResultCode = GameKitErrors.GAMEKIT_ERROR_GENERAL; } callback.Invoke(result); }); } /// <summary> /// Gets a single item that is associated with a certain bundle for a user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name in userGameplayDataBundleItem is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY: The bundle key in userGameplayDataBundleItem is malformed. If this error is received, Check the output log for more details on which item keys are not valid.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="userGameplayDataBundleItem">Object containing needed inforamtion for fetching the bundle item</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetBundleItem(UserGameplayDataBundleItem userGameplayDataBundleItem, Action<StringCallbackResult> callback) { Call(Feature.GetUserGameplayDataBundleItem, userGameplayDataBundleItem, callback); } /// <summary> /// Updates the value of an existing item inside a bundle with new item data.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name in userGameplayDataBundleItem is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY: The bundle key in userGameplayDataBundleItem is malformed. If this error is received, Check the output log for more details on which item keys are not valid.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="userGameplayDataBundleItemValue">Object containing information for the bundle item update and what to update it with</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void UpdateItem(UserGameplayDataBundleItemValue userGameplayDataBundleItemValue, Action<uint> callback) { Call(Feature.UpdateUserGameplayDataBundleItem, userGameplayDataBundleItemValue, callback); } /// <summary> /// Permanently deletes all bundles associated with a user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void DeleteAllData(Action<uint> callback) { Call(Feature.DeleteAllUserGameplayData, callback); } /// <summary> /// Permanently deletes an entire bundle, along with all corresponding items, associated with a user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name in UserGameplayDataBundleName is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="bundleName">name of the bundle to delete</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> /// <returns>Unity JobHandle object for the call</returns> public void DeleteBundle(string bundleName, Action<uint> callback) { Call(Feature.DeleteUserGameplayDataBundle, bundleName, callback); } /// <summary> /// Permanently deletes a list of items inside of a bundle associated with a user.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED: The session manager does not have settings loaded in for the User Gameplay data feature.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME: The bundle name in userGameplayDataBundleItemsDeleteRequest is malformed. If this error is received, Check the output log for more details on requirements.<br/> /// - GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY: The bundle key in userGameplayDataBundleItemsDeleteRequest is malformed. If this error is received, Check the output log for more details on which item keys are not valid.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED: The call made to the backend service has failed.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED: The call made to the backend service has been dropped.<br/> /// - GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED: The call made to the backend service has been enqueued as connection may be unhealthy and will automatically be retried.<br/> /// - GAMEKIT_ERROR_GENERAL: The request has failed unknown reason.<br/> /// </summary> /// <param name="deleteUserGameplayDataBundleItemsDesc">Object containing the bundle and list of items to delete</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> /// <returns>Unity JobHandle object for the call</returns> public void DeleteBundleItems(DeleteUserGameplayDataBundleItemsDesc deleteUserGameplayDataBundleItemsDesc, Action<uint> callback) { Call(Feature.DeleteUserGameplayDataBundleItems, deleteUserGameplayDataBundleItemsDesc, callback); } /// <summary> /// Enables automatic offline mode, including persisting all failed calls in the retry thread to a cache file at the end of program.<br/><br/> /// If the cache needs to be persisted before the application is closed it is recommended to use StopRetryBackgroundThread() to stop the thread and PersistToCache to save the cache manually, then EnableAutomaticOfflineModeWithCaching can be restarted. <br/><br/> /// /// Note: Methods such as DropAllCachedEvents, SetNetworkChangeDelegate, SetCacheProcessedDelegate and SetClientSettings are not handled by this method and should be called independently. /// </summary> /// <param name="offlineCacheFile">The location of the offline cache file. All persisted calls in the cache will automatically be loaded into the queue. Any failed calls in the queue at the end of the program will be cached in this file.</param> public void EnableAutomaticOfflineModeWithCaching(string offlineCacheFile) { if (_isOfflineCacheRunning) { Logging.LogWarning("EnableAutomaticOfflineModeWithCaching: Background thread already running, ensure that the thread is stopped before attempting to start the retry thread again."); return; } _offlineCacheFile = offlineCacheFile; if (System.IO.File.Exists(_offlineCacheFile)) { LoadFromCache(offlineCacheFile, result => { Logging.LogInfo($"User Gameplay Data LoadFromCache completed with result: {result}"); StartRetryBackgroundThread(); }); } else { StartRetryBackgroundThread(); } } /// <summary> /// Start the Retry background thread.<br/><br/> /// /// The DestroyFeature() method, which is automatically called when the application is closing, will handle stopping the thread.<br/> /// However, if you need to persist the files during play it is recommended that you call StopRetryBackgroundThread() and Save/Load to Cache manually.<br/><br/> /// /// Note: If you are Caching your offline calls, StartRetryBackgroundThread() should be called after loading from cache. /// </summary> public void StartRetryBackgroundThread() { if (!_isOfflineCacheRunning) { _isOfflineCacheRunning = true; Feature.UserGameplayDataStartRetryBackgroundThread(); } } /// <summary> /// Stop the Retry background thread.<br/><br/> /// /// Note: If you are caching your offline calls, StopRetryBackgroundThread() should be called before saving to cache. /// </summary> public void StopRetryBackgroundThread() { if (_isOfflineCacheRunning) { Feature.UserGameplayDataStopRetryBackgroundThread(); _isOfflineCacheRunning = false; } } /// <summary> /// Return information about the running state of the background thread. /// </summary> /// <returns>True if it is running, false otherwise</returns> public bool IsBackgroundThreadRunning() { return _isOfflineCacheRunning; } /// <summary> /// Clear all pending events from the user's cache. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> /// <returns>Unity JobHandle object for the call</returns> public void DropAllCachedEvents(Action callback) { Call(Feature.UserGameplayDataDropAllCachedEvents, callback); } /// <summary> /// Set the callback to invoke when the network state changes. /// </summary> /// <param name="callback">Delegate that should be called whenever there is a network change.</param> public void SetNetworkChangeDelegate(NetworkChangedDelegate callback) { Feature.UserGameplayDataSetNetworkChangeCallback(callback); } /// <summary> /// Get the last known state of network connectivity. /// </summary> /// <returns>The last known state of connectivity. True means healthy, False means unhealthy</returns> public bool GetLastNetworkHealthState() { return Feature.GetLastNetworkHealthState(); } /// <summary> /// Set the callback to invoke when the offline cache finishes processing. /// </summary> /// <param name="callback">Delegate that should be called whenever there the cache has finished processing.</param> public void SetCacheProcessedDelegate(CacheProcessedDelegate callback) { Feature.UserGameplayDataSetCacheProcessedCallback(callback); } /// <summary> /// Write the pending API calls to cache.<br/><br/> /// /// Pending API calls are requests that could not be sent due to network being offline or other failures.<br/> /// The internal queue of pending calls is cleared. It is recommended to stop the background thread before calling this method.<br/><br/> /// /// This is the non-blocking version persist to cache call and should be used when saving during play, if you need to persist to cache on application close the blocking version, ImmediatePersistToCache() is recommended.<br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_WRITE_FAILED: There was an issue writing the queue to the offline cache file.<br/> /// </summary> /// <param name="offlineCacheFile">Path to the offline cache file.</param> /// <param name="callback">Delegate that is called once the function has finished executing.</param> /// <returns>Unity JobHandle object for the call</returns> public void PersistToCache(string offlineCacheFile, Action<uint> callback) { Call(Feature.UserGameplayDataPersistApiCallsToCache, offlineCacheFile, callback); } /// <summary> /// Write the pending API calls to cache.<br/><br/> /// /// Pending API calls are requests that could not be sent due to network being offline or other failures.<br/> /// The internal queue of pending calls is cleared. It is recommended to stop the background thread before calling this method.<br/><br/> /// /// This is the blocking version of the call and should be used on application close. PersistToCache() is recommended for saving to cache during play.<br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_WRITE_FAILED: There was an issue writing the queue to the offline cache file.<br/> /// </summary> /// <param name="offlineCacheFile">Path to the offline cache file.</param> /// <returns>The result code of persisting the queue to cache.</returns> public uint ImmediatePersistToCache(string offlineCacheFile) { return Feature.UserGameplayDataPersistApiCallsToCache(offlineCacheFile); } /// <summary> /// Read the pending API calls from cache.<br/><br/> /// /// The calls will be enqueued and retried as soon as the Retry background thread is started and network connectivity is up.<br/> /// The contents of the cache are deleted.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_READ_FAILED: There was an issue loading the offline cache file to the queue.<br/> /// </summary> /// <param name="offlineCacheFile">Path to the offline cache file.</param> /// <param name="callback">Delegate that is called once the function has finished executing.</param> /// <returns>Unity JobHandle object for the call</returns> public void LoadFromCache(string offlineCacheFile, Action<uint> callback) { Call(Feature.UserGameplayDataLoadApiCallsFromCache, offlineCacheFile, callback); } /// <summary> /// Forces an immediate retry of the calls that are in the queue. /// </summary> /// <remarks>The Network state can transiton from Unhealthy to Healthy as a side effect of this.</remarks> /// <param name="resultCallback">Callback invoked then the retry finishes. Returns success or failure.</param> public void ForceRetry(Action<bool> resultCallback) { Logging.LogInfo("Forcing a Retry to synchronize the data with the backend."); Feature.ForceRetry(resultCallback); } /// <summary> /// Attempts to synchronize data in the queue with the backend and, if successful, executes another User Gameplay Data API. /// Use this when you want to be sure that the data in the backend is updated before making subsequent calls. /// </summary> /// <param name="gameplayDataApiCall">The User Gameplay Data API to call (for example GetBundle(), GetBundleItem(), ListBundles(), or other APIs)</param> /// <param name="onErrorAction">Action to execute in case of error. Error can happen if the device is still offline or if the backend is experiencing problems.</param> public void TryForceSynchronizeAndExecute(Action gameplayDataApiCall, Action onSynchronizeErrorAction) { if (GetLastNetworkHealthState()) { gameplayDataApiCall(); } else { ForceRetry((bool success) => { if (success) { gameplayDataApiCall(); } else { onSynchronizeErrorAction(); } }); } } } }
510
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace AWS.GameKit.Runtime.Features.GameKitUserGameplayData { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncNetworkStatusChangeCallback(IntPtr dispatchReceiver, bool isConnectionOk, string connectionClient); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncCacheProcessedCallback(IntPtr dispatchReceiver, bool isCacheProcessed); [StructLayout(LayoutKind.Sequential)] public struct UserGameplayDataBundle { public string BundleName; public IntPtr BundleItemKeys; public IntPtr BundleItemValues; public IntPtr NumKeys; }; [StructLayout(LayoutKind.Sequential)] public struct UserGameplayDataBundleItem { public string BundleName; public string BundleItemKey; }; [StructLayout(LayoutKind.Sequential)] public struct UserGameplayDataBundleItemValue { public string BundleName; public string BundleItemKey; public string BundleItemValue; }; [StructLayout(LayoutKind.Sequential)] public struct UserGameplayDataDeleteItemsRequest { public string BundleName; public IntPtr BundleItemKeys; public IntPtr NumKeys; }; [StructLayout(LayoutKind.Sequential)] public struct UserGameplayDataClientSettings { public uint ClientTimeoutSeconds; public uint RetryIntervalSeconds; public uint MaxRetryQueueSize; public uint MaxRetries; public uint RetryStrategy; public uint MaxExponentialRetryThreshold; public uint PaginationSize; }; public class AddUserGameplayDataDesc { public string BundleName; public Dictionary<string, string> BundleItems = new Dictionary<string, string>(); }; public class AddUserGameplayDataResults { public uint ResultCode; public Dictionary<string, string> BundleItems = new Dictionary<string, string>(); } public class GetUserGameplayDataBundleResults { public uint ResultCode; public Dictionary<string, string> Bundles = new Dictionary<string, string>(); } public class DeleteUserGameplayDataBundleItemsDesc { public string BundleName; public string[] BundleItemKeys = new string[0]; public ulong NumKeys = 0; }; public class NetworkStatusChangeResults { public uint ResultCode; public bool IsConnectionOk; public string ConnectionClient; } public class CacheProcessedResults { public uint ResultCode; public bool IsCacheProcessed; } }
99
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.Features.GameKitUserGameplayData { /// <summary> /// User Gameplay Data wrapper for GameKit C++ SDK calls /// </summary> public class UserGameplayDataWrapper : GameKitFeatureWrapperBase { // Select the correct source path based on the platform #if UNITY_IPHONE && !UNITY_EDITOR private const string IMPORT = "__Internal"; #else private const string IMPORT = "aws-gamekit-user-gameplay-data"; #endif // Delegates protected static UserGameplayData.NetworkChangedDelegate _networkCallbackDelegate; protected static UserGameplayData.CacheProcessedDelegate _cacheProcessedDelegate; // Network state protected static bool _isNetworkHealthy = true; // DLL loading [DllImport(IMPORT)] private static extern IntPtr GameKitUserGameplayDataInstanceCreateWithSessionManager(IntPtr sessionManager, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern void GameKitUserGameplayDataInstanceRelease(IntPtr userGameplayDataInstance); [DllImport(IMPORT)] private static extern void GameKitSetUserGameplayDataClientSettings(IntPtr userGameplayDataInstance, UserGameplayDataClientSettings settings); [DllImport(IMPORT)] private static extern uint GameKitAddUserGameplayData(IntPtr userGameplayDataInstance, UserGameplayDataBundle userGameplayDataBundle, IntPtr unprocessedItemsReceiver, FuncKeyValueStringCallback unprocessedItemsCallback); [DllImport(IMPORT)] private static extern uint GameKitListUserGameplayDataBundles(IntPtr userGameplayDataInstance, IntPtr dispatchReceiver, FuncStringCallback responseCb); [DllImport(IMPORT)] private static extern uint GameKitGetUserGameplayDataBundle(IntPtr userGameplayDataInstance, string bundleName, IntPtr dispatchReceiver, FuncKeyValueStringCallback responseCb); [DllImport(IMPORT)] private static extern uint GameKitGetUserGameplayDataBundleItem(IntPtr userGameplayDataInstance, UserGameplayDataBundleItem userGameplayDataBundleItem, IntPtr dispatchReceiver, FuncStringCallback responseCb); [DllImport(IMPORT)] private static extern uint GameKitUpdateUserGameplayDataBundleItem(IntPtr userGameplayDataInstance, UserGameplayDataBundleItemValue userGameplayDataBundleItemValue); [DllImport(IMPORT)] private static extern uint GameKitDeleteAllUserGameplayData(IntPtr userGameplayDataInstance); [DllImport(IMPORT)] private static extern uint GameKitDeleteUserGameplayDataBundle(IntPtr userGameplayDataInstance, string bundleName); [DllImport(IMPORT)] private static extern uint GameKitDeleteUserGameplayDataBundleItems(IntPtr userGameplayDataInstance, UserGameplayDataDeleteItemsRequest deleteItemsRequest); [DllImport(IMPORT)] private static extern void GameKitUserGameplayDataStartRetryBackgroundThread(IntPtr userGameplayDataInstance); [DllImport(IMPORT)] private static extern void GameKitUserGameplayDataStopRetryBackgroundThread(IntPtr userGameplayDataInstance); [DllImport(IMPORT)] private static extern void GameKitUserGameplayDataSetNetworkChangeCallback(IntPtr userGameplayDataInstance, IntPtr dispatchReceiver, FuncNetworkStatusChangeCallback statusChangeCallback); [DllImport(IMPORT)] private static extern void GameKitUserGameplayDataSetCacheProcessedCallback(IntPtr userGameplayDataInstance, IntPtr dispatchReceiver, FuncCacheProcessedCallback cacheProcessedCallback); [DllImport(IMPORT)] private static extern void GameKitUserGameplayDataDropAllCachedEvents(IntPtr userGameplayDataInstance); [DllImport(IMPORT)] private static extern uint GameKitUserGameplayDataPersistApiCallsToCache(IntPtr userGameplayDataInstance, string offlineCacheFile); [DllImport(IMPORT)] private static extern uint GameKitUserGameplayDataLoadApiCallsFromCache(IntPtr userGameplayDataInstance, string offlineCacheFile); [AOT.MonoPInvokeCallback(typeof(FuncNetworkStatusChangeCallback))] protected static void NetworkStatusChangeCallback(IntPtr dispatchReceiver, bool isConnectionOk, string connectionClient) { NetworkStatusChangeResults results = new NetworkStatusChangeResults(); results.IsConnectionOk = isConnectionOk; results.ConnectionClient = connectionClient; results.ResultCode = GameKitErrors.GAMEKIT_SUCCESS; _isNetworkHealthy = isConnectionOk; _networkCallbackDelegate(results); } [AOT.MonoPInvokeCallback(typeof(FuncCacheProcessedCallback))] protected static void CacheProcessedCallback(IntPtr dispatchReceiver, bool isCacheProcessed) { CacheProcessedResults results = new CacheProcessedResults(); results.IsCacheProcessed = isCacheProcessed; results.ResultCode = GameKitErrors.GAMEKIT_SUCCESS; _cacheProcessedDelegate(results); } public void SetUserGameplayDataClientSettings(UserGameplayDataClientSettings settings) { DllLoader.TryDll(() => GameKitSetUserGameplayDataClientSettings(GetInstance(), settings), nameof(GameKitSetUserGameplayDataClientSettings)); } public AddUserGameplayDataResults AddUserGameplayData(AddUserGameplayDataDesc addUserGameplayDataDesc) { IntPtr[] bundleItemKeys = Marshaller.ArrayOfStringsToArrayOfIntPtr(addUserGameplayDataDesc.BundleItems.Keys.ToArray()); IntPtr[] bundleItemValues = Marshaller.ArrayOfStringsToArrayOfIntPtr(addUserGameplayDataDesc.BundleItems.Values.ToArray()); GCHandle bundleItemKeysPin = GCHandle.Alloc(bundleItemKeys, GCHandleType.Pinned); GCHandle bundleItemValuesPin = GCHandle.Alloc(bundleItemValues, GCHandleType.Pinned); UserGameplayDataBundle userGameplayDataBundle; userGameplayDataBundle.BundleName = addUserGameplayDataDesc.BundleName; userGameplayDataBundle.NumKeys = (IntPtr)addUserGameplayDataDesc.BundleItems.Count; userGameplayDataBundle.BundleItemKeys = bundleItemKeysPin.AddrOfPinnedObject(); userGameplayDataBundle.BundleItemValues = bundleItemValuesPin.AddrOfPinnedObject(); MultiKeyValueStringCallbackResult callbackResults = new MultiKeyValueStringCallbackResult(); uint status = GameKitErrors.GAMEKIT_ERROR_GENERAL; try { status = DllLoader.TryDll(callbackResults, (IntPtr dispatchReceiver) => GameKitAddUserGameplayData(GetInstance(), userGameplayDataBundle, dispatchReceiver, GameKitCallbacks.MultiKeyValueStringCallback), nameof(GameKitAddUserGameplayData), GameKitErrors.GAMEKIT_ERROR_GENERAL); } finally { bundleItemKeysPin.Free(); bundleItemValuesPin.Free(); Marshaller.FreeArrayOfIntPtr(bundleItemKeys); Marshaller.FreeArrayOfIntPtr(bundleItemValues); } AddUserGameplayDataResults results = new AddUserGameplayDataResults(); for (uint i = 0; i < callbackResults.ResponseKeys.Count(); ++i) { results.BundleItems.Add(callbackResults.ResponseKeys[i], callbackResults.ResponseValues[i]); } results.ResultCode = status; return results; } public MultiStringCallbackResult ListUserGameplayDataBundles() { MultiStringCallbackResult results = new MultiStringCallbackResult(); uint status = DllLoader.TryDll(results, (IntPtr dispatchReceiver) => GameKitListUserGameplayDataBundles(GetInstance(), dispatchReceiver, GameKitCallbacks.MultiStringCallback), nameof(GameKitListUserGameplayDataBundles), GameKitErrors.GAMEKIT_ERROR_GENERAL); results.ResultCode = status; return results; } public GetUserGameplayDataBundleResults GetUserGameplayDataBundle(string bundleName) { MultiKeyValueStringCallbackResult callbackResults = new MultiKeyValueStringCallbackResult(); uint status = DllLoader.TryDll(callbackResults, (IntPtr dispatchReceiver) => GameKitGetUserGameplayDataBundle(GetInstance(), bundleName, dispatchReceiver, GameKitCallbacks.MultiKeyValueStringCallback), nameof(GameKitGetUserGameplayDataBundle), GameKitErrors.GAMEKIT_ERROR_GENERAL); GetUserGameplayDataBundleResults results = new GetUserGameplayDataBundleResults(); for (uint i = 0; i < callbackResults.ResponseKeys.Count(); ++i) { results.Bundles.Add(callbackResults.ResponseKeys[i], callbackResults.ResponseValues[i]); } results.ResultCode = status; return results; } public StringCallbackResult GetUserGameplayDataBundleItem(UserGameplayDataBundleItem userGameplayDataBundleItem) { StringCallbackResult results = new StringCallbackResult(); uint status = DllLoader.TryDll(results, (IntPtr dispatchReceiver) => GameKitGetUserGameplayDataBundleItem(GetInstance(), userGameplayDataBundleItem, dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitGetUserGameplayDataBundleItem), GameKitErrors.GAMEKIT_ERROR_GENERAL); results.ResultCode = status; return results; } public uint UpdateUserGameplayDataBundleItem(UserGameplayDataBundleItemValue userGameplayDataBundleItemValue) { return DllLoader.TryDll(() => GameKitUpdateUserGameplayDataBundleItem(GetInstance(), userGameplayDataBundleItemValue), nameof(GameKitUpdateUserGameplayDataBundleItem), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint DeleteAllUserGameplayData() { return DllLoader.TryDll(() => GameKitDeleteAllUserGameplayData(GetInstance()), nameof(GameKitDeleteAllUserGameplayData), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint DeleteUserGameplayDataBundle(string bundleName) { return DllLoader.TryDll(() => GameKitDeleteUserGameplayDataBundle(GetInstance(), bundleName), nameof(GameKitDeleteUserGameplayDataBundle), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint DeleteUserGameplayDataBundleItems(DeleteUserGameplayDataBundleItemsDesc deleteUserGameplayDataBundleItemsDesc) { IntPtr[] bundleItemKeys = Marshaller.ArrayOfStringsToArrayOfIntPtr(deleteUserGameplayDataBundleItemsDesc.BundleItemKeys); GCHandle bundleKeysPin = GCHandle.Alloc(bundleItemKeys, GCHandleType.Pinned); UserGameplayDataDeleteItemsRequest userGameplayDataDeleteItemsRequest = new UserGameplayDataDeleteItemsRequest(); userGameplayDataDeleteItemsRequest.BundleName = deleteUserGameplayDataBundleItemsDesc.BundleName; userGameplayDataDeleteItemsRequest.NumKeys = (IntPtr)deleteUserGameplayDataBundleItemsDesc.NumKeys; userGameplayDataDeleteItemsRequest.BundleItemKeys = bundleKeysPin.AddrOfPinnedObject(); try { return DllLoader.TryDll(() => GameKitDeleteUserGameplayDataBundleItems(GetInstance(), userGameplayDataDeleteItemsRequest), nameof(GameKitDeleteUserGameplayDataBundleItems), GameKitErrors.GAMEKIT_ERROR_GENERAL); } finally { bundleKeysPin.Free(); Marshaller.FreeArrayOfIntPtr(bundleItemKeys); } } public void UserGameplayDataStartRetryBackgroundThread() { DllLoader.TryDll(() => GameKitUserGameplayDataStartRetryBackgroundThread(GetInstance()), nameof(GameKitUserGameplayDataStartRetryBackgroundThread)); } public void UserGameplayDataStopRetryBackgroundThread() { DllLoader.TryDll(() => GameKitUserGameplayDataStopRetryBackgroundThread(GetInstance()), nameof(GameKitUserGameplayDataStopRetryBackgroundThread)); } public void ForceRetry(Action<bool> callback) { UserGameplayDataStopRetryBackgroundThread(); UserGameplayData.NetworkChangedDelegate tempNetworkChangeDelegate = null; tempNetworkChangeDelegate = (NetworkStatusChangeResults results) => { // This temporary delegate must unsubscribe itself otherwise the captured // objects could remain in memory longer than needed. _networkCallbackDelegate -= tempNetworkChangeDelegate; callback(results.IsConnectionOk); }; _networkCallbackDelegate += tempNetworkChangeDelegate; UserGameplayDataStartRetryBackgroundThread(); } public void UserGameplayDataSetNetworkChangeCallback(UserGameplayData.NetworkChangedDelegate networkChangeDelegate) { _networkCallbackDelegate += networkChangeDelegate; DllLoader.TryDll(() => GameKitUserGameplayDataSetNetworkChangeCallback(GetInstance(), IntPtr.Zero, NetworkStatusChangeCallback), nameof(GameKitUserGameplayDataSetNetworkChangeCallback)); } public bool GetLastNetworkHealthState() { return _isNetworkHealthy; } public void UserGameplayDataSetCacheProcessedCallback(UserGameplayData.CacheProcessedDelegate cacheProcessedDelegate) { _cacheProcessedDelegate = cacheProcessedDelegate; DllLoader.TryDll(() => GameKitUserGameplayDataSetCacheProcessedCallback(GetInstance(), IntPtr.Zero, CacheProcessedCallback), nameof(GameKitUserGameplayDataSetCacheProcessedCallback)); } public void UserGameplayDataDropAllCachedEvents() { DllLoader.TryDll(() => GameKitUserGameplayDataDropAllCachedEvents(GetInstance()), nameof(GameKitUserGameplayDataDropAllCachedEvents)); } public uint UserGameplayDataPersistApiCallsToCache(string offlineCacheFile) { return DllLoader.TryDll(() => GameKitUserGameplayDataPersistApiCallsToCache(GetInstance(), offlineCacheFile), nameof(GameKitUserGameplayDataPersistApiCallsToCache), GameKitErrors.GAMEKIT_ERROR_GENERAL); } public uint UserGameplayDataLoadApiCallsFromCache(string offlineCacheFile) { return DllLoader.TryDll(() => GameKitUserGameplayDataLoadApiCallsFromCache(GetInstance(), offlineCacheFile), nameof(GameKitUserGameplayDataLoadApiCallsFromCache), GameKitErrors.GAMEKIT_ERROR_GENERAL); } protected override IntPtr Create(IntPtr sessionManager, FuncLoggingCallback logCb) { return DllLoader.TryDll(() => GameKitUserGameplayDataInstanceCreateWithSessionManager(sessionManager, logCb), nameof(GameKitUserGameplayDataInstanceCreateWithSessionManager), IntPtr.Zero); } protected override void Release(IntPtr instance) { DllLoader.TryDll(() => GameKitUserGameplayDataInstanceRelease(instance), nameof(GameKitUserGameplayDataInstanceRelease)); } } }
270
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.Runtime.InteropServices; namespace AWS.GameKit.Runtime.Models { [StructLayout(LayoutKind.Sequential)] public struct AccountCredentials { public string Region; public string AccessKey; public string AccessSecret; public string AccountId; }; [StructLayout(LayoutKind.Sequential)] public struct AccountCredentialsCopy { public string Region; public string AccessKey; public string AccessSecret; public string ShortRegionCode; public string AccountId; }; [StructLayout(LayoutKind.Sequential)] public struct GetAWSAccountIdDescription { public string AccessKey; public string AccessSecret; }; }
36
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.Runtime.InteropServices; namespace AWS.GameKit.Runtime.Models { [StructLayout(LayoutKind.Sequential)] public struct AccountInfo { public string Environment; public string AccountId; public string CompanyName; public string GameName; }; }
18
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Runtime.Models { public static class Constants { public static class EnvironmentCodes { public const string DEVELOPMENT = "dev"; public const string QA = "qa"; public const string STAGING = "stg"; public const string PRODUCTION = "prd"; }; } }
17
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard using System; using System.Collections.Generic; // GameKit using AWS.GameKit.Common.Models; namespace AWS.GameKit.Runtime.Models { public class DeploymentResponseCallbackResult { public uint ResultCode; public FeatureType[] Features = new FeatureType[0]; public FeatureStatus[] FeatureStatuses = new FeatureStatus[0]; } public class DeploymentResponseResult { public uint ResultCode; public Dictionary<FeatureType, FeatureStatus> FeatureStatuses = new Dictionary<FeatureType, FeatureStatus>(); } public class SetCredentialsDesc { public AccountInfo AccountInfo; public AccountCredentials AccountCredentials; } public class CanExecuteDeploymentActionResult { public FeatureType TargetFeature; public bool CanExecuteAction; public DeploymentActionBlockedReason Reason; public FeatureType[] BlockingFeatures = new FeatureType[0]; } }
40
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // GameKit using AWS.GameKit.Common.Models; namespace AWS.GameKit.Runtime.Models { public class FeatureStatusSetDesc { public FeatureType FeatureType; public FeatureStatus Status; } }
15
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.Runtime.InteropServices; namespace AWS.GameKit.Runtime.Models { [StructLayout(LayoutKind.Sequential)] public class StringCallbackResult { public uint ResultCode; public string ResponseValue = string.Empty; } [StructLayout(LayoutKind.Sequential)] public class KeyValueStringCallbackResult { public uint ResultCode; public string ResponseKey = string.Empty; public string ResponseValue = string.Empty; } [StructLayout(LayoutKind.Sequential)] public class ResourceInfoCallbackResult { public uint ResultCode; public string LogicalResourceId = string.Empty; public string ResourceType = string.Empty; public string ResourceStatus = string.Empty; } [StructLayout(LayoutKind.Sequential)] public class MultiResourceInfoCallbackResult { public uint ResultCode; public string[] LogicalResourceId = new string[0]; public string[] ResourceType = new string[0]; public string[] ResourceStatus = new string[0]; } [StructLayout(LayoutKind.Sequential)] public class MultiKeyValueStringCallbackResult { public uint ResultCode; public string[] ResponseKeys = new string[0]; public string[] ResponseValues = new string[0]; } [StructLayout(LayoutKind.Sequential)] public class MultiStringCallbackResult { public uint ResultCode; public string[] ResponseValues = new string[0]; } }
57
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.Models { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncLoggingCallback(uint level, string message, int size); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncStringCallback(IntPtr dispatchReceiver, string responseValue); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncKeyValueStringCallback(IntPtr dispatchReceiver, string responseKey, string responseValue); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncResourceInfoCallback(IntPtr dispatchReceiver, string logicalResourceId, string resourceType, string resourceStatus); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncDeploymentResponseCallback(IntPtr dispatchReceiver, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] FeatureType[] features, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] FeatureStatus[] featureStatuses, uint featureCount, uint callStatus); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FuncCanExecuteDeploymentActionCallback(IntPtr dispatchReceiver, FeatureType targetFeature, [MarshalAs(UnmanagedType.U1)] bool canExecuteAction, DeploymentActionBlockedReason reason, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] FeatureType[] blockingFeatures, uint featureCount); public static class GameKitCallbacks { [AOT.MonoPInvokeCallback(typeof(FuncKeyValueStringCallback))] public static void KeyValueStringCallback(IntPtr dispatchReceiver, string responseKey, string responseValue) { // recover object reference from dispatchReceiver KeyValueStringCallbackResult result = Marshaller.GetDispatchObject<KeyValueStringCallbackResult>(dispatchReceiver); // handle assignments to the result object result.ResponseKey = responseKey; result.ResponseValue = responseValue; } [AOT.MonoPInvokeCallback(typeof(FuncKeyValueStringCallback))] public static void MultiKeyValueStringCallback(IntPtr dispatchReceiver, string responseKey, string responseValue) { // recover object reference from dispatchReceiver MultiKeyValueStringCallbackResult result = Marshaller.GetDispatchObject<MultiKeyValueStringCallbackResult>(dispatchReceiver); // handle assignments to the result object Marshaller.AppendToArray(ref result.ResponseKeys, responseKey); Marshaller.AppendToArray(ref result.ResponseValues, responseValue); } [AOT.MonoPInvokeCallback(typeof(FuncStringCallback))] public static void RecurringCallStringCallback(IntPtr dispatchReceiver, string responseValue) { // recover callback delegate from dispatchReceiver Action<StringCallbackResult> resultCallback = Marshaller.GetDispatchObject<Action<StringCallbackResult>>(dispatchReceiver); // create a temporary struct to hold the result StringCallbackResult result = new StringCallbackResult(); // handle assignments to the result object result.ResponseValue = responseValue; // call the callback and pass it the result resultCallback(result); } [AOT.MonoPInvokeCallback(typeof(FuncStringCallback))] public static void StringCallback(IntPtr dispatchReceiver, string responseValue) { // recover object reference from dispatchReceiver StringCallbackResult result = Marshaller.GetDispatchObject<StringCallbackResult>(dispatchReceiver); // handle assignments to the result object result.ResponseValue = responseValue; } [AOT.MonoPInvokeCallback(typeof(FuncStringCallback))] public static void MultiStringCallback(IntPtr dispatchReceiver, string responseValue) { // recover object reference from dispatchReceiver MultiStringCallbackResult result = Marshaller.GetDispatchObject<MultiStringCallbackResult>(dispatchReceiver); // handle assignments to the result object Marshaller.AppendToArray(ref result.ResponseValues, responseValue); } [AOT.MonoPInvokeCallback(typeof(FuncResourceInfoCallback))] public static void ResourceInfoCallback(IntPtr dispatchReceiver, string logicalResourceId, string resourceType, string resourceStatus) { // recover object reference from dispatchReceiver ResourceInfoCallbackResult result = Marshaller.GetDispatchObject<ResourceInfoCallbackResult>(dispatchReceiver); // handle assignments to the result object result.LogicalResourceId = logicalResourceId; result.ResourceType = resourceType; result.ResourceStatus = resourceStatus; } [AOT.MonoPInvokeCallback(typeof(FuncResourceInfoCallback))] public static void MultiResourceInfoCallback(IntPtr dispatchReceiver, string logicalResourceId, string resourceType, string resourceStatus) { // recover object reference from dispatchReceiver MultiResourceInfoCallbackResult result = Marshaller.GetDispatchObject<MultiResourceInfoCallbackResult>(dispatchReceiver); // handle assignments to the result object Marshaller.AppendToArray(ref result.LogicalResourceId, logicalResourceId); Marshaller.AppendToArray(ref result.ResourceType, resourceType); Marshaller.AppendToArray(ref result.ResourceStatus, resourceStatus); } [AOT.MonoPInvokeCallback(typeof(FuncDeploymentResponseCallback))] public static void DeploymentResponseCallback(IntPtr dispatchReceiver, FeatureType[] features, FeatureStatus[] featureStatuses, uint featureCount, uint callStatus) { // recover object reference from dispatchReceiver DeploymentResponseCallbackResult result = Marshaller.GetDispatchObject<DeploymentResponseCallbackResult>(dispatchReceiver); // handle assignments to the result object result.Features = features; result.FeatureStatuses = featureStatuses; // copy the GK Error status result.ResultCode = callStatus; } [AOT.MonoPInvokeCallback(typeof(FuncCanExecuteDeploymentActionCallback))] public static void CanExecuteDeploymentActionCallback(IntPtr dispatchReceiver, FeatureType targetFeature, bool canExecuteAction, DeploymentActionBlockedReason reason, FeatureType[] blockingFeatures, uint featureCount) { // recover object reference from dispatchReceiver CanExecuteDeploymentActionResult result = Marshaller.GetDispatchObject<CanExecuteDeploymentActionResult>(dispatchReceiver); // handle assignments to the result object result.TargetFeature = targetFeature; result.CanExecuteAction = canExecuteAction; result.Reason = reason; result.BlockingFeatures = blockingFeatures; } } }
144
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Runtime.Models { [Serializable] public class JsonResponse<T> { public T data; } }
14
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Runtime.Models { public enum DeploymentActionBlockedReason : uint { NotBlocked = 0, FeatureMustBeCreated, FeatureMustBeDeleted, FeatureStatusIsUnknown, OngoingDeployments, DependenciesMustBeCreated, DependenciesMustBeDeleted, DependenciesStatusIsInvalid, CredentialsInvalid, MainStackNotReady } }
20
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Linq; namespace AWS.GameKit.Runtime.Models { public static class EnumExtensions { public static TAttribute GetAttribute<TAttribute>(this Enum value) where TAttribute : Attribute { Type enumType = value.GetType(); string name = Enum.GetName(enumType, value); return enumType.GetField(name).GetCustomAttributes(false).OfType<TAttribute>().SingleOrDefault(); } } }
21
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Runtime.Models { public enum FeatureStatus { [FeatureStatusData(displayName: "Deployed")] Deployed, [FeatureStatusData(displayName: "Undeployed")] Undeployed, [FeatureStatusData(displayName: "Error")] Error, [FeatureStatusData(displayName: "Rollback Complete")] RollbackComplete, [FeatureStatusData(displayName: "Running")] Running, [FeatureStatusData(displayName: "Generating Templates")] GeneratingTemplates, [FeatureStatusData(displayName: "Uploading Dashboards")] UploadingDashboards, [FeatureStatusData(displayName: "Uploading Layers")] UploadingLayers, [FeatureStatusData(displayName: "Uploading Functions")] UploadingFunctions, [FeatureStatusData(displayName: "Deploying Resources")] DeployingResources, [FeatureStatusData(displayName: "Deleting Resources")] DeletingResources, [FeatureStatusData(displayName: "Unknown")] Unknown, }; [AttributeUsage(AttributeTargets.Field)] public class FeatureStatusData : Attribute { public readonly string DisplayName; public FeatureStatusData(string displayName) { DisplayName = displayName; } } /// <summary> /// Extension methods for <c>FeatureStatus</c> which give access to it's enum metadata. /// </summary> /// <example> /// This shows how to use the extension methods. /// <code> /// // On the enum class: /// FeatureStatus.Undeployed.GetDisplayName(); /// /// // On an enum variable: /// FeatureStatus myStatus = FeatureStatus.Deployed /// myStatus.GetDisplayName(); /// </code> /// </example> public static class FeatureStatusConverter { public static string GetDisplayName(this FeatureStatus status) { return status.GetAttribute<FeatureStatusData>().DisplayName; } } public enum FeatureStatusSummary { Deployed = 0, Undeployed, Error, Running, Unknown }; }
89
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Runtime.Models { public enum TemplateType { Base, Instance }; }
11
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Runtime.Models { public enum TokenType : uint { AccessToken, RefreshToken, IdToken, IamSessionToken, // TokenType_COUNT should be the last item in the enum, it is used for providing the total number of enums TokenType_COUNT } }
17
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.Collections.Generic; using System.IO; // AWS GameKit using AWS.GameKit.Common; // Third Party using Newtonsoft.Json; namespace AWS.GameKit.Runtime.Utils { public static class AwsGameKitPersistentSettings { // Note: Application.dataPath is not available before scriptable objects have initialized private static readonly string SETTINGS_FILE_DIRECTORY = GameKitPaths.Get().ASSETS_EDITOR_RESOURCES_FULL_PATH; private static readonly string SETTINGS_FILE_PATH = Path.Combine(SETTINGS_FILE_DIRECTORY, "AwsGameKitPersistentSettings.json"); private static Dictionary<string, string> _settings = new Dictionary<string, string>(); static AwsGameKitPersistentSettings() { #if UNITY_EDITOR if (File.Exists(SETTINGS_FILE_PATH)) { string toImport = File.ReadAllText(SETTINGS_FILE_PATH); _settings = JsonConvert.DeserializeObject<Dictionary<string, string>> (toImport); } #endif } public static void Delete(string key) { _settings.Remove(key); SaveToFile(); } public static void SaveString(string key, string value) { _settings[key] = value; SaveToFile(); } public static void SaveBool(string key, bool value) { SaveString(key, value.ToString()); } public static void SaveInt(string key, int value) { SaveString(key, value.ToString()); } public static string LoadString(string key, string defaultValue) { string value; if (_settings.TryGetValue(key, out value)) { return value; } return defaultValue; } public static bool LoadBool(string key, bool defaultValue) { return bool.Parse(LoadString(key, defaultValue.ToString())); } public static int LoadInt(string key, int defaultValue) { return int.Parse(LoadString(key, defaultValue.ToString())); } private static void SaveToFile() { #if UNITY_EDITOR string toExport = JsonConvert.SerializeObject(_settings, Formatting.Indented); if (!Directory.Exists(SETTINGS_FILE_DIRECTORY)) { Directory.CreateDirectory(SETTINGS_FILE_DIRECTORY); } File.WriteAllText(SETTINGS_FILE_PATH, toExport); #endif } } }
95
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Runtime.Utils { /// <summary> /// Class to help with calling exported DLL functions. /// </summary> public static class DllLoader { /// <summary> /// Tries to call imported DLL method. Logs Dll Exception if unsuccessful. /// </summary> /// <param name="importedMethod">The imported method to call.</param> /// <param name="dllName">Name of the dll the method is in.</param> public static void TryDll(Action importedMethod, string dllName) { try { importedMethod(); } catch (Exception e) { LogDllException(e, dllName); } } /// <summary> /// Tries to call imported DLL method. Logs Dll Exception if unsuccessful. /// </summary> /// <param name="importedMethod">The imported method to call.</param> /// <param name="dllName">Name of the dll the method is in.</param> public static T TryDll<T>(Func<T> importedMethod, string dllName, T returnOnError) { try { return importedMethod(); } catch (Exception e) { LogDllException(e, dllName); return returnOnError; } } /// <summary> /// Tries to call imported DLL method. Logs Dll Exception if unsuccessful. /// </summary> /// <param name="importedMethod">The imported method to call.</param> /// <param name="dllName">Name of the dll the method is in.</param> /// <param name="dispatchReceiver">The object this method is called on.</param> public static void TryDll(object dispatchReceiver, Action<IntPtr> importedMethod, string dllName) { Marshaller.Dispatch(dispatchReceiver, (IntPtr handle) => { try { importedMethod(handle); } catch (Exception e) { LogDllException(e, dllName); } }); } /// <summary> /// Tries to call imported DLL method. Logs Dll Exception if unsuccessful. /// </summary> /// <param name="importedMethod">The imported method to call.</param> /// <param name="dllName">Name of the dll the method is in.</param> /// <param name="dispatchReceiver">The object this method is called on.</param> public static T TryDll<T>(object dispatchReceiver, Func<IntPtr, T> importedMethod, string dllName, T returnOnError) { return Marshaller.Dispatch(dispatchReceiver, (IntPtr handle) => { try { return importedMethod(handle); } catch (Exception e) { LogDllException(e, dllName); return returnOnError; } }); } private static void LogDllException(Exception e, string dllName) { if (e is DllNotFoundException || e is EntryPointNotFoundException) { Logging.LogException($"{dllName} DLL not linked", e); } else { Logging.LogException("Unable to make call to DLL imported method, {}, ", e); } } } }
108
aws-gamekit-unity
aws
C#
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This was generated by a script, do not modify! // Standard Library using System.Collections.Generic; // GameKit using AWS.GameKit.Runtime.Core; namespace AWS.GameKit.Runtime.Utils { /// <summary> /// Matches each GameKit error code to a string so they can be converted into a more helpful string. /// </summary> public static class GameKitErrorConverter { private static IReadOnlyDictionary<uint, string> RESULT_CODE_TO_NAME = new Dictionary<uint, string> { { GameKitErrors.GAMEKIT_SUCCESS, nameof(GameKitErrors.GAMEKIT_SUCCESS) }, { GameKitErrors.GAMEKIT_ERROR_INVALID_PROVIDER, nameof(GameKitErrors.GAMEKIT_ERROR_INVALID_PROVIDER) }, { GameKitErrors.GAMEKIT_ERROR_PARAMETERS_FILE_SAVE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_PARAMETERS_FILE_SAVE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_FILE_SAVE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_FILE_SAVE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_SETTINGS_FILE_SAVE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_SETTINGS_FILE_SAVE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_NO_ID_TOKEN, nameof(GameKitErrors.GAMEKIT_ERROR_NO_ID_TOKEN) }, { GameKitErrors.GAMEKIT_ERROR_HTTP_REQUEST_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_HTTP_REQUEST_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_PARSE_JSON_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_PARSE_JSON_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_SIGN_REQUEST_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_SIGN_REQUEST_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_SETTINGS_FILE_READ_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_FILE_OPEN_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_FILE_OPEN_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_FILE_WRITE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_FILE_WRITE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_FILE_READ_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_FILE_READ_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_DIRECTORY_CREATE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_DIRECTORY_CREATE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_DIRECTORY_NOT_FOUND, nameof(GameKitErrors.GAMEKIT_ERROR_DIRECTORY_NOT_FOUND) }, { GameKitErrors.GAMEKIT_ERROR_FUNCTIONS_COPY_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_FUNCTIONS_COPY_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_METHOD_NOT_IMPLEMENTED, nameof(GameKitErrors.GAMEKIT_ERROR_METHOD_NOT_IMPLEMENTED) }, { GameKitErrors.GAMEKIT_ERROR_GENERAL, nameof(GameKitErrors.GAMEKIT_ERROR_GENERAL) }, { GameKitErrors.GAMEKIT_ERROR_REGION_CODE_CONVERSION_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_REGION_CODE_CONVERSION_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CREDENTIALS_FILE_NOT_FOUND, nameof(GameKitErrors.GAMEKIT_ERROR_CREDENTIALS_FILE_NOT_FOUND) }, { GameKitErrors.GAMEKIT_ERROR_CREDENTIALS_FILE_SAVE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CREDENTIALS_FILE_SAVE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CREDENTIALS_NOT_FOUND, nameof(GameKitErrors.GAMEKIT_ERROR_CREDENTIALS_NOT_FOUND) }, { GameKitErrors.GAMEKIT_ERROR_CREDENTIALS_FILE_MALFORMED, nameof(GameKitErrors.GAMEKIT_ERROR_CREDENTIALS_FILE_MALFORMED) }, { GameKitErrors.GAMEKIT_ERROR_REQUEST_TIMED_OUT, nameof(GameKitErrors.GAMEKIT_ERROR_REQUEST_TIMED_OUT) }, { GameKitErrors.GAMEKIT_ERROR_SETTINGS_MISSING, nameof(GameKitErrors.GAMEKIT_ERROR_SETTINGS_MISSING) }, { GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_BUCKET_LOOKUP_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_BUCKET_LOOKUP_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_BUCKET_CREATION_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_BUCKET_CREATION_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_INVALID_REGION_CODE, nameof(GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_INVALID_REGION_CODE) }, { GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_MISSING_PLUGIN_ROOT, nameof(GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_MISSING_PLUGIN_ROOT) }, { GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_REGION_CODE_CONVERSION_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_REGION_CODE_CONVERSION_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_FUNCTIONS_PATH_NOT_FOUND, nameof(GameKitErrors.GAMEKIT_ERROR_FUNCTIONS_PATH_NOT_FOUND) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_PATH_NOT_FOUND, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_PATH_NOT_FOUND) }, { GameKitErrors.GAMEKIT_ERROR_FUNCTION_ZIP_INIT_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_FUNCTION_ZIP_INIT_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_FUNCTION_ZIP_WRITE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_FUNCTION_ZIP_WRITE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_PARAMSTORE_WRITE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_PARAMSTORE_WRITE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_BUCKET_UPLOAD_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_BOOTSTRAP_BUCKET_UPLOAD_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_SECRETSMANAGER_WRITE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_SECRETSMANAGER_WRITE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_STACK_CREATION_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_STACK_CREATION_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_STACK_UPDATE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_STACK_UPDATE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_RESOURCE_CREATION_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_RESOURCE_CREATION_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_STACK_DELETE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_STACK_DELETE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_DESCRIBE_RESOURCE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_DESCRIBE_RESOURCE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_DESCRIBE_STACKS_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_DESCRIBE_STACKS_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_APIGATEWAY_DEPLOYMENT_CREATION_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_APIGATEWAY_DEPLOYMENT_CREATION_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_APIGATEWAY_STAGE_DEPLOYMENT_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_APIGATEWAY_STAGE_DEPLOYMENT_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_LAYERS_PATH_NOT_FOUND, nameof(GameKitErrors.GAMEKIT_ERROR_LAYERS_PATH_NOT_FOUND) }, { GameKitErrors.GAMEKIT_ERROR_LAYER_ZIP_INIT_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_LAYER_ZIP_INIT_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_LAYER_ZIP_WRITE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_LAYER_ZIP_WRITE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_LAYER_CREATION_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_LAYER_CREATION_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_GET_TEMPLATE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_GET_TEMPLATE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_PARAMSTORE_READ_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_PARAMSTORE_READ_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_NO_CURRENT_STACK_STATUS, nameof(GameKitErrors.GAMEKIT_ERROR_CLOUDFORMATION_NO_CURRENT_STACK_STATUS) }, { GameKitErrors.GAMEKIT_ERROR_REGISTER_USER_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_REGISTER_USER_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CONFIRM_REGISTRATION_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CONFIRM_REGISTRATION_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_RESEND_CONFIRMATION_CODE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_RESEND_CONFIRMATION_CODE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_LOGIN_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_LOGIN_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_FORGOT_PASSWORD_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_FORGOT_PASSWORD_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_CONFIRM_FORGOT_PASSWORD_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_CONFIRM_FORGOT_PASSWORD_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_LOGOUT_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_LOGOUT_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_MALFORMED_USERNAME, nameof(GameKitErrors.GAMEKIT_ERROR_MALFORMED_USERNAME) }, { GameKitErrors.GAMEKIT_ERROR_MALFORMED_PASSWORD, nameof(GameKitErrors.GAMEKIT_ERROR_MALFORMED_PASSWORD) }, { GameKitErrors.GAMEKIT_ERROR_INVALID_FEDERATED_IDENTITY_PROVIDER, nameof(GameKitErrors.GAMEKIT_ERROR_INVALID_FEDERATED_IDENTITY_PROVIDER) }, { GameKitErrors.GAMEKIT_ERROR_ACHIEVEMENTS_ICON_UPLOAD_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_ACHIEVEMENTS_ICON_UPLOAD_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_ACHIEVEMENTS_INVALID_ID, nameof(GameKitErrors.GAMEKIT_ERROR_ACHIEVEMENTS_INVALID_ID) }, { GameKitErrors.GAMEKIT_ERROR_ACHIEVEMENTS_PAYLOAD_TOO_LARGE, nameof(GameKitErrors.GAMEKIT_ERROR_ACHIEVEMENTS_PAYLOAD_TOO_LARGE) }, { GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_PAYLOAD_INVALID, nameof(GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_PAYLOAD_INVALID) }, { GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED, nameof(GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_API_CALL_DROPPED) }, { GameKitErrors.GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED, nameof(GameKitErrors.GAMEKIT_WARNING_USER_GAMEPLAY_DATA_API_CALL_ENQUEUED) }, { GameKitErrors.GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME, nameof(GameKitErrors.GAMEKIT_ERROR_MALFORMED_BUNDLE_NAME) }, { GameKitErrors.GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY, nameof(GameKitErrors.GAMEKIT_ERROR_MALFORMED_BUNDLE_ITEM_KEY) }, { GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_WRITE_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_WRITE_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_READ_FAILED, nameof(GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_CACHE_READ_FAILED) }, { GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_UNPROCESSED_ITEMS, nameof(GameKitErrors.GAMEKIT_ERROR_USER_GAMEPLAY_DATA_UNPROCESSED_ITEMS) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SLOT_NOT_FOUND) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_CLOUD_SLOT_IS_NEWER, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_CLOUD_SLOT_IS_NEWER) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SYNC_CONFLICT) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_DOWNLOAD_SLOT_ALREADY_IN_SYNC, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_DOWNLOAD_SLOT_ALREADY_IN_SYNC) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_UPLOAD_SLOT_ALREADY_IN_SYNC, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_UPLOAD_SLOT_ALREADY_IN_SYNC) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_EXCEEDED_MAX_SIZE, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_EXCEEDED_MAX_SIZE) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_FILE_EMPTY, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_FILE_EMPTY) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_FILE_FAILED_TO_OPEN, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_FILE_FAILED_TO_OPEN) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_LOCAL_SLOT_IS_NEWER, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_LOCAL_SLOT_IS_NEWER) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SLOT_UNKNOWN_SYNC_STATUS, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SLOT_UNKNOWN_SYNC_STATUS) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_MALFORMED_SLOT_NAME) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_MISSING_SHA, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_MISSING_SHA) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SLOT_TAMPERED, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_SLOT_TAMPERED) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_BUFFER_TOO_SMALL, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_BUFFER_TOO_SMALL) }, { GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_MAX_CLOUD_SLOTS_EXCEEDED, nameof(GameKitErrors.GAMEKIT_ERROR_GAME_SAVING_MAX_CLOUD_SLOTS_EXCEEDED) }, { GameKitErrors.GAMEKIT_WARNING_SECRETSMANAGER_SECRET_NOT_FOUND, nameof(GameKitErrors.GAMEKIT_WARNING_SECRETSMANAGER_SECRET_NOT_FOUND) }, }; public static string GetErrorName(uint resultCode) { if (RESULT_CODE_TO_NAME.TryGetValue(resultCode, out string value)) { return value; } return $"Unknown error = {GameKitErrors.ToString(resultCode)}."; } } }
123
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Concurrent; using System.Collections.Generic; // Unity using UnityEngine; // GameKit using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Runtime.Utils { public static class Logging { private const int DEFAULT_MAX_LOG_QUEUE_SIZE = 1000; private const bool DEFAULT_IS_UNITY_LOGGING_ENABLED = true; private const Level DEFAULT_MINIMUM_UNITY_LOGGING_LEVEL = Level.INFO; public enum Level : int { VERBOSE = 1, INFO = 2, WARNING = 3, ERROR = 4, // This Level only applies on the Unity plugin side, the AWS GameKit C++ SDK code does not differentiate between ERRORs and EXCEPTIONs EXCEPTION = 5 } public static uint InfoLogCount => _infoLogCount; public static uint WarningLogCount => _warningLogCount; public static uint ErrorLogCount => _errorLogCount; public static IReadOnlyCollection<string> LogQueue => _logQueue; public static bool IsUnityLoggingEnabled { get => _isUnityLoggingEnabled; set { _isUnityLoggingEnabled = value; AwsGameKitPersistentSettings.SaveBool(nameof(IsUnityLoggingEnabled), value); } } public static Level MinimumUnityLoggingLevel { get => _minimumUnityLoggingLevel; set { _minimumUnityLoggingLevel = value; AwsGameKitPersistentSettings.SaveInt(nameof(MinimumUnityLoggingLevel), (int)value); } } public static int MaxLogQueueSize { get => _maxLogQueueSize; set { _maxLogQueueSize = value; AwsGameKitPersistentSettings.SaveInt(nameof(MaxLogQueueSize), value); } } public static FuncLoggingCallback DefaultLogCb => LoggingCallback; public static FuncLoggingCallback LogCb { get => _logCb; set => _logCb = value; } private static bool _isUnityLoggingEnabled; private static Level _minimumUnityLoggingLevel; private static int _maxLogQueueSize; private static FuncLoggingCallback _logCb = DefaultLogCb; private static uint _infoLogCount = 0; private static uint _warningLogCount = 0; private static uint _errorLogCount = 0; private static ConcurrentQueue<string> _logQueue = new ConcurrentQueue<string>(); static Logging() { IsUnityLoggingEnabled = AwsGameKitPersistentSettings.LoadBool(nameof(IsUnityLoggingEnabled), DEFAULT_IS_UNITY_LOGGING_ENABLED); MinimumUnityLoggingLevel = (Level)AwsGameKitPersistentSettings.LoadInt(nameof(MinimumUnityLoggingLevel), (int)DEFAULT_MINIMUM_UNITY_LOGGING_LEVEL); MaxLogQueueSize = AwsGameKitPersistentSettings.LoadInt(nameof(MaxLogQueueSize), DEFAULT_MAX_LOG_QUEUE_SIZE); // Default logging level to error when outside editor unless using DEBUG symbols, override by changing log level within game. #if !UNITY_EDITOR && DEBUG MinimumUnityLoggingLevel = Level.INFO; #elif !UNITY_EDITOR MinimumUnityLoggingLevel = Level.ERROR; #endif } public static void ClearLogQueue() { _logQueue = new ConcurrentQueue<string>(); _infoLogCount = 0; _warningLogCount = 0; _errorLogCount = 0; } public static void Log(Level level, object message) { string messageAsString = message.ToString(); _logCb((uint)level, messageAsString, messageAsString.Length); } public static void LogInfo(object message) => Log(Level.INFO, message); public static void LogWarning(object message) => Log(Level.WARNING, message); public static void LogError(object message) => Log(Level.ERROR, message); public static void LogException(object message, Exception e) { ++_errorLogCount; LogInUnity(Level.EXCEPTION, () => { Debug.LogException(e); }); AddToLogQueue((uint)Level.EXCEPTION, $"{message.ToString()}, {e}"); } [AOT.MonoPInvokeCallback(typeof(FuncLoggingCallback))] private static void LoggingCallback(uint level, string message, int size) { switch (level) { case ((uint)Level.VERBOSE): goto default; case ((uint)Level.INFO): goto default; case ((uint)Level.WARNING): ++_warningLogCount; LogInUnity(Level.WARNING, () => { Debug.LogWarning($"AWS GameKit: {message}"); }); break; case ((uint)Level.ERROR): ++_errorLogCount; LogInUnity(Level.ERROR, () => { Debug.LogError($"AWS GameKit: {message}"); }); break; default: ++_infoLogCount; LogInUnity(Level.INFO, () => { Debug.Log($"AWS GameKit: {message}"); }); break; } AddToLogQueue(level, message); } private static void AddToLogQueue(uint level, string message) { #if UNITY_EDITOR // treat VERBOSE level the same as INFO level = level == (uint)Level.VERBOSE ? (uint)Level.INFO : level; _logQueue.Enqueue($"{DateTime.Now} {((Level)level).ToString()}: {message}"); if (_logQueue.Count > MaxLogQueueSize) { string removedLog; _logQueue.TryDequeue(out removedLog); // subtract from the correct log count if (removedLog.Contains(Level.INFO.ToString())) { --_infoLogCount; } else if(removedLog.Contains(Level.WARNING.ToString())) { --_warningLogCount; } else { --_errorLogCount; } } // request an update of the editor window anytime we add a new log to our queue SettingsWindowUpdateController.RequestUpdate(); #endif } private static void LogInUnity(Level minimumLevelRequired, Action lambdaForLogging) { if (IsUnityLoggingEnabled && MinimumUnityLoggingLevel <= minimumLevelRequired) { lambdaForLogging(); } } } }
216
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace AWS.GameKit.Runtime.Utils { /// <summary> /// Class to help with marshalling for calling exported C methods (of the GameKit C++ SDK) /// </summary> public static class Marshaller { /// <summary> /// Call an Action with data referenced by an IntPtr. /// </summary> /// <param name="obj">The data to work on.</param> /// <param name="work">The action the data is called with.</param> public static void Dispatch(object obj, Action<IntPtr> work) { GCHandle gch = GCHandle.Alloc(obj); try { work(GCHandle.ToIntPtr(gch)); } finally { gch.Free(); } } /// <summary> /// Call an Action with data referenced by an IntPtr. /// </summary> /// <param name="obj">The data to work on.</param> /// <param name="work">The action the data is called with.</param> public static T Dispatch<T>(object obj, Func<IntPtr, T> work) { GCHandle gch = GCHandle.Alloc(obj); try { return work(GCHandle.ToIntPtr(gch)); } finally { gch.Free(); } } /// <summary> /// Get a GCHandle to data in unmanaged memory. /// </summary> /// <typeparam name="T">Type of the object.</typeparam> /// <param name="intptr">IntPtr pointing to object in unmanaged memory.</param> /// <returns>Marshalled object.</returns> public static T GetDispatchObject<T>(IntPtr intptr) { GCHandle gch = GCHandle.FromIntPtr(intptr); return (T)gch.Target; } /// <summary> /// Marshalls array in unmanaged memory to managed memory. /// </summary> /// <typeparam name="T">Array element type.</typeparam> /// <param name="pointerToArray">Pointer to array in unmanaged memory.</param> /// <param name="sizeOfArray">Size of the array (in size of type)</param> /// <returns>Marshalled array.</returns> public static T[] IntPtrToArray<T>(IntPtr pointerToArray, uint sizeOfArray) where T : new() { T[] array = new T[sizeOfArray]; int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); for (int i = 0; i < sizeOfArray; ++i) { try { array[i] = Marshal.PtrToStructure<T>(pointerToArray + (size * i)); } catch (Exception e) { array[i] = new T(); Logging.LogException("Unable to construct an array from the provided pointer", e); } } return array; } /// <summary> /// Marshalls array from managed to unmanaged memory. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> /// <param name="array">Array in managed memory.</param> /// <returns>IntPtr to array in unmanaged memory.</returns> public static IntPtr ArrayToIntPtr<T>(T[] array) { IntPtr head = IntPtr.Zero; if (array.Length > 0) { head = Marshal.AllocHGlobal(Marshal.SizeOf(array[0]) * array.Length); long nextAddr = head.ToInt64(); for (uint i = 0; i < array.Length; ++i) { IntPtr next = new IntPtr(nextAddr); Marshal.StructureToPtr(array[i], next, false); nextAddr += Marshal.SizeOf(typeof(T)); } } return head; } /// <summary> /// Marshalls array of strings to array in unmanaged memory. /// </summary> /// <param name="array">Array of strings in managed memory.</param> /// <returns>Array of IntPtr.</returns> public static IntPtr[] ArrayOfStringsToArrayOfIntPtr(string[] array) { IntPtr[] arrayOfPointers = new IntPtr[array.Length]; for (uint i = 0; i < array.Length; ++i) { arrayOfPointers[i] = Marshal.StringToHGlobalAnsi(array[i]); } return arrayOfPointers; } /// <summary> /// Frees an array of IntPtr. /// </summary> /// <param name="array">The IntPtr array.</param> public static void FreeArrayOfIntPtr(IntPtr[] array) { for (uint i = 0; i < array.Length; ++i) { Marshal.FreeHGlobal(array[i]); array[i] = IntPtr.Zero; } } /// <summary> /// Append value to an array of type T /// </summary> /// <typeparam name="T">Type of array element.</typeparam> /// <param name="arrayOfValues">Data array.</param> /// <param name="value">Value to be appended.</param> public static void AppendToArray<T>(ref T[] arrayOfValues, T value) { List<T> buffer = new List<T>(arrayOfValues); buffer.Add(value); arrayOfValues = buffer.ToArray(); } } }
163
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEngine; namespace AWS.GameKit.Runtime.Utils { [Serializable] public class SerializableDictionary<K, V> : Dictionary<K, V>, ISerializationCallbackReceiver { public List<V> ListOfSerializedValues => _values; public string NameOfSerializedValuesList => nameof(_values); [HideInInspector] [SerializeField] private List<K> _keys = new List<K>(); [HideInInspector] [SerializeField] private List<V> _values = new List<V>(); /// <summary> /// Since a Dictionary is not Serializable in C# by default we breakout the KVPs that were stored in the dictionary into a key list and value list which can be Serialized.<br/><br/> /// /// OnBeforeSerialize will run whenever the SerializableDictionary is trying to be Serialized. /// </summary> public void OnBeforeSerialize() { _keys.Clear(); _values.Clear(); foreach (var kvp in this) { _keys.Add(kvp.Key); _values.Add(kvp.Value); } } /// <summary> /// Since a Dictionary is not Serializable in C# by default we take a list of keys and list of values that were serialized in OnBeforeSerialize() and turn them back into a dictionary.<br/><br/> /// /// OnAfterDeserialize will run whenever the SerializableDictionary is trying to be Deserialized. /// </summary> public void OnAfterDeserialize() { Clear(); if (_keys.Count != _values.Count) { Logging.LogError($"There were {_keys.Count} keys and {_values.Count} values found while deserializing the SerializableDictionary. This SerializableDictionary may contain inaccurate data."); } int lowestCount = Math.Min(_keys.Count, _values.Count); for (int i = 0; i != lowestCount; i++) { Add(_keys[i], _values[i]); } } /// <summary> /// Gets a value from the dictionary.<br/><br/> /// /// Note: If the key does not exist yet, will first add the key with a initial value of new V(). /// </summary> /// <param name="key">The key in the dictionary that holds the desired value.</param> /// <returns></returns> public V GetValue(K key) { if (!this.ContainsKey(key)) { this.Add(key, default); } return this[key]; } /// <summary> /// Adds a key value pair to the dictionary.<br/><br/> /// /// Note: If the key does not exist in the dictionary, will add it. /// </summary> /// <param name="key">The key in the dictionary that should hold the passed in value.</param> /// <param name="value">The new value the key should be matched to.</param> public void SetValue(K key, V value) { if (!this.ContainsKey(key)) { this.Add(key, value); } this[key] = value; } } }
95
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Linq; // Unity using UnityEngine; namespace AWS.GameKit.Runtime.Utils { /// <summary> /// A Serializable <see cref="Dictionary{TKey,TValue}"/> that remembers the order the elements were added. /// </summary> /// <remarks> /// [Serialization] /// <para> /// The <see cref="Dictionary{TKey,TValue}"/> class is not Serializable in C# by default. /// This class is able to serialize a dictionary by breaking out the key/value pairs into a key list and value list which can be Serialized. /// </para> /// /// [Order Remembered] /// <para> /// This collection remembers the order the elements were added. /// The ordered elements can be accessed through <see cref="Keys"/>, <see cref="Values"/>, and <see cref="KeyValuePairs"/>. /// The elements can be sorted in a custom order by calling <see cref="Sort"/>. /// </para> /// /// [Time Complexity] /// <para> /// Each method has the following time complexity: /// <list type="bullet"> /// <item><see cref="ContainsKey"/> - O(1)</item> /// <item><see cref="Add"/> - O(1)</item> /// <item><see cref="SetValue"/> - O(1)</item> /// <item><see cref="GetValue"/> - O(1)</item> /// <item><see cref="Remove"/> - O(N)</item> /// <item><see cref="Sort"/> - depends on the provided callback function, usually O(N log(N))</item> /// <item><see cref="Clear"/> - O(N)</item> /// </list> /// </para> /// </remarks> /// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam> /// <typeparam name="TValue">The type of the values in the dictionary.</typeparam> [Serializable] public class SerializableOrderedDictionary<TKey, TValue> : ISerializationCallbackReceiver { protected IDictionary<TKey, TValue> _dict = new Dictionary<TKey, TValue>(); // Serialization // The keys and values are stored in sorted order. [HideInInspector] [SerializeField] protected List<TKey> _keys = new List<TKey>(); [HideInInspector] [SerializeField] protected List<TValue> _values = new List<TValue>(); /// <summary> /// The number of key/value pairs in the <see cref="SerializableOrderedDictionary{K,V}"/> collection. /// </summary> public int Count => _dict.Count; /// <summary> /// Get all keys in the <see cref="SerializableOrderedDictionary{K,V}"/> collection in the order they were added or later sorted with <see cref="Sort"/>. /// </summary> public IEnumerable<TKey> Keys => _keys; /// <summary> /// Get all values in the <see cref="SerializableOrderedDictionary{K,V}"/> collection in the order they were added or later sorted with <see cref="Sort"/>. /// </summary> public IEnumerable<TValue> Values => _values; /// <summary> /// Get all key/value pairs in the <see cref="SerializableOrderedDictionary{K,V}"/> collection in the order they were added or later sorted with <see cref="Sort"/>. /// </summary> public IEnumerable<KeyValuePair<TKey, TValue>> KeyValuePairs => _keys.Zip(_values, (key, value) => new KeyValuePair<TKey, TValue>(key, value)); /// <summary> /// This method is called by Unity when this class needs to be Serialized. /// </summary> public virtual void OnBeforeSerialize() { // Nothing to do. // The _keys and _values lists are already up-to-date. They will be used in OnAfterDeserialize() to reconstruct this object. } /// <summary> /// This method is called by Unity when this class needs to be Deserialized. /// </summary> public virtual void OnAfterDeserialize() { // Rebuild the dictionary from the serialized keys/values. _dict.Clear(); if (_keys.Count != _values.Count) { Logging.LogError($"There were {_keys.Count} keys and {_values.Count} values found while deserializing the {nameof(SerializableOrderedDictionary<TKey, TValue>)}. " + $"This collection may contain inaccurate data."); } int lowestCount = Math.Min(_keys.Count, _values.Count); for (int i = 0; i < lowestCount; ++i) { _dict.Add(_keys[i], _values[i]); } } /// <summary> /// Determine whether the <see cref="SerializableOrderedDictionary{TKey,TValue}"/> collection contains the specified key. /// </summary> /// <param name="key">The key to locate in the collection.</param> /// <exception cref="ArgumentNullException">Thrown when the provided key is null.</exception> public virtual bool ContainsKey(TKey key) { return _dict.ContainsKey(key); } /// <summary> /// Add the specified key and value to the dictionary at the end of the ordered list. /// </summary> /// <param name="key">The key of the element to add.</param> /// <param name="value">The value of the element to add.</param> /// <exception cref="ArgumentNullException">Thrown when the provided key is null.</exception> /// <exception cref="ArgumentException">Thrown when an element with the same key already exists in the <see cref="SerializableOrderedDictionary{K,V}"/> collection.</exception> public virtual void Add(TKey key, TValue value) { _dict.Add(key, value); _keys.Add(key); _values.Add(value); } /// <summary> /// Set the value associated with the specified key. /// </summary> /// <param name="key">The key of the value to set.</param> /// <param name="value">The value associated with the specified key. If the specified key is not found, creates a new element with the specified key. Otherwise overwrites the existing element.</param> /// <exception cref="ArgumentNullException">Thrown when the provided key is null.</exception> public virtual void SetValue(TKey key, TValue value) { if (_dict.ContainsKey(key)) { // Update existing value _dict[key] = value; } else { // Add new element Add(key, value); } } /// <summary> /// Get the value associated with the specified key. /// </summary> /// <param name="key">The key of the value to get.</param> /// <returns>The value associated with the specified key. If the specified key is not found, throws a <see cref="KeyNotFoundException"/>.</returns> /// <exception cref="ArgumentNullException">Thrown when the provided key is null.</exception> /// <exception cref="KeyNotFoundException">Thrown when the specified key does not exist in the <see cref="SerializableOrderedDictionary{K,V}"/> collection.</exception> public virtual TValue GetValue(TKey key) { return _dict[key]; } /// <summary> /// Remove the value with the specified key from the <see cref="SerializableOrderedDictionary{K,V}"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <exception cref="ArgumentNullException">Thrown when the provided key is null.</exception> public virtual void Remove(TKey key) { if (!_dict.ContainsKey(key)) { return; } _dict.Remove(key); int indexOfElement = _keys.IndexOf(key); _keys.RemoveAt(indexOfElement); _values.RemoveAt(indexOfElement); } /// <summary> /// Remove all elements from the <see cref="SerializableOrderedDictionary{K,V}"/> collection. /// </summary> public virtual void Clear() { _dict.Clear(); _keys.Clear(); _values.Clear(); } /// <summary> /// Sort the collection's elements in-place using using the provided sorting function. /// </summary> /// <remarks> /// After calling this method, the new ordering is reflected in <see cref="Keys"/>, <see cref="Values"/>, and <see cref="KeyValuePairs"/>. /// </remarks> /// <param name="sortFunction">A function which sorts a list of key/value pairs. The function's input is this collection's ordered key/value pairs. /// The function's output is the same key/value pairs in a newly sorted order.</param> public virtual void Sort(Func<IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>> sortFunction) { IEnumerable<KeyValuePair<TKey, TValue>> sortedElements = sortFunction(KeyValuePairs.ToList()); _keys.Clear(); _values.Clear(); foreach (KeyValuePair<TKey, TValue> keyValuePair in sortedElements) { _keys.Add(keyValuePair.Key); _values.Add(keyValuePair.Value); } } } }
215
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This class is only usable while in Editor #if UNITY_EDITOR // Standard using System.Threading; // Unity using UnityEditor; using UnityEngine; namespace AWS.GameKit.Runtime.Utils { /// <summary> /// Used to manage updates of the assigned SettingsWindow. /// </summary> public static class SettingsWindowUpdateController { // 0 == false, 1 == true private static int _shouldUpdate = 0; private static EditorWindow _settingsWindow = null; public static void AssignSettingsWindow(EditorWindow settingsWindow) => _settingsWindow = settingsWindow; public static void RequestUpdate() { // set to 1 for true Interlocked.Exchange(ref _shouldUpdate, 1); } public static void Update() { // if the original value found in _shouldUpdate is 1 (true) then force the repaint if (Interlocked.Exchange(ref _shouldUpdate, 0) == 1 && _settingsWindow && !Application.isPlaying) { // this method can only be called from Unity's main thread _settingsWindow.Repaint(); } } } } #endif
47
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Threading; #if UNITY_EDITOR // Unity using UnityEditor; #endif namespace AWS.GameKit.Runtime.Utils { /// <summary> /// Utility class that wraps the calls to functions with a predefined signature inside of a thread and then manages the callbacks resulting from the calls.<br/><br/> /// /// Callbacks are called by using the Threader class's Update() method. This method should be called from one of Unity's Update() lifecycle methods. /// This will result in all callbacks being executed by Unity's main thread, thus making Unity calls from the callbacks safe. /// </summary> public class Threader { /// <summary> /// This is the count of how many callbacks are currently waiting to be executed but have not been loaded into the main thread safe queue /// </summary> public int WaitingQueueCount => _waitingQueue.Count; /// <summary> /// This is the count of how many callbacks are currently waiting to be executed and are in the queue to be executed on the main thread /// </summary> public int ExecutionQueueCount => _executionQueue.Count; // Queue of callbacks waiting to be called - touched by both the functions thread and main thread private List<Action> _waitingQueue = new List<Action>(); // Queue of callbacks in the process of being called - touched only by the main thread private List<Action> _executionQueue = new List<Action>(); // Internal generational counter which increments when Awake is called - callbacks queued up from previous generations are discarded private int _generationCounter = 0; // Internal count of threaded work items outstanding - incremented on main thread, decremented on work thread private int _atomicOutstandingWorkCounter = 0; // Internal identifier for this threader private int _threaderId => GetHashCode(); /// <summary> /// Calls, in its own thread, a simple function that returns a RESULT object<br/><br/> /// /// RESULT: An object signature for the output object returned by the function Threader will act on /// </summary> /// <param name="function">The function to wrap in a thread, signature must be RESULT function(void)</param> /// <param name="callback">Action that is called on the completion of the thread</param> public virtual void Call(Action function, Action callback) { // lambda captures object references, including "this"; explicitly capture counter value int initialCounter = _generationCounter; IncrementWorkCounterAndRun(() => { function(); AddToWaitingQueue(initialCounter, callback); DecrementWorkCounter(); }); } /// <summary> /// Calls, in its own thread, a simple function that returns a RESULT object<br/><br/> /// /// RESULT: An object signature for the output object returned by the function Threader will act on /// </summary> /// <param name="function">The function to wrap in a thread, signature must be RESULT function(void)</param> /// <param name="callback">Action that takes a RESULT type object and is called on the completion of the thread</param> public virtual void Call<RESULT>(Func<RESULT> function, Action<RESULT> callback) { // lambda captures object references, including "this"; explicitly capture counter value int initialCounter = _generationCounter; IncrementWorkCounterAndRun(() => { RESULT result = function(); AddToWaitingQueue(initialCounter, callback, result); DecrementWorkCounter(); }); } /// <summary> /// Calls, in its own thread, a simple function that takes a DESCRIPTION object and returns a RESULT object<br/><br/> /// /// DESCRIPTION: An object signature for the input object sent into the function Threader will act on<br/> /// RESULT: An object signature for the output object returned by the function Threader will act on /// </summary> /// <param name="function">The function to wrap in a thread, signature must be RESULT function(DESCRIPTION)</param> /// <param name="description">Object provided the the wrapped function when it is called</param> /// <param name="callback">Action that takes a RESULT type object and is called on the completion of the thread</param> public virtual void Call<DESCRIPTION, RESULT>(Func<DESCRIPTION, RESULT> function, DESCRIPTION description, Action<RESULT> callback) { // lambda captures object references, including "this"; explicitly capture counter by-value int initialCounter = _generationCounter; IncrementWorkCounterAndRun(() => { RESULT result = function(description); AddToWaitingQueue(initialCounter, callback, result); DecrementWorkCounter(); }); } /// <summary> /// Calls, in its own thread, a function that calls multiple callbacks, such as a paginated function. The function must take a DESCRIPTION and callback then return void<br/><br/> /// /// DESCRIPTION: An object signature for the input object sent into the function Threader will act on<br/> /// RESULT: An object signature for the output object returned by the function Threader will act on /// </summary> /// <param name="function">The function to wrap in a thread, signature must be void function(DESCRIPTION, Action&lt;RESULT&gt;)</param> /// <param name="description">Object provided the the wrapped function when it is called</param> /// <param name="callback">Action that takes a RESULT type object and is called when the wrapped function has a result to return</param> public virtual void Call<DESCRIPTION, RESULT, RETURN_RESULT>( Func<DESCRIPTION, Action<RESULT>, RETURN_RESULT> function, DESCRIPTION description, Action<RESULT> callback, Action<RETURN_RESULT> onCompleteCallback) { // lambda captures object references, including "this"; explicitly capture counter by-value int initialCounter = _generationCounter; IncrementWorkCounterAndRun(() => { Action<RESULT> wrappedCallback = (RESULT result) => { AddToWaitingQueue(initialCounter, callback, result); }; RETURN_RESULT result = function(description, wrappedCallback); AddToWaitingQueue(initialCounter, onCompleteCallback, result); DecrementWorkCounter(); }); } /// <summary> /// Calls, in its own thread, a simple function that takes a DESCRIPTION object and returns nothing<br/><br/> /// /// DESCRIPTION: An object signature for the input object sent into the function Threader will act on /// </summary> /// <param name="function">The function to wrap in a thread, signature must be void function(DESCRIPTION)</param> /// <param name="description">Object provided the the wrapped function when it is called</param> /// <param name="callback">Action that takes a RESULT type object and is called on the completion of the thread</param> public virtual void Call<DESCRIPTION>(Action<DESCRIPTION> function, DESCRIPTION description, Action callback) { // lambda captures object references, including "this"; explicitly capture counter by-value int initialCounter = _generationCounter; IncrementWorkCounterAndRun(() => { function(description); AddToWaitingQueue(initialCounter, callback); DecrementWorkCounter(); }); } /// <summary> /// Called to (re)initialize the threader when changing play modes or scenes /// </summary> public virtual void Awake() { Logging.LogInfo($"GameKit Threader {_threaderId} Awake"); // clear the queues each time this class is used to prevent any spill over when changing from playmode to editmode (and visa versa) lock (_waitingQueue) { _waitingQueue.Clear(); _executionQueue.Clear(); _generationCounter = unchecked(_generationCounter + 1); // overflow is possible, ignored. } } /// <summary> /// Called to handle any callbacks generated by the called functions /// </summary> public virtual void Update() { // move any actions waiting to execute into the execture queue lock (_waitingQueue) { _executionQueue.AddRange(_waitingQueue); _waitingQueue.Clear(); } // execute the current actions try { _executionQueue.ForEach((action) => { action(); #if UNITY_EDITOR // if there has been a callback, request that our settings window updates so that any results from that callback can display if needed SettingsWindowUpdateController.RequestUpdate(); #endif }); } finally { _executionQueue.Clear(); } } /// <summary> /// Waits for the completion of pending tasks in a loop (blocking). No-op in Editor. /// </summary> /// <param name="loopDelay">Time to wait before checking for task completion in each loop iteration.</param> public void WaitForThreadedWork(int loopDelay = 50) { #if !UNITY_EDITOR // In game mode wait for pending tasks WaitForThreadedWork_Internal(loopDelay); #endif } /// <summary> /// Waits for the completion of pending tasks in a loop (blocking). /// </summary> /// <param name="loopDelay">Time to wait before checking for task completion in each loop iteration.</param> private void WaitForThreadedWork_Internal(int loopDelay = 50) { while (true) { // Note: slightly abusing Interlocked.Add(x, 0) as an atomic read w/ full memory barrier. if (Interlocked.Add(ref _atomicOutstandingWorkCounter, 0) == 0) { Logging.LogInfo($"GameKit Threader {_threaderId} WaitForThreadedWork: No outstanding work remaining."); return; } Logging.LogInfo($"GameKit Threader {_threaderId} WaitForThreadedWork: Waiting for outstanding work..."); Thread.Sleep(loopDelay); } } /// <summary> /// Called to block until threaded work is complete. Callbacks remain unprocessed in the wait queue. Intended for tests only. /// </summary> public virtual void WaitForThreadedWork_TestOnly() { WaitForThreadedWork_Internal(1); } /// <summary> /// Helper method for adding a new callback action to the waiting queue in preparation for it to be called by the main thread. /// </summary> /// <param name="checkCounter">Generational counter value when call was initiated - callback will be ignored if counter has changed</param> /// <param name="callback">Callback to execute on the main thread during the update game state. Must have signature void func(RESULT)</param> /// <param name="result">Object that is passed into the callback function when it is executed</param> private void AddToWaitingQueue<RESULT>(int checkCounter, Action<RESULT> callback, RESULT result) { lock (_waitingQueue) { if (checkCounter == _generationCounter) { _waitingQueue.Add(() => callback(result)); } } } /// <summary> /// Helper method for adding a new callback action to the waiting queue in preparation for it to be called by the main thread. /// </summary> /// <param name="checkCounter">Generational counter value when call was initiated - callback will be ignored if counter has changed</param> /// <param name="callback">Callback to execute on the main thread during the update game state. Must have signature void func(void)</param> private void AddToWaitingQueue(int checkCounter, Action callback) { lock (_waitingQueue) { if (checkCounter == _generationCounter) { _waitingQueue.Add(callback); } } } /// <summary> /// Helper method for tracking when threaded work item has completed (adjusting _atomicOutstandingWorkCounter) /// </summary> private void DecrementWorkCounter() { Interlocked.Decrement(ref _atomicOutstandingWorkCounter); } /// <summary> /// Helper method for scheduling an async threaded action from the main thread (adjusting _atomicOutstandingWorkCounter) /// </summary> /// <param name="action">Action to be executed asynchronously</param> private void IncrementWorkCounterAndRun(Action action) { Interlocked.Increment(ref _atomicOutstandingWorkCounter); bool queued = false; try { queued = ThreadPool.QueueUserWorkItem(delegate (object param) { ((Action)param)(); }, action); } finally { // If QueueUserWorkItem throws for any reason, do not leave the counter permanently incremented if (!queued) { DecrementWorkCounter(); } } } } }
306
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Runtime.Utils { public static class TimeUtils { /// <summary> /// Converts an epoch timestamp into a human readable string. /// </summary> /// <remarks> /// Converts the timestamp into the format "dd/mm/yyyy hh:mm:ss [AM|PM] [+|-]hh:mm". /// Uses the platform's local time zone.<br/> /// If the provided epoch timestamp is 0, this function assumes it to be an empty value /// and returns an empty string. /// </remarks> /// <param name="epochTime">The epoch time, in millseconds.</param> /// <returns>The epoch time as a date string.</returns> public static string EpochTimeToString(long epochTime) { if (epochTime == 0) { return string.Empty; } DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(epochTime).ToLocalTime(); return dateTimeOffset.ToString(); } /// <summary> /// Convert an ISO-8601 formatted timestamp into a human readable string. /// </summary> /// <remarks> /// Converts the timestamp into the format "dd/mm/yyyy hh:mm:ss [AM|PM] [+|-]hh:mm". /// Uses the platform's local time zone.<br/> /// If the provided epoch timestamp is 0, this function assumes it to be an empty value /// and returns an empty string. /// </remarks> /// <param name="timestamp">The ISO-8601 formatted timestamp to convert.</param> /// <returns>The ISO-8601 timestamp as a human readable string.</returns> public static string ISO8601StringToLocalFormattedString(string timestamp) { if (string.IsNullOrEmpty(timestamp)) { return string.Empty; } DateTimeOffset dateTimeOffset = DateTimeOffset.Parse(timestamp).ToLocalTime(); return dateTimeOffset.ToString(); } } }
55
aws-gamekit-unreal
aws
C#
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using UnrealBuildTool; public class AwsGameKitCore : ModuleRules { public AwsGameKitCore(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicIncludePaths.AddRange( new string[] { Path.Combine(ModuleDirectory, "Public"), Path.Combine(ModuleDirectory, "Public/Core") } ); PrivateIncludePaths.AddRange( new string[] { Path.Combine(ModuleDirectory, "Private"), Path.Combine(ModuleDirectory, "Private/Core") } ); PublicIncludePaths.Add(Path.Combine(PluginDirectory, "Libraries/include")); if (Target.Platform == UnrealTargetPlatform.IOS) { // Curl PublicIncludePaths.Add(Path.Combine(PluginDirectory, "Libraries/include/curl")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/curl/libcurl.a")); // nghttp PublicIncludePaths.Add(Path.Combine(PluginDirectory, "Libraries/include/nghttp2")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/nghttp2/libnghttp2.a")); if (Target.Configuration == UnrealTargetConfiguration.Debug || Target.Configuration == UnrealTargetConfiguration.DebugGame || Target.Configuration == UnrealTargetConfiguration.Development) { // Aws SDK PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-auth.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-cal.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-common.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-compression.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-event-stream.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-http.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-io.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-mqtt.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-s3.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-checksums.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-apigateway.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-cloudformation.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-cognito-idp.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-core.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-lambda.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-s3.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-secretsmanager.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-ssm.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-sts.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-crt-cpp.a")); // GameKit PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-achievements.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-authentication.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-core.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-game-saving.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-identity.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-user-gameplay-data.a")); // yaml-cpp PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/yaml-cpp/libyaml-cppd.a")); // boost PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/boost/libboost_filesystem.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/boost/libboost_iostreams.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/boost/libboost_regex.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/boost/libboost.a")); } else { PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-auth.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-cal.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-common.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-compression.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-event-stream.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-http.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-io.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-mqtt.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-s3.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-checksums.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-apigateway.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-cloudformation.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-cognito-idp.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-core.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-lambda.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-s3.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-secretsmanager.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-ssm.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-sts.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-crt-cpp.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-achievements.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-authentication.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-core.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-game-saving.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-identity.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-user-gameplay-data.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/yaml-cpp/libyaml-cppd.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/boost/libboost_filesystem.a")); } } if (Target.Platform == UnrealTargetPlatform.Android) { /* The Android libraries directory must have this hierarchy to support combined 32 + 64 bit builds: PluginDirectory Libraries Android arm64 Debug Release armv7 Debug Release */ IList<string> architectures = new List<string> { "armv7", "arm64" }; IList<string> libs = new List<string> { // Aws sdk "libaws-c-auth.a", "libaws-c-cal.a", "libaws-c-common.a", "libaws-c-compression.a", "libaws-c-event-stream.a", "libaws-c-http.a", "libaws-c-io.a", "libaws-c-mqtt.a", "libaws-c-s3.a", "libaws-checksums.a", "libaws-cpp-sdk-apigateway.a", "libaws-cpp-sdk-cloudformation.a", "libaws-cpp-sdk-cognito-idp.a", "libaws-cpp-sdk-core.a", "libaws-cpp-sdk-lambda.a", "libaws-cpp-sdk-s3.a", "libaws-cpp-sdk-secretsmanager.a", "libaws-cpp-sdk-ssm.a", "libaws-cpp-sdk-sts.a", "libaws-crt-cpp.a", "libs2n.a", // SSL "libcrypto.a", "libssl.a", // Curl "libcurl.a", // Yaml "libyaml-cpp.a", // GameKit "libaws-gamekit-achievements.a", "libaws-gamekit-authentication.a", "libaws-gamekit-core.a", "libaws-gamekit-game-saving.a", "libaws-gamekit-identity.a", "libaws-gamekit-user-gameplay-data.a" }; string buildFlavor = string.Empty; IList<string> boostLibs = new List<string>(); IDictionary<string, string> boostMapping = new Dictionary<string, string>() { { "armv7", "a32" }, { "arm64", "a64" } }; if (Target.Configuration == UnrealTargetConfiguration.Debug || Target.Configuration == UnrealTargetConfiguration.DebugGame || Target.Configuration == UnrealTargetConfiguration.Development) { buildFlavor = "Debug"; boostLibs.Add("libboost_filesystem-mt-d-{0}.a"); boostLibs.Add("libboost_iostreams-mt-d-{0}.a"); } else { buildFlavor = "Release"; boostLibs.Add("libboost_filesystem-mt-{0}.a"); boostLibs.Add("libboost_iostreams-mt-{0}.a"); } foreach (var architecture in architectures) { foreach (var lib in libs) { PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries", "Android", architecture, buildFlavor, lib)); } foreach (var lib in boostLibs) { PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries", "Android", architecture, buildFlavor, string.Format(lib, boostMapping[architecture]))); } } } PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", } ); PrivateDependencyModuleNames.AddRange( new string[] { } ); DynamicallyLoadedModuleNames.AddRange( new string[] { } ); if (Target.Platform == UnrealTargetPlatform.Win64) { if (Target.Configuration == UnrealTargetConfiguration.Debug || Target.Configuration == UnrealTargetConfiguration.DebugGame || Target.Configuration == UnrealTargetConfiguration.Development) { RuntimeDependencies.Add("$(ProjectDir)/Binaries/Win64/aws-*.dll", Path.Combine(PluginDirectory, "Libraries/Win64/Debug/aws-*.dll")); RuntimeDependencies.Add("$(ProjectDir)/Binaries/Win64/aws-*.pdb", Path.Combine(PluginDirectory, "Libraries/Win64/Debug/aws-*.pdb")); } else { RuntimeDependencies.Add("$(ProjectDir)/Binaries/Win64/aws-*.dll", Path.Combine(PluginDirectory, "Libraries/Win64/Release/aws-*.dll")); } } else if (Target.Platform == UnrealTargetPlatform.Mac) { if (Target.Configuration == UnrealTargetConfiguration.Debug || Target.Configuration == UnrealTargetConfiguration.DebugGame || Target.Configuration == UnrealTargetConfiguration.Development) { RuntimeDependencies.Add("$(ProjectDir)/Binaries/Mac/libaws-*.dylib", Path.Combine(PluginDirectory, "Libraries/Mac/Debug/libaws-*.dylib")); } else { RuntimeDependencies.Add("$(ProjectDir)/Binaries/Mac/libaws-*.dylib", Path.Combine(PluginDirectory, "Libraries/Mac/Release/libaws-*.dylib")); } } else if (Target.Platform == UnrealTargetPlatform.IOS || Target.Platform == UnrealTargetPlatform.Android) { RuntimeDependencies.Add("$(ProjectDir)/Content/certs/*.pem", Path.Combine(PluginDirectory, "Libraries/certs/*.pem")); } } }
261
aws-gamekit-unreal
aws
C#
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using UnrealBuildTool; public class AwsGameKitEditor : ModuleRules { public AwsGameKitEditor(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicIncludePaths.AddRange( new string[] { Path.Combine(ModuleDirectory, "Public/Achievements"), Path.Combine(ModuleDirectory, "Public/GameSaving"), Path.Combine(ModuleDirectory, "Public/Identity"), Path.Combine(ModuleDirectory, "Public/UserGameplayData"), Path.Combine(ModuleDirectory, "Public/Utils") } ); PrivateIncludePaths.AddRange( new string[] { Path.Combine(ModuleDirectory, "Private/Achievements"), Path.Combine(ModuleDirectory, "Private/GameSaving"), Path.Combine(ModuleDirectory, "Private/Identity"), Path.Combine(ModuleDirectory, "Private/UserGameplayData"), Path.Combine(ModuleDirectory, "Private/Utils") } ); if (Target.Platform == UnrealTargetPlatform.IOS) { PublicIncludePaths.Add(Path.Combine(PluginDirectory, "Libraries/include")); // Curl PublicIncludePaths.Add(Path.Combine(PluginDirectory, "Libraries/include/curl")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/curl/libcurl.a")); // OpenSSL PublicIncludePaths.Add(Path.Combine(PluginDirectory, "Libraries/include/openssl")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/openssl/libcrypto.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/openssl/libssl.a")); // nghttp PublicIncludePaths.Add(Path.Combine(PluginDirectory, "Libraries/include/nghttp2")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/nghttp2/libnghttp2.a")); if (Target.Configuration == UnrealTargetConfiguration.Debug || Target.Configuration == UnrealTargetConfiguration.DebugGame || Target.Configuration == UnrealTargetConfiguration.Development) { PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-auth.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-cal.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-common.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-compression.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-event-stream.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-http.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-io.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-mqtt.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-c-s3.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-checksums.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-apigateway.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-cloudformation.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-cognito-idp.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-core.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-lambda.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-s3.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-secretsmanager.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-ssm.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-cpp-sdk-sts.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-crt-cpp.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-achievements.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-authentication.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-core.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-game-saving.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-identity.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/libaws-gamekit-user-gameplay-data.a")); // yaml-cpp PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/yaml-cpp/libyaml-cppd.a")); // boost PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/boost/libboost_filesystem.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/boost/libboost_iostreams.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/boost/libboost_regex.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Debug/boost/libboost.a")); } else { PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-auth.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-cal.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-common.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-compression.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-event-stream.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-http.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-io.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-mqtt.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-c-s3.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-checksums.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-apigateway.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-cloudformation.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-cognito-idp.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-core.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-lambda.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-s3.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-secretsmanager.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-ssm.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-cpp-sdk-sts.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-crt-cpp.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-achievements.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-authentication.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-core.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-game-saving.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-identity.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/libaws-gamekit-user-gameplay-data.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/yaml-cpp/libyaml-cppd.a")); PublicAdditionalLibraries.Add(Path.Combine(PluginDirectory, "Libraries/IOS/Release/boost/libboost_filesystem.a")); } } PublicDependencyModuleNames.AddRange( new string[] { "Core", "AwsGameKitCore", "AwsGameKitRuntime", "CoreUObject", "Engine", "Json", "UnrealEd", "Slate", "SlateCore", "EditorStyle", "Projects", "InputCore", "AwsGameKitCore", "AwsGameKitRuntime", "Http", "ImageWrapper" } ); DynamicallyLoadedModuleNames.AddRange( new string[] { } ); if (Target.Platform == UnrealTargetPlatform.Win64) { // Add any libraries not part of AwsGameKit but needed by AwsGameKitRuntime } else if (Target.Platform == UnrealTargetPlatform.Mac) { // Add any libraries not part of AwsGameKit but needed by AwsGameKitRuntime } } }
161
aws-gamekit-unreal
aws
C#
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using UnrealBuildTool; public class AwsGameKitRuntime : ModuleRules { public AwsGameKitRuntime(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicIncludePaths.AddRange( new string[] { Path.Combine(ModuleDirectory, "Public"), Path.Combine(ModuleDirectory, "Public/Achievements"), Path.Combine(ModuleDirectory, "Public/Common"), Path.Combine(ModuleDirectory, "Public/GameSaving"), Path.Combine(ModuleDirectory, "Public/Identity"), Path.Combine(ModuleDirectory, "Public/Models"), Path.Combine(ModuleDirectory, "Public/SessionManager"), Path.Combine(ModuleDirectory, "Public/UserGameplayData"), Path.Combine(ModuleDirectory, "Public/Utils") } ); PrivateIncludePaths.AddRange( new string[] { Path.Combine(ModuleDirectory, "Private"), Path.Combine(ModuleDirectory, "Private/Achievements"), Path.Combine(ModuleDirectory, "Private/GameSaving"), Path.Combine(ModuleDirectory, "Private/Identity"), Path.Combine(ModuleDirectory, "Private/SessionManager"), Path.Combine(ModuleDirectory, "Private/UserGameplayData"), Path.Combine(ModuleDirectory, "Private/Utils") } ); PublicDependencyModuleNames.AddRange( new string[] { "Core", "AwsGameKitCore", "Engine", "Json" } ); if (Target.bBuildEditor) { PublicDependencyModuleNames.AddRange( new string[] { "DesktopPlatform", "EngineSettings", "GameProjectGeneration", "Projects" } ); } PrivateDependencyModuleNames.AddRange( new string[] { "CoreUObject", "Slate" } ); DynamicallyLoadedModuleNames.AddRange( new string[] { } ); } }
79
aws-lambda-builders
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; namespace CustomRuntime6; public class Function { private static async Task Main(string[] args) { Func<string, ILambdaContext, string> handler = FunctionHandler; await LambdaBootstrapBuilder.Create(handler, new DefaultLambdaJsonSerializer()) .Build() .RunAsync(); } public static string FunctionHandler(string input, ILambdaContext context) { return input.ToUpper(); } }
21
aws-lambda-builders
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace RequireParameters { public class Function { /// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string FunctionHandler(string input, ILambdaContext context) { return input?.ToUpper(); } } }
28
aws-lambda-builders
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace WithDefaultsFile { public class Function { /// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string FunctionHandler(string input, ILambdaContext context) { return input?.ToUpper(); } } }
28
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using System.IO; namespace BlueprintBaseName._1 { /// <summary> /// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the /// actual Lambda function entry point. The Lambda handler field should be set to /// /// BlueprintBaseName.1::BlueprintBaseName.1.LambdaEntryPoint::FunctionHandlerAsync /// </summary> public class LambdaEntryPoint : // When using an ELB's Application Load Balancer as the event source change // the base class to Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction { /// <summary> /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class /// needs to be configured in this method using the UseStartup<>() method. /// </summary> /// <param name="builder"></param> protected override void Init(IWebHostBuilder builder) { builder .UseStartup<Startup>(); } } }
34
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace BlueprintBaseName._1 { /// <summary> /// The Main function can be used to run the ASP.NET Core application locally using the Kestrel webserver. /// </summary> public class LocalEntryPoint { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
27
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace BlueprintBaseName._1 { public class Startup { public const string AppS3BucketKey = "AppS3Bucket"; public Startup(IConfiguration configuration) { Configuration = configuration; } public static IConfiguration Configuration { get; private set; } // This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Add S3 to the ASP.NET Core dependency injection framework. services.AddAWSService<Amazon.S3.IAmazonS3>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); } } }
51
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Amazon.S3; using Amazon.S3.Model; using Newtonsoft.Json; namespace BlueprintBaseName._1.Controllers { /// <summary> /// ASP.NET Core controller acting as a S3 Proxy. /// </summary> [Route("api/[controller]")] public class S3ProxyController : Controller { IAmazonS3 S3Client { get; set; } ILogger Logger { get; set; } string BucketName { get; set; } public S3ProxyController(IConfiguration configuration, ILogger<S3ProxyController> logger, IAmazonS3 s3Client) { this.Logger = logger; this.S3Client = s3Client; this.BucketName = configuration[Startup.AppS3BucketKey]; if(string.IsNullOrEmpty(this.BucketName)) { logger.LogCritical("Missing configuration for S3 bucket. The AppS3Bucket configuration must be set to a S3 bucket."); throw new Exception("Missing configuration for S3 bucket. The AppS3Bucket configuration must be set to a S3 bucket."); } logger.LogInformation($"Configured to use bucket {this.BucketName}"); } [HttpGet] public async Task<JsonResult> Get() { var listResponse = await this.S3Client.ListObjectsV2Async(new ListObjectsV2Request { BucketName = this.BucketName }); try { this.Response.ContentType = "text/json"; return new JsonResult(listResponse.S3Objects, new JsonSerializerSettings { Formatting = Formatting.Indented }); } catch(AmazonS3Exception e) { this.Response.StatusCode = (int)e.StatusCode; return new JsonResult(e.Message); } } [HttpGet("{key}")] public async Task Get(string key) { try { var getResponse = await this.S3Client.GetObjectAsync(new GetObjectRequest { BucketName = this.BucketName, Key = key }); this.Response.ContentType = getResponse.Headers.ContentType; getResponse.ResponseStream.CopyTo(this.Response.Body); } catch (AmazonS3Exception e) { this.Response.StatusCode = (int)e.StatusCode; var writer = new StreamWriter(this.Response.Body); writer.Write(e.Message); } } [HttpPut("{key}")] public async Task Put(string key) { // Copy the request body into a seekable stream required by the AWS SDK for .NET. var seekableStream = new MemoryStream(); await this.Request.Body.CopyToAsync(seekableStream); seekableStream.Position = 0; var putRequest = new PutObjectRequest { BucketName = this.BucketName, Key = key, InputStream = seekableStream }; try { var response = await this.S3Client.PutObjectAsync(putRequest); Logger.LogInformation($"Uploaded object {key} to bucket {this.BucketName}. Request Id: {response.ResponseMetadata.RequestId}"); } catch (AmazonS3Exception e) { this.Response.StatusCode = (int)e.StatusCode; var writer = new StreamWriter(this.Response.Body); writer.Write(e.Message); } } [HttpDelete("{key}")] public async Task Delete(string key) { var deleteRequest = new DeleteObjectRequest { BucketName = this.BucketName, Key = key }; try { var response = await this.S3Client.DeleteObjectAsync(deleteRequest); Logger.LogInformation($"Deleted object {key} from bucket {this.BucketName}. Request Id: {response.ResponseMetadata.RequestId}"); } catch (AmazonS3Exception e) { this.Response.StatusCode = (int)e.StatusCode; var writer = new StreamWriter(this.Response.Body); writer.Write(e.Message); } } } }
136
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace BlueprintBaseName._1.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
45
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using Amazon; using Amazon.S3; using Amazon.S3.Util; using Amazon.S3.Model; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class S3ProxyControllerTests : IDisposable { string BucketName { get; set; } IAmazonS3 S3Client { get; set; } IConfigurationRoot Configuration { get; set; } public S3ProxyControllerTests() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); this.Configuration = builder.Build(); // Use the region and possible profile specified in the appsettings.json file to construct an Amazon S3 service client. this.S3Client = Configuration.GetAWSOptions().CreateServiceClient<IAmazonS3>(); // Create a bucket used for the test which will be deleted along with any data in the bucket once the test is complete. this.BucketName = "lambda-S3ProxyControllerTests-".ToLower() + DateTime.Now.Ticks; this.S3Client.PutBucketAsync(this.BucketName).Wait(); } [Fact] public async Task TestSuccessWorkFlow() { var lambdaFunction = new LambdaEntryPoint(); Startup.Configuration[Startup.AppS3BucketKey] = this.BucketName; // Use sample API Gateway request that uploads an object with object key "foo.txt" and content of "Hello World". var requestStr = File.ReadAllText("./SampleRequests/S3ProxyController-Put.json"); var request = JsonConvert.DeserializeObject<APIGatewayProxyRequest>(requestStr); var context = new TestLambdaContext(); var response = await lambdaFunction.FunctionHandlerAsync(request, context); Assert.Equal(200, response.StatusCode); // Get with no object key in the resource path does an object list call requestStr = File.ReadAllText("./SampleRequests/S3ProxyController-Get.json"); request = JsonConvert.DeserializeObject<APIGatewayProxyRequest>(requestStr); context = new TestLambdaContext(); response = await lambdaFunction.FunctionHandlerAsync(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("text/json", response.MultiValueHeaders["Content-Type"][0]); Assert.Contains("foo.txt", response.Body); // Return the content of the new s3 object foo.txt requestStr = File.ReadAllText("./SampleRequests/S3ProxyController-GetByKey.json"); request = JsonConvert.DeserializeObject<APIGatewayProxyRequest>(requestStr); context = new TestLambdaContext(); response = await lambdaFunction.FunctionHandlerAsync(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("text/plain", response.MultiValueHeaders["Content-Type"][0]); Assert.Equal("Hello World", response.Body); // Delete the object requestStr = File.ReadAllText("./SampleRequests/S3ProxyController-Delete.json"); request = JsonConvert.DeserializeObject<APIGatewayProxyRequest>(requestStr); context = new TestLambdaContext(); response = await lambdaFunction.FunctionHandlerAsync(request, context); Assert.Equal(200, response.StatusCode); // Make sure the object was deleted requestStr = File.ReadAllText("./SampleRequests/S3ProxyController-GetByKey.json"); request = JsonConvert.DeserializeObject<APIGatewayProxyRequest>(requestStr); context = new TestLambdaContext(); response = await lambdaFunction.FunctionHandlerAsync(request, context); Assert.Equal(404, response.StatusCode); } private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { AmazonS3Util.DeleteS3BucketWithObjectsAsync(this.S3Client, BucketName).Wait(); this.S3Client.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } } }
124
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; using Newtonsoft.Json; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class ValuesControllerTests { [Fact] public async Task TestGet() { var lambdaFunction = new LambdaEntryPoint(); var requestStr = File.ReadAllText("./SampleRequests/ValuesController-Get.json"); var request = JsonConvert.DeserializeObject<APIGatewayProxyRequest>(requestStr); var context = new TestLambdaContext(); var response = await lambdaFunction.FunctionHandlerAsync(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("[\"value1\",\"value2\"]", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } } }
42
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using System.IO; namespace BlueprintBaseName._1 { /// <summary> /// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the /// actual Lambda function entry point. The Lambda handler field should be set to /// /// BlueprintBaseName.1::BlueprintBaseName.1.LambdaEntryPoint::FunctionHandlerAsync /// </summary> public class LambdaEntryPoint : // When using an ELB's Application Load Balancer as the event source change // the base class to Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction { /// <summary> /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class /// needs to be configured in this method using the UseStartup<>() method. /// </summary> /// <param name="builder"></param> protected override void Init(IWebHostBuilder builder) { builder .UseStartup<Startup>(); } } }
34
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace BlueprintBaseName._1 { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
26
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace BlueprintBaseName._1 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); } } }
58