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
|
---|---|---|---|---|
amazon-cognito-sync-manager-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Amazon.CognitoSync.SyncManager
{
public partial interface ILocalStorage
{
/// <summary>
/// Caches the Identity Id
/// </summary>
/// <param name="key"></param>
/// <param name="identity"></param>
[System.Security.SecuritySafeCritical]
void CacheIdentity(string key, string identity);
/// <summary>
/// Gets the cached identity id
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
[System.Security.SecuritySafeCritical]
string GetIdentity(string key);
/// <summary>
/// Removes the Identity Id identified by the key from the cache
/// </summary>
/// <param name="key"></param>
[System.Security.SecuritySafeCritical]
void DeleteCachedIdentity(string key);
}
}
| 35 |
amazon-cognito-sync-manager-net | aws | C# | //
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
using Amazon.Runtime.Internal.Util;
using System.Data.SQLite;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Globalization;
using System.Security;
using System.Security.Permissions;
using Amazon.Util.Internal;
namespace Amazon.CognitoSync.SyncManager.Internal
{
public partial class SQLiteLocalStorage : ILocalStorage
{
//datetime is converted to ticks and stored as string
private SQLiteConnection connection;
#region dispose methods
/// <summary>
/// Releases the resources consumed by this object if disposing is true.
/// </summary>
[SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
connection.Close();
connection.Dispose();
}
}
#endregion
#region helper methods
[SecuritySafeCritical]
private void SetupDatabase()
{
//check if database already exists
var filePath = InternalSDKUtils.DetermineAppLocalStoragePath(DB_FILE_NAME);
var directoryPath = InternalSDKUtils.DetermineAppLocalStoragePath();
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
if (!File.Exists(filePath))
SQLiteConnection.CreateFile(filePath);
connection = new SQLiteConnection(string.Format(CultureInfo.InvariantCulture, "Data Source={0};Version=3;", filePath));
connection.Open();
string createDatasetTable = "CREATE TABLE IF NOT EXISTS " + TABLE_DATASETS + "("
+ DatasetColumns.IDENTITY_ID + " TEXT NOT NULL,"
+ DatasetColumns.DATASET_NAME + " TEXT NOT NULL,"
+ DatasetColumns.CREATION_TIMESTAMP + " TEXT DEFAULT '0',"
+ DatasetColumns.LAST_MODIFIED_TIMESTAMP + " TEXT DEFAULT '0',"
+ DatasetColumns.LAST_MODIFIED_BY + " TEXT,"
+ DatasetColumns.STORAGE_SIZE_BYTES + " INTEGER DEFAULT 0,"
+ DatasetColumns.RECORD_COUNT + " INTEGER DEFAULT 0,"
+ DatasetColumns.LAST_SYNC_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ DatasetColumns.LAST_SYNC_TIMESTAMP + " TEXT DEFAULT '0',"
+ DatasetColumns.LAST_SYNC_RESULT + " TEXT,"
+ "UNIQUE (" + DatasetColumns.IDENTITY_ID + ", "
+ DatasetColumns.DATASET_NAME + ")"
+ ")";
using (var command = new SQLiteCommand(createDatasetTable, connection))
{
command.ExecuteNonQuery();
}
string createRecordsTable = "CREATE TABLE IF NOT EXISTS " + TABLE_RECORDS + "("
+ RecordColumns.IDENTITY_ID + " TEXT NOT NULL,"
+ RecordColumns.DATASET_NAME + " TEXT NOT NULL,"
+ RecordColumns.KEY + " TEXT NOT NULL,"
+ RecordColumns.VALUE + " TEXT,"
+ RecordColumns.SYNC_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ RecordColumns.LAST_MODIFIED_TIMESTAMP + " TEXT DEFAULT '0',"
+ RecordColumns.LAST_MODIFIED_BY + " TEXT,"
+ RecordColumns.DEVICE_LAST_MODIFIED_TIMESTAMP + " TEXT DEFAULT '0',"
+ RecordColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 1,"
+ "UNIQUE (" + RecordColumns.IDENTITY_ID + ", " + RecordColumns.DATASET_NAME
+ ", " + RecordColumns.KEY + ")"
+ ")";
using (var command = new SQLiteCommand(createRecordsTable, connection))
{
command.ExecuteNonQuery();
}
string createKvStore = "CREATE TABLE IF NOT EXISTS kvstore (key TEXT NOT NULL, value TEXT NOT NULL, UNIQUE (KEY))";
using (var command = new SQLiteCommand(createKvStore, connection))
{
command.ExecuteNonQuery();
}
}
[SecuritySafeCritical]
internal void CreateDatasetHelper(string query, params object[] parameters)
{
using (var command = new SQLiteCommand(connection))
{
command.CommandText = query;
BindData(command, parameters);
command.ExecuteNonQuery();
}
}
[SecuritySafeCritical]
internal DatasetMetadata GetMetadataHelper(string identityId, string datasetName)
{
string query = DatasetColumns.BuildQuery(
DatasetColumns.IDENTITY_ID + " = @identityId AND " +
DatasetColumns.DATASET_NAME + " = @datasetName "
);
DatasetMetadata metadata = null;
using (var command = new SQLiteCommand(connection))
{
command.CommandText = query;
BindData(command, identityId, datasetName);
using (var reader = command.ExecuteReader())
{
if (reader.HasRows && reader.Read())
{
metadata = SqliteStmtToDatasetMetadata(reader);
}
}
}
return metadata;
}
[SecuritySafeCritical]
internal List<DatasetMetadata> GetDatasetMetadataHelper(string query, params string[] parameters)
{
List<DatasetMetadata> datasetMetadataList = new List<DatasetMetadata>();
using (var command = new SQLiteCommand(connection))
{
command.CommandText = query;
BindData(command, parameters);
using (var reader = command.ExecuteReader())
{
while (reader.HasRows && reader.Read())
{
datasetMetadataList.Add(SqliteStmtToDatasetMetadata(reader));
}
}
}
return datasetMetadataList;
}
[SecuritySafeCritical]
internal Record GetRecordHelper(string query, params string[] parameters)
{
Record record = null;
using (var command = new SQLiteCommand(connection))
{
command.CommandText = query;
BindData(command, parameters);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
record = SqliteStmtToRecord(reader);
}
}
}
return record;
}
[SecuritySafeCritical]
internal List<Record> GetRecordsHelper(string query, params string[] parameters)
{
List<Record> records = new List<Record>();
using (var command = new SQLiteCommand(connection))
{
command.CommandText = query;
BindData(command, parameters);
using (var reader = command.ExecuteReader())
{
while (reader.HasRows && reader.Read())
{
records.Add(SqliteStmtToRecord(reader));
}
}
}
return records;
}
[SecuritySafeCritical]
internal long GetLastSyncCountHelper(string query, params string[] parameters)
{
long lastSyncCount = 0;
using (var command = new SQLiteCommand(connection))
{
command.CommandText = query;
BindData(command, parameters);
using (var reader = command.ExecuteReader())
{
if (reader.HasRows && reader.Read())
{
var nvc = reader.GetValues();
lastSyncCount = long.Parse(nvc[DatasetColumns.LAST_SYNC_COUNT], CultureInfo.InvariantCulture);
}
}
}
return lastSyncCount;
}
[SecuritySafeCritical]
internal List<Record> GetModifiedRecordsHelper(string query, params object[] parameters)
{
List<Record> records = new List<Record>();
using (var command = new SQLiteCommand(connection))
{
command.CommandText = query;
BindData(command, parameters);
using (var reader = command.ExecuteReader())
{
while (reader.HasRows && reader.Read())
{
records.Add(SqliteStmtToRecord(reader));
}
}
}
return records;
}
[SecuritySafeCritical]
internal void ExecuteMultipleHelper(List<Statement> statements)
{
using (var transaction = connection.BeginTransaction())
{
foreach (var stmt in statements)
{
using (var command = connection.CreateCommand())
{
command.CommandText = stmt.Query;
command.Transaction = transaction;
BindData(command, stmt.Parameters);
command.ExecuteNonQuery();
}
}
transaction.Commit();
}
}
[SecuritySafeCritical]
internal void UpdateLastSyncCountHelper(string query, params object[] parameters)
{
using (var command = connection.CreateCommand())
{
command.CommandText = query;
BindData(command, parameters);
command.ExecuteNonQuery();
}
}
[SecuritySafeCritical]
internal void UpdateLastModifiedTimestampHelper(string query, params object[] parameters)
{
using (var command = connection.CreateCommand())
{
command.CommandText = query;
BindData(command, parameters);
command.ExecuteNonQuery();
}
}
[SecuritySafeCritical]
internal void UpdateOrInsertRecord(string identityId, string datasetName, Record record)
{
lock (sqlite_lock)
{
string checkRecordExistsQuery = "SELECT COUNT(*) FROM " + SQLiteLocalStorage.TABLE_RECORDS + " WHERE " +
RecordColumns.IDENTITY_ID + " = @whereIdentityId AND " +
RecordColumns.DATASET_NAME + " = @whereDatasetName AND " +
RecordColumns.KEY + " = @whereKey ";
bool recordsFound = false;
using (var command = connection.CreateCommand())
{
command.CommandText = checkRecordExistsQuery;
BindData(command, identityId, datasetName, record.Key);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
recordsFound = reader.GetInt32(0) > 0;
}
}
if (recordsFound)
{
string updateRecordQuery =
RecordColumns.BuildUpdate(
new string[] {
RecordColumns.VALUE,
RecordColumns.SYNC_COUNT,
RecordColumns.MODIFIED,
RecordColumns.LAST_MODIFIED_TIMESTAMP,
RecordColumns.LAST_MODIFIED_BY,
RecordColumns.DEVICE_LAST_MODIFIED_TIMESTAMP
},
RecordColumns.IDENTITY_ID + " = @whereIdentityId AND " +
RecordColumns.DATASET_NAME + " = @whereDatasetName AND " +
RecordColumns.KEY + " = @whereKey "
);
using (var command = connection.CreateCommand())
{
command.CommandText = updateRecordQuery;
BindData(command, record.Value, record.SyncCount, record.IsModified ? 1 : 0, record.LastModifiedDate, record.LastModifiedBy, record.DeviceLastModifiedDate, identityId, datasetName, record.Key);
command.ExecuteNonQuery();
}
}
else
{
string insertRecord = RecordColumns.BuildInsert();
using (var command = new SQLiteCommand(insertRecord, connection))
{
BindData(command, identityId, datasetName, record.Key, record.Value, record.SyncCount, record.LastModifiedDate, record.LastModifiedBy, record.DeviceLastModifiedDate, record.IsModified ? 1 : 0);
command.ExecuteNonQuery();
}
}
}
}
#endregion
#region private methods
[SecuritySafeCritical]
private static void BindData(SQLiteCommand command, params object[] parameters)
{
string query = command.CommandText;
int count = 0;
foreach (Match match in Regex.Matches(query, "(\\@\\w+) "))
{
var date = parameters[count] as DateTime?;
if (date.HasValue)
{
command.Parameters.Add(new SQLiteParameter(match.Groups[1].Value, date.Value.Ticks.ToString(CultureInfo.InvariantCulture.NumberFormat)));
}
else
{
command.Parameters.Add(new SQLiteParameter(match.Groups[1].Value, parameters[count]));
}
count++;
}
}
[SecuritySafeCritical]
private static DatasetMetadata SqliteStmtToDatasetMetadata(SQLiteDataReader reader)
{
var nvc = reader.GetValues();
return new DatasetMetadata(
nvc[DatasetColumns.DATASET_NAME],
new DateTime(long.Parse(nvc[DatasetColumns.CREATION_TIMESTAMP], CultureInfo.InvariantCulture.NumberFormat)),
new DateTime(long.Parse(nvc[DatasetColumns.LAST_MODIFIED_TIMESTAMP], CultureInfo.InvariantCulture.NumberFormat)),
nvc[DatasetColumns.LAST_MODIFIED_BY],
long.Parse(nvc[DatasetColumns.STORAGE_SIZE_BYTES], CultureInfo.InvariantCulture.NumberFormat),
long.Parse(nvc[DatasetColumns.RECORD_COUNT], CultureInfo.InvariantCulture.NumberFormat)
);
}
[SecuritySafeCritical]
private static Record SqliteStmtToRecord(SQLiteDataReader reader)
{
var nvc = reader.GetValues();
return new Record(nvc[RecordColumns.KEY], nvc[RecordColumns.VALUE],
int.Parse(nvc[RecordColumns.SYNC_COUNT], CultureInfo.InvariantCulture), new DateTime(long.Parse(nvc[RecordColumns.LAST_MODIFIED_TIMESTAMP], CultureInfo.InvariantCulture.NumberFormat), DateTimeKind.Utc),
nvc[RecordColumns.LAST_MODIFIED_BY], new DateTime(long.Parse(nvc[RecordColumns.DEVICE_LAST_MODIFIED_TIMESTAMP], CultureInfo.InvariantCulture.NumberFormat), DateTimeKind.Utc),
int.Parse(nvc[RecordColumns.MODIFIED], CultureInfo.InvariantCulture) == 1);
}
#endregion
#region BCL Specific implementation for identityId caching
/// <summary>
/// cache the identity
/// </summary>
/// <param name="key"></param>
/// <param name="identity"></param>
[SecuritySafeCritical]
public void CacheIdentity(string key, string identity)
{
string query = "INSERT INTO kvstore(key,value) values ( @key , @value )";
using (var command = connection.CreateCommand())
{
command.CommandText = query;
BindData(command, key, identity);
command.ExecuteNonQuery();
}
}
/// <summary>
/// Get the cached identity id
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
[SecuritySafeCritical]
public string GetIdentity(string key)
{
string query = "SELECT value FROM kvstore WHERE key = @key ";
using (var command = connection.CreateCommand())
{
command.CommandText = query;
BindData(command, key);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
return reader.GetString(0);
}
}
return null;
}
/// <summary>
/// Delete the cached identity id
/// </summary>
/// <param name="key"></param>
[SecuritySafeCritical]
public void DeleteCachedIdentity(string key)
{
string query = "delete from kvstore where key = @key ";
using (var command = connection.CreateCommand())
{
command.CommandText = query;
BindData(command, key);
command.ExecuteNonQuery();
}
}
#endregion
}
}
| 454 |
amazon-cognito-sync-manager-net | aws | C# | #if BCL35
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
using System;
using System.Collections.Generic;
using Amazon.Runtime;
using Amazon.CognitoSync.Model;
using Amazon.Util.Internal;
namespace Amazon.CognitoSync.SyncManager.Internal
{
/// <summary>
/// Remote data storage using Cognito Sync service on which we can invoke
/// actions like creating a dataset or record.
/// </summary>
public partial class CognitoSyncStorage
{
#region GetDataset
private delegate List<DatasetMetadata> PopulateDatasetMetadataDelegate(IAmazonCognitoSync client, ListDatasetsRequest request);
private PopulateDatasetMetadataDelegate DatasetMetadataPopulator = delegate (IAmazonCognitoSync client, ListDatasetsRequest request)
{
var datasets = new List<DatasetMetadata>();
string nextToken = null;
do
{
request.NextToken = nextToken;
ListDatasetsResponse response = client.ListDatasets(request);
foreach (Amazon.CognitoSync.Model.Dataset dataset in response.Datasets)
{
datasets.Add(ModelToDatasetMetadata(dataset));
}
nextToken = response.NextToken;
} while (nextToken != null);
return datasets;
};
private static ListDatasetsRequest PrepareListDatasetsRequest()
{
ListDatasetsRequest request = new ListDatasetsRequest();
// a large enough number to reduce # of requests
request.MaxResults = 64;
return request;
}
/// <summary>
/// Gets a list of <see cref="DatasetMetadata"/>
/// </summary>
/// <exception cref="Amazon.CognitoSync.SyncManager.DataStorageException"></exception>
public List<DatasetMetadata> ListDatasetMetadata()
{
return DatasetMetadataPopulator.Invoke(client, PrepareListDatasetsRequest());
}
/// <summary>
/// Initiates the asynchronous execution of the ListDatasetMetadata operation.
/// </summary>
///
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndBulkPublish
/// operation.</returns>
public IAsyncResult BeginListDatasetMetadata(AsyncCallback callback, object state)
{
return DatasetMetadataPopulator.BeginInvoke(client, PrepareListDatasetsRequest(), callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListDatasetMetadata operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListDatasetMetadata.</param>
public List<DatasetMetadata> EndListDatasetMetadata(IAsyncResult asyncResult)
{
return DatasetMetadataPopulator.EndInvoke(asyncResult);
}
#endregion
#region ListUpdates
private ListRecordsRequest PrepareListRecordsRequest(string datasetName, long lastSyncCount)
{
ListRecordsRequest request = new ListRecordsRequest();
request.IdentityPoolId = identityPoolId;
request.IdentityId = this.GetCurrentIdentityId();
request.DatasetName = datasetName;
request.LastSyncCount = lastSyncCount;
// mark it large enough to reduce # of requests
request.MaxResults = 1024;
return request;
}
private delegate DatasetUpdates PopulateUpdatesDelegate(IAmazonCognitoSync client, ListRecordsRequest request);
private PopulateUpdatesDelegate UpdatesPopulator = delegate (IAmazonCognitoSync client, ListRecordsRequest request)
{
var records = new List<Record>();
ListRecordsResponse response;
string nextToken = null;
do
{
request.NextToken = nextToken;
response = client.ListRecords(request);
foreach (Amazon.CognitoSync.Model.Record remoteRecord in response.Records)
{
records.Add(ModelToRecord(remoteRecord));
}
// update last evaluated key
nextToken = response.NextToken;
} while (nextToken != null);
return new DatasetUpdates(
request.DatasetName,
records,
response.DatasetSyncCount,
response.SyncSessionToken,
response.DatasetExists,
response.DatasetDeletedAfterRequestedSyncCount,
response.MergedDatasetNames
);
};
/// <summary>
/// Gets a list of records which have been updated since lastSyncCount
/// (inclusive). If the value of a record equals null, then the record is
/// deleted. If you pass 0 as lastSyncCount, the full list of records will be
/// returned.
/// </summary>
/// <returns>A list of records which have been updated since lastSyncCount.</returns>
/// <param name="datasetName">Dataset name.</param>
/// <param name="lastSyncCount">Last sync count.</param>
/// <exception cref="Amazon.CognitoSync.SyncManager.DataStorageException"></exception>
public DatasetUpdates ListUpdates(string datasetName, long lastSyncCount)
{
return UpdatesPopulator.Invoke(client, PrepareListRecordsRequest(datasetName, lastSyncCount));
}
/// <summary>
/// Initiates the asynchronous execution of the ListUpdates operation.
/// </summary>
///
/// <param name="datasetName">Dataset name.</param>
/// <param name="lastSyncCount">Last sync count.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndBulkPublish
/// operation.</returns>
public IAsyncResult BeginListUpdates(string datasetName, long lastSyncCount, AsyncCallback callback, object state)
{
return UpdatesPopulator.BeginInvoke(client, PrepareListRecordsRequest(datasetName, lastSyncCount), callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListUpdates operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListUpdates.</param>
/// <returns>A list of records which have been updated since lastSyncCount.</returns>
public DatasetUpdates EndListUpdates(IAsyncResult asyncResult)
{
return UpdatesPopulator.EndInvoke(asyncResult);
}
#endregion
#region PutRecords
private UpdateRecordsRequest PrepareUpdateRecordsRequest(string datasetName, List<Record> records, string syncSessionToken)
{
UpdateRecordsRequest request = new UpdateRecordsRequest();
request.DatasetName = datasetName;
request.IdentityPoolId = identityPoolId;
request.IdentityId = this.GetCurrentIdentityId();
request.SyncSessionToken = syncSessionToken;
// create patches
List<RecordPatch> patches = new List<RecordPatch>();
foreach (Record record in records)
{
patches.Add(RecordToPatch(record));
}
request.RecordPatches = patches;
return request;
}
private static List<Record> ExtractRecords(UpdateRecordsResponse response)
{
List<Record> updatedRecords = new List<Record>();
foreach (Amazon.CognitoSync.Model.Record remoteRecord in response.Records)
{
updatedRecords.Add(ModelToRecord(remoteRecord));
}
return updatedRecords;
}
/// <summary>
/// Post updates to remote storage. Each record has a sync count. If the sync
/// count doesn't match what's on the remote storage, i.e. the record is
/// modified by a different device, this operation throws ConflictException.
/// Otherwise it returns a list of records that are updated successfully.
/// </summary>
/// <returns>The records.</returns>
/// <param name="datasetName">Dataset name.</param>
/// <param name="records">Records.</param>
/// <param name="syncSessionToken">Sync session token.</param>
/// <exception cref="Amazon.CognitoSync.SyncManager.DatasetNotFoundException"></exception>
/// <exception cref="Amazon.CognitoSync.SyncManager.DataConflictException"></exception>
public List<Record> PutRecords(string datasetName, List<Record> records, string syncSessionToken)
{
UpdateRecordsResponse response = client.UpdateRecords(PrepareUpdateRecordsRequest(datasetName, records, syncSessionToken));
return ExtractRecords(response);
}
/// <summary>
/// Initiates the asynchronous execution of the PutRecords operation.
/// </summary>
///
/// <param name="datasetName">Dataset name.</param>
/// <param name="records">Records.</param>
/// <param name="syncSessionToken">Sync session token.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutRecords
/// operation.</returns>
public IAsyncResult BeginPutRecords(string datasetName, List<Record> records, string syncSessionToken, AsyncCallback callback, object state)
{
return client.BeginUpdateRecords(PrepareUpdateRecordsRequest(datasetName, records, syncSessionToken), callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the PutRecords operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutRecords.</param>
public List<Record> EndPutRecords(IAsyncResult asyncResult)
{
try
{
UpdateRecordsResponse response = client.EndUpdateRecords(asyncResult);
return ExtractRecords(response);
}
catch (Exception ex)
{
throw HandleException(ex, "Failed to update records in dataset");
}
}
#endregion
#region DeleteDataset
private DeleteDatasetRequest PrepareDeleteDatasetRequest(string datasetName)
{
DeleteDatasetRequest request = new DeleteDatasetRequest();
request.IdentityPoolId = identityPoolId;
request.IdentityId = this.GetCurrentIdentityId();
request.DatasetName = datasetName;
return request;
}
/// <summary>
/// Deletes a dataset.
/// </summary>
/// <param name="datasetName">Dataset name.</param>
/// <exception cref="Amazon.CognitoSync.SyncManager.DatasetNotFoundException"></exception>
public void DeleteDataset(string datasetName)
{
client.DeleteDataset(PrepareDeleteDatasetRequest(datasetName));
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteDataset operation.
/// </summary>
///
/// <param name="datasetName">Dataset name.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteDataset
/// operation.</returns>
public IAsyncResult BeginDeleteDataset(string datasetName, AsyncCallback callback, object state)
{
return client.BeginDeleteDataset(PrepareDeleteDatasetRequest(datasetName), callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteDataset operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteDataset.</param>
public void EndDeleteDataset(IAsyncResult asyncResult)
{
try
{
client.EndDeleteDataset(asyncResult);
}
catch (Exception ex)
{
throw HandleException(ex, "Failed to delete dataset");
}
client.EndDeleteDataset(asyncResult);
}
#endregion
#region GetDatasetMetadata
private DescribeDatasetRequest PrepareDescribeDatasetRequest(string datasetName)
{
DescribeDatasetRequest request = new DescribeDatasetRequest();
request.IdentityPoolId = identityPoolId;
request.IdentityId = this.GetCurrentIdentityId();
request.DatasetName = datasetName;
return request;
}
/// <summary>
/// Retrieves the metadata of a dataset.
/// </summary>
/// <param name="datasetName">Dataset name.</param>
/// <exception cref="Amazon.CognitoSync.SyncManager.DataStorageException"></exception>
public DatasetMetadata GetDatasetMetadata(string datasetName)
{
return ModelToDatasetMetadata(client.DescribeDataset(PrepareDescribeDatasetRequest(datasetName)).Dataset);
}
/// <summary>
/// Initiates the asynchronous execution of the GetDatasetMetadata operation.
/// </summary>
///
/// <param name="datasetName">Dataset name.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetDatasetMetadata
/// operation.</returns>
public IAsyncResult BeginGetDatasetMetadata(string datasetName, AsyncCallback callback, object state)
{
return client.BeginDescribeDataset(PrepareDescribeDatasetRequest(datasetName), callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetDatasetMetadata operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetDatasetMetadata.</param>
public DatasetMetadata EndGetDatasetMetadata(IAsyncResult asyncResult)
{
try
{
return ModelToDatasetMetadata(client.EndDescribeDataset(asyncResult).Dataset);
}
catch (Exception ex)
{
throw new DataStorageException("Failed to get metadata of dataset", ex);
}
}
#endregion
}
}
#endif | 372 |
amazon-cognito-sync-manager-net | aws | C# | //
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
using System;
using System.Text.RegularExpressions;
using Amazon.CognitoIdentity;
using Amazon.Runtime.Internal.Util;
using System.Text;
namespace Amazon.CognitoSync.SyncManager.Internal
{
/// <summary>
/// A Utility class for all the dataset operations
/// </summary>
public static class DatasetUtils
{
/// <summary>
/// Valid dataset name pattern
/// </summary>
public static readonly string DATASET_NAME_PATTERN = @"^[a-zA-Z0-9_.:-]{1,128}$";
/// <summary>
/// Unknown identity id when the identity id is null
/// </summary>
public static readonly string UNKNOWN_IDENTITY_ID = "unknown";
/// <summary>
/// Validates the dataset name.
/// </summary>
/// <returns>The dataset name.</returns>
/// <param name="datasetName">Dataset name.</param>
public static string ValidateDatasetName(string datasetName)
{
if (!Regex.IsMatch(datasetName, DATASET_NAME_PATTERN))
{
throw new ArgumentException("Invalid dataset name");
}
return datasetName;
}
/// <summary>
/// Validates the record key. It must be non empty and its length must be no
/// greater than 128. Otherwise {@link IllegalArgumentException} will be
/// thrown.
/// </summary>
/// <returns>The record key.</returns>
/// <param name="key">Key.</param>
public static string ValidateRecordKey(string key)
{
if (string.IsNullOrEmpty(key) || Encoding.UTF8.GetByteCount(key) > 128)
{
throw new ArgumentException("Invalid record key");
}
return key;
}
/// <summary>
/// A helper function to compute record size which equals the sum of the
/// UTF-8 string length of record key and value. 0 if record is null.
/// </summary>
/// <returns>The record size.</returns>
/// <param name="record">Record.</param>
public static long ComputeRecordSize(Record record)
{
if (record == null)
{
return 0;
}
return Encoding.UTF8.GetByteCount(record.Key)
+ Encoding.UTF8.GetByteCount(record.Value);
}
/// <summary>
/// A helper function to get the identity id of the dataset from credentials
/// provider. If the identity id is null, UNKNOWN_IDENTITY_ID will be
/// returned.
/// </summary>
/// <param name="credentials">The Cognito Credentials.</param>
/// <returns>The identity identifier.</returns>
public static string GetIdentityId(CognitoAWSCredentials credentials)
{
return string.IsNullOrEmpty(credentials.GetCachedIdentityId())
? UNKNOWN_IDENTITY_ID
: credentials.GetCachedIdentityId();
}
/// <summary>
/// A helper function to truncate a DateTime object to whole seconds.
/// </summary>
/// <returns>The truncated DateTime</returns>
/// <param name="dateTime">The DateTime to be truncated.</param>
public static DateTime TruncateToSeconds(DateTime dateTime)
{
return dateTime.AddTicks(-(dateTime.Ticks % TimeSpan.TicksPerSecond));
}
}
}
| 104 |
amazon-cognito-sync-manager-net | aws | C# | #if AWS_ASYNC_API
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Amazon.CognitoSync.SyncManager
{
public partial class CognitoSyncManager
{
/// <summary>
/// Refreshes dataset metadata. Dataset metadata is pulled from remote
/// storage and stored in local storage. Their record data isn't pulled down
/// until you sync each dataset.
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <exception cref="Amazon.CognitoSync.SyncManager.DataStorageException">Thrown when fail to fresh dataset metadata</exception>
public async Task<List<DatasetMetadata>> RefreshDatasetMetadataAsync(CancellationToken cancellationToken = default(CancellationToken))
{
List<DatasetMetadata> response = await Remote.ListDatasetMetadataAsync(cancellationToken).ConfigureAwait(false);
Local.UpdateDatasetMetadata(IdentityId, response);
return response;
}
}
}
#endif | 30 |
amazon-cognito-sync-manager-net | aws | C# | using Amazon.CognitoIdentity;
using Amazon.CognitoSync.SyncManager.Internal;
using System;
namespace Amazon.CognitoSync.SyncManager
{
/// <summary>
/// The SQLiteCognitoAWSCredentials extends from <see cref="Amazon.CognitoIdentity.CognitoAWSCredentials"/>
/// and adds support for caching of identity id using SQLite
/// </summary>
public class SQLiteCognitoAWSCredentials : CognitoAWSCredentials
{
/// <summary>
/// Constructs a new SQLiteCognitoAWSCredentials instance, which will use the
/// specified Amazon Cognito identity pool to get short lived session credentials.
/// </summary>
/// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
/// <param name="region">Region to use when accessing Amazon Cognito and AWS Security Token Service.</param>
public SQLiteCognitoAWSCredentials(string identityPoolId, RegionEndpoint region)
: base(identityPoolId, region) { }
/// <summary>
/// Constructs a new SQLiteCognitoAWSCredentials instance, which will use the
/// specified Amazon Cognito identity pool to make a requests to the
/// AWS Security Token Service (STS) to request short lived session credentials.
/// </summary>
/// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
/// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
/// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
/// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
/// <param name="region">Region to use when accessing Amazon Cognito and AWS Security Token Service.</param>
public SQLiteCognitoAWSCredentials(string accountId, string identityPoolId, string unAuthRoleArn, string authRoleArn, RegionEndpoint region)
: base(accountId, identityPoolId, unAuthRoleArn, authRoleArn, region) { }
private const String IDENTITY_ID_CACHE_KEY = "CognitoIdentity:IdentityId";
/// <summary>
/// Caches the identity id retrieved from Cognito.
/// </summary>
/// <param name="identityId">The Cognito identity id to cache</param>
[System.Security.SecuritySafeCritical]
public override void CacheIdentityId(string identityId)
{
base.CacheIdentityId(identityId);
using (var kvStore = new SQLiteLocalStorage())
{
kvStore.CacheIdentity(GetNamespacedKey(IDENTITY_ID_CACHE_KEY), identityId);
}
}
/// <summary>
/// Clears the currently identity id from the cache.
/// </summary>
[System.Security.SecuritySafeCritical]
public override void ClearIdentityCache()
{
base.ClearIdentityCache();
using (var kvStore = new SQLiteLocalStorage())
{
kvStore.DeleteCachedIdentity(GetNamespacedKey(IDENTITY_ID_CACHE_KEY));
}
}
/// <summary>
/// Gets the previously cached the identity id retrieved from Cognito.
/// </summary>
/// <returns>The previously cached identity id</returns>
[System.Security.SecuritySafeCritical]
public override string GetCachedIdentityId()
{
string identityId = null;
using (var kvStore = new SQLiteLocalStorage())
{
identityId = kvStore.GetIdentity(GetNamespacedKey(IDENTITY_ID_CACHE_KEY));
}
return identityId;
}
}
}
| 85 |
amazon-cognito-sync-manager-net | aws | C# | #if BCL35
using Amazon.CognitoSync.SyncManager.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Amazon.CognitoSync.SyncManager
{
public partial class CognitoSyncManager
{
private delegate List<DatasetMetadata> RefreshDatasetMetadataInnerDelegate(CognitoSyncStorage remote, ILocalStorage local, string identityId);
private RefreshDatasetMetadataInnerDelegate RefreshDatasetMetadataInnerHandler = delegate (CognitoSyncStorage remote, ILocalStorage local, string identityId)
{
List<DatasetMetadata> response = remote.ListDatasetMetadata();
local.UpdateDatasetMetadata(identityId, response);
return response;
};
/// <summary>
/// Initiates the asynchronous execution of the RefreshDatasetMetadata operation.
///
/// Refreshes dataset metadata. Dataset metadata is pulled from remote
/// storage and stored in local storage. Their record data isn't pulled down
/// until you sync each dataset.
/// </summary>
///
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
public IAsyncResult BeginRefreshDatasetMetadata(AsyncCallback callback, object state)
{
return RefreshDatasetMetadataInnerHandler.BeginInvoke(Remote, Local, IdentityId, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the RefreshDatasetMetadata operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRefreshDatasetMetadata.</param>
public List<DatasetMetadata> EndRefreshDatasetMetadata(IAsyncResult asyncResult)
{
return RefreshDatasetMetadataInnerHandler.EndInvoke(asyncResult);
}
}
}
#endif | 46 |
amazon-cognito-sync-manager-net | aws | C# | #if BCL35
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
using Amazon.CognitoIdentity;
using Amazon.CognitoSync.SyncManager.Internal;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Threading;
namespace Amazon.CognitoSync.SyncManager
{
public partial class Dataset : IDisposable
{
private void DatasetSetupInternal()
{
NetworkChange.NetworkAvailabilityChanged += HandleNetworkChange;
}
#region Dispose Methods
/// <summary>
/// Releases the resources consumed by this object if disposing is true.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
ClearAllDelegates();
NetworkChange.NetworkAvailabilityChanged -= HandleNetworkChange;
_disposed = true;
}
}
#endregion
#region Public Methods
/// <summary>
/// Synchronize <see cref="Dataset"/> between local storage and remote storage.
/// </summary>
/// <seealso href="http://docs.aws.amazon.com/cognito/latest/developerguide/synchronizing-data.html#synchronizing-local-data">Amazon Cognito Sync Dev. Guide - Synchronizing Local Data with the Sync Store</seealso>
public virtual void Synchronize()
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
FireSyncFailureEvent(new NetworkException("Network connectivity unavailable."));
return;
}
SynchronizeHelper();
}
/// <summary>
/// Attempt to synchronize <see cref="Dataset"/> when connectivity is available. If
/// the connectivity is available right away, it behaves the same as
/// <see cref="Dataset.Synchronize()"/>. Otherwise it listens to connectivity
/// changes, and will do a sync once the connectivity is back. Note that if
/// this method is called multiple times, only the last synchronize request
/// is kept. If either the dataset or the callback is garbage collected
/// , this method will not perform a sync and the callback won't fire.
/// </summary>
public virtual void SynchronizeOnConnectivity()
{
if (NetworkInterface.GetIsNetworkAvailable())
{
SynchronizeHelper();
}
else
{
waitingForConnectivity = true;
}
}
#endregion
#region Private Methods
private void HandleNetworkChange(object sender, NetworkAvailabilityEventArgs e)
{
if (!waitingForConnectivity)
{
return;
}
if (e.IsAvailable)
{
Synchronize();
}
}
#endregion
private void SynchronizeHelper()
{
try
{
if (locked)
{
_logger.InfoFormat("Already in a Synchronize. Queueing new request.", DatasetName);
queuedSync = true;
return;
}
else
{
locked = true;
}
waitingForConnectivity = false;
SynchornizeInternal();
}
catch (Exception e)
{
FireSyncFailureEvent(e);
_logger.Error(e, "");
}
}
}
}
#endif | 127 |
amazon-cognito-sync-manager-net | aws | C# | #if BCL45
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
using Amazon.CognitoIdentity;
using Amazon.CognitoSync.SyncManager.Internal;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
namespace Amazon.CognitoSync.SyncManager
{
public partial class Dataset : IDisposable
{
private void DatasetSetupInternal()
{
NetworkChange.NetworkAvailabilityChanged += HandleNetworkChange;
}
#region Dispose Methods
/// <summary>
/// Releases the resources consumed by this object if disposing is true.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
ClearAllDelegates();
NetworkChange.NetworkAvailabilityChanged -= HandleNetworkChange;
_disposed = true;
}
}
#endregion
#region Public Methods
/// <summary>
/// Attempt to synchronize <see cref="Dataset"/> when connectivity is available. If
/// the connectivity is available right away, it behaves the same as
/// <see cref="Dataset.SynchronizeAsync"/>. Otherwise it listens to connectivity
/// changes, and will do a sync once the connectivity is back. Note that if
/// this method is called multiple times, only the last synchronize request
/// is kept. If either the dataset or the callback is garbage collected
/// , this method will not perform a sync and the callback won't fire.
/// </summary>
public async Task SynchronizeOnConnectivity(CancellationToken cancellationToken = default(CancellationToken))
{
if (NetworkInterface.GetIsNetworkAvailable())
{
await SynchronizeHelperAsync(cancellationToken).ConfigureAwait(false);
}
else
{
waitingForConnectivity = true;
}
}
#endregion
#region Private Methods
private async void HandleNetworkChange(object sender, NetworkAvailabilityEventArgs e)
{
if (!waitingForConnectivity)
{
return;
}
if (e.IsAvailable)
{
await SynchronizeAsync().ConfigureAwait(false);
}
}
#endregion
/// <summary>
/// Synchronize <see cref="Dataset"/> between local storage and remote storage.
/// </summary>
/// <seealso href="http://docs.aws.amazon.com/cognito/latest/developerguide/synchronizing-data.html#synchronizing-local-data">Amazon Cognito Sync Dev. Guide - Synchronizing Local Data with the Sync Store</seealso>
public async Task SynchronizeAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
FireSyncFailureEvent(new NetworkException("Network connectivity unavailable."));
return;
}
await SynchronizeHelperAsync(cancellationToken).ConfigureAwait(false);
}
internal async Task SynchronizeHelperAsync(CancellationToken cancellationToken)
{
try
{
if (locked)
{
_logger.InfoFormat("Already in a Synchronize. Queueing new request.", DatasetName);
queuedSync = true;
return;
}
else
{
locked = true;
}
waitingForConnectivity = false;
//make a call to fetch the identity id before the synchronization starts
await CognitoCredentials.GetIdentityIdAsync().ConfigureAwait(false);
// there could be potential merges that could have happened due to reparenting from the previous step,
// check and call onDatasetMerged
bool resume = true;
List<string> mergedDatasets = LocalMergedDatasets;
if (mergedDatasets.Count > 0)
{
_logger.InfoFormat("Detected merge datasets - {0}", DatasetName);
if (this.OnDatasetMerged != null)
{
resume = this.OnDatasetMerged(this, mergedDatasets);
}
}
if (!resume)
{
FireSyncFailureEvent(new OperationCanceledException(string.Format("Sync canceled on merge for dataset - {0}", this.DatasetName)));
return;
}
await RunSyncOperationAsync(MAX_RETRY, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
FireSyncFailureEvent(e);
_logger.Error(e, "");
}
}
}
}
#endif | 154 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Runtime.CompilerServices;
[assembly: System.Reflection.AssemblyCompany("Amazon Web Services")]
[assembly: System.Reflection.AssemblyTitle("GameLift Plugin Editor")]
[assembly: System.Reflection.AssemblyCopyright("Copyright 2021.")]
[assembly: InternalsVisibleTo("AmazonGameLiftPlugin.Editor.UiTests")]
[assembly: InternalsVisibleTo("AmazonGameLiftPlugin.Editor.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
| 12 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal static class AssetNames
{
public const string SpinnerIcon = "Spinner";
public const string GameLiftLogo = "GameLiftLogo";
}
}
| 12 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal static class DevStrings
{
public const string BucketNameTooLong = "The bucket name is too long.";
public const string OperationInvalid = "There was a problem with the operation.";
public const string StringNullOrEmpty = "The string is null or empty.";
public const string ProfileInvalid = "The was a problem with the AWS profile.";
public const string RegionInvalid = "The was a problem with the AWS Region.";
public const string FailedToDescribeStackTemplate = "There was a problem refreshing stack status. {0}";
}
}
| 16 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal static class EditorMenu
{
[MenuItem("GameLift/Import Sample Game", priority = 8000)]
public static void ImportSampleGame()
{
string filePackagePath = $"Packages/{Paths.PackageName}/{Paths.SampleGameInPackage}";
AssetDatabase.ImportPackage(filePackagePath, interactive: true);
}
[MenuItem("GameLift/Plugin Settings", priority = 0)]
public static void ShowPluginSettings()
{
Assembly unityEditorAssembly = typeof(UnityEditor.Editor).Assembly;
Type settingsWindowType = unityEditorAssembly.GetType("UnityEditor.SceneHierarchyWindow");
if (settingsWindowType == null)
{
settingsWindowType = unityEditorAssembly.GetType("UnityEditor.InspectorWindow");
}
EditorWindow.GetWindow<SettingsWindow>(settingsWindowType);
}
public static void ShowDeployment()
{
EditorWindow.GetWindow<DeploymentWindow>();
}
public static void ShowLocalTesting()
{
EditorWindow.GetWindow<LocalTestWindow>();
}
public static void OpenForums()
{
Application.OpenURL(Urls.AwsGameTechForums);
}
public static void OpenGameLiftServerCSharpSdkIntegrationDoc()
{
Application.OpenURL(Urls.GameLiftServerCSharpSdkIntegrationDoc);
}
public static void OpenGameLiftServerCSharpSdkApiDoc()
{
Application.OpenURL(Urls.GameLiftServerCSharpSdkApiDoc);
}
public static void OpenAwsDocumentation()
{
Application.OpenURL(Urls.AwsHelpGameLiftUnity);
}
public static void ReportSecurity()
{
Application.OpenURL(Urls.AwsSecurity);
}
public static void ReportBugs()
{
Application.OpenURL(Urls.GitHubAwsLabs);
}
public static void PingSdk()
{
string filePackagePath = $"Packages/{Paths.PackageName}/{Paths.ServerSdkDllInPackage}";
UnityEngine.Object sdk = AssetDatabase.LoadMainAssetAtPath(filePackagePath);
Type projectBrowser = typeof(UnityEditor.Editor).Assembly.GetType("UnityEditor.ProjectBrowser");
if (projectBrowser != null) {
// Show Project Browser window
EditorWindow.GetWindow(projectBrowser).Show();
} else {
Debug.LogError($"Cannot open the Unity Project Browser window.");
return;
}
if (sdk != null)
{
// Show SDK DLL in Unity Inspector
Selection.activeObject = sdk;
// Highlight SDK DLL in Unity Project Browser
EditorGUIUtility.PingObject(sdk);
} else {
Debug.LogError($"Cannot find GameLift SDK DLL in asset path: {filePackagePath}. "
+ "Try downloading the Plugin package and import again.");
}
}
}
}
| 105 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal static class EditorWindowExtensions
{
public static void SetConstantSize(this EditorWindow window, Vector2 size)
{
if (!window)
{
return;
}
window.minSize = size;
window.maxSize = size;
}
}
}
| 23 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLift.Runtime;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
[CustomEditor(typeof(GameLiftClientSettings))]
public sealed class GameLiftClientSettingsEditor : UnityEditor.Editor
{
private SerializedProperty _isLocalTest;
private SerializedProperty _localPort;
private SerializedProperty _remoteUrl;
private SerializedProperty _region;
private SerializedProperty _poolClientId;
private void OnEnable()
{
_isLocalTest = serializedObject.FindProperty(nameof(GameLiftClientSettings.IsLocalTest));
_localPort = serializedObject.FindProperty(nameof(GameLiftClientSettings.LocalPort));
_remoteUrl = serializedObject.FindProperty(nameof(GameLiftClientSettings.ApiGatewayUrl));
_region = serializedObject.FindProperty(nameof(GameLiftClientSettings.AwsRegion));
_poolClientId = serializedObject.FindProperty(nameof(GameLiftClientSettings.UserPoolClientId));
}
public override void OnInspectorGUI()
{
serializedObject.Update();
var targetSettings = (GameLiftClientSettings)target;
EditorGUILayout.PropertyField(_isLocalTest, new GUIContent("Local Testing Mode", "Enabling this to make sample game client connect to game server running on localhost"));
try
{
if (targetSettings.IsLocalTest)
{
EditLocalMode(targetSettings);
}
else
{
EditGameLiftMode(targetSettings);
}
}
finally
{
serializedObject.ApplyModifiedProperties();
}
}
private void EditLocalMode(GameLiftClientSettings targetSettings)
{
EditorGUILayout.LabelField("GameLift Local URL", targetSettings.LocalUrl);
EditorGUILayout.PropertyField(_localPort, new GUIContent("GameLift Local Port", "This port should match the port value defined in Local Testing"));
if (targetSettings.LocalPort == 0)
{
EditorGUILayout.HelpBox("Please set the GameLift Local port.", MessageType.Warning);
}
}
private void EditGameLiftMode(GameLiftClientSettings targetSettings)
{
EditorGUILayout.PropertyField(_remoteUrl, new GUIContent("API Gateway Endpoint", "API Gateway URL"));
EditorGUILayout.PropertyField(_region, new GUIContent("AWS Region", "AWS region used for communicating with Cognito and API Gateway"));
EditorGUILayout.PropertyField(_poolClientId, new GUIContent("Cognito Client ID"));
if (string.IsNullOrWhiteSpace(targetSettings.ApiGatewayUrl))
{
EditorGUILayout.HelpBox("Please set the API Gateway URL.", MessageType.Warning);
}
if (string.IsNullOrWhiteSpace(targetSettings.AwsRegion))
{
EditorGUILayout.HelpBox("Please set the AWS Region.", MessageType.Warning);
}
if (string.IsNullOrWhiteSpace(targetSettings.UserPoolClientId))
{
EditorGUILayout.HelpBox("Please set the User Pool Client ID.", MessageType.Warning);
}
}
}
}
| 86 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
[Serializable]
internal class HyperLinkButton
{
private readonly string _label;
private readonly GUIStyle _linkStyle;
public string Url { get; set; }
public HyperLinkButton(string label, string url, GUIStyle linkStyle)
{
_label = label ?? throw new ArgumentNullException(nameof(label));
Url = url ?? throw new ArgumentNullException(nameof(url));
_linkStyle = linkStyle ?? throw new ArgumentNullException(nameof(linkStyle));
}
public void Draw()
{
using (new GUILayout.VerticalScope())
{
if (GUILayout.Button(_label, _linkStyle))
{
Application.OpenURL(Url);
}
Rect position = GUILayoutUtility.GetLastRect();
Handles.BeginGUI();
{
Color defaultColor = Handles.color;
Handles.color = _linkStyle.normal.textColor;
var p1 = new Vector3(position.xMin, position.yMax + 2f);
var p2 = new Vector3(position.xMax, position.yMax + 2f);
Handles.DrawLine(p1, p2);
Handles.color = defaultColor;
}
Handles.EndGUI();
GUILayout.Space(2f);
}
}
}
}
| 52 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.Shared;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal interface ILogger
{
void Log(string message, LogType logType);
void LogResponseError(Response response, LogType logType = LogType.Error);
void LogException(Exception ex);
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class ImageLoader
{
/// <summary>
/// Loads all <see cref="Texture2D"/>s named "{<paramref name="assetNameBase"/>} {i}"
/// where i is in [<paramref name="first"/>; <paramref name="last"/>].
/// </summary>
public IReadOnlyList<Texture2D> LoadImageSequence(string assetNameBase, int first, int last)
{
var sequence = new List<Texture2D>();
for (int i = first; i <= last; i++)
{
string assetName = $"{assetNameBase} {i}";
Texture2D texture = LoadImage(assetName);
if (!texture)
{
continue;
}
sequence.Add(texture);
}
return sequence;
}
public Texture2D LoadImage(string assetName)
{
if (assetName is null)
{
throw new ArgumentNullException(nameof(assetName));
}
Texture2D texture = Load(ResourceUtility.GetImagePath(assetName));
if (texture)
{
return texture;
}
return Load(ResourceUtility.GetImagePathForCurrentTheme(assetName));
}
protected virtual Texture2D Load(string assetPath)
{
return Resources.Load<Texture2D>(assetPath);
}
}
}
| 59 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using UnityEditor;
namespace AmazonGameLift.Editor
{
internal interface IReadStatus
{
bool IsDisplayed { get; }
string Message { get; }
MessageType Type { get; }
event Action Changed;
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using UnityEngine;
using AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models;
namespace AmazonGameLift.Editor
{
// See available operating system types: https://docs.unity3d.com/ScriptReference/SystemInfo-operatingSystem.html
internal class OperatingSystemUtility
{
public static LocalOperatingSystem GetLocalOperatingSystem()
{
if (isMacOs())
{
return LocalOperatingSystem.MAC_OS;
}
if (isWindows())
{
return LocalOperatingSystem.WINDOWS;
}
return LocalOperatingSystem.UNSUPPORTED;
}
public static bool isMacOs()
{
return SystemInfo.operatingSystem.StartsWith("Mac OS");
}
public static bool isWindows()
{
return SystemInfo.operatingSystem.StartsWith("Windows");
}
}
}
| 38 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class ResourceUtility
{
private static IReadOnlyDictionary<MessageType, GUIStyle> s_cachedMessageStyles;
private static GUIStyle s_cachedConfiguredStyle;
private static GUIStyle s_cachedNotConfiguredStyle;
private static GUIStyle s_cachedRadioButtonStyle;
private static GUIStyle s_cachedHyperLinkStyle;
private static GUIStyle s_cachedInfoLabelStyle;
private static GUIStyle s_cachedTabActiveStyle;
private static bool s_cachedProSkin;
public static string GetImagePathForCurrentTheme(string assetName)
{
string skinPath = EditorGUIUtility.isProSkin ? "Dark" : "Light";
return string.Format("Images/{0}/{1}", skinPath, assetName);
}
public static string GetImagePath(string assetName)
{
return string.Format("Images/{0}", assetName);
}
/// <summary>
/// Call this only from OnGUI().
/// </summary>
public static IReadOnlyDictionary<MessageType, GUIStyle> GetMessageStyles()
{
ClearCacheIfSkinChanged();
if (s_cachedMessageStyles != null)
{
return s_cachedMessageStyles;
}
// EditorStyles are not ready when Unity starts.
var styles = new Dictionary<MessageType, GUIStyle>
{
[MessageType.None] = new GUIStyle(EditorStyles.label)
};
var info = new GUIStyle
{
wordWrap = true
};
info.normal.textColor = EditorGUIUtility.isProSkin
? new Color32(0x64, 0xD6, 0x97, 0xFF)
: new Color32(0x00, 0x46, 0x37, 0xFF);
styles[MessageType.Info] = info;
var warning = new GUIStyle
{
wordWrap = true
};
warning.normal.textColor = new Color32(255, 255, 0, 255);
styles[MessageType.Warning] = warning;
var error = new GUIStyle
{
wordWrap = true
};
error.normal.textColor = new Color32(255, 0, 0, 255);
styles[MessageType.Error] = error;
s_cachedMessageStyles = styles;
return styles;
}
public static GUIStyle GetInfoLabelStyle()
{
ClearCacheIfSkinChanged();
if (s_cachedInfoLabelStyle != null)
{
return s_cachedInfoLabelStyle;
}
var style = new GUIStyle();
style.normal.textColor = EditorGUIUtility.isProSkin
? new Color32(0x9D, 0x9D, 0x9D, 0xFF)
: new Color32(0x30, 0x30, 0x30, 0xFF);
style.fontSize = 11;
style.wordWrap = true;
s_cachedInfoLabelStyle = style;
return style;
}
/// <summary>
/// Call this only from OnGUI().
/// </summary>
public static GUIStyle GetRadioButtonStyle()
{
if (s_cachedRadioButtonStyle != null)
{
return s_cachedRadioButtonStyle;
}
// EditorStyles are not ready when Unity starts.
var style = new GUIStyle(EditorStyles.radioButton);
style.normal.textColor = new Color32(0x83, 0x83, 0x83, 0xFF);
s_cachedRadioButtonStyle = style;
return style;
}
public static GUIStyle GetHyperLinkStyle()
{
ClearCacheIfSkinChanged();
if (s_cachedHyperLinkStyle != null)
{
return s_cachedHyperLinkStyle;
}
var style = new GUIStyle
{
wordWrap = false,
stretchWidth = false
};
style.normal.textColor = EditorGUIUtility.isProSkin
? new Color32(0x4B, 0x7E, 0xFF, 0xFF)
: new Color32(0x1B, 0x53, 0xE0, 0xFF);
s_cachedHyperLinkStyle = style;
return style;
}
public static GUIStyle GetConfiguredStyle()
{
ClearCacheIfSkinChanged();
if (s_cachedConfiguredStyle != null)
{
return s_cachedConfiguredStyle;
}
var configuredStyle = new GUIStyle(EditorStyles.largeLabel);
configuredStyle.normal.textColor = EditorGUIUtility.isProSkin
? new Color32(0x64, 0xD6, 0x97, 0xFF)
: new Color32(0x00, 0x46, 0x37, 0xFF);
s_cachedConfiguredStyle = configuredStyle;
return configuredStyle;
}
public static GUIStyle GetNotConfiguredStyle()
{
ClearCacheIfSkinChanged();
if (s_cachedNotConfiguredStyle != null)
{
return s_cachedNotConfiguredStyle;
}
var notConfiguredStyle = new GUIStyle(EditorStyles.largeLabel);
notConfiguredStyle.normal.textColor = EditorGUIUtility.isProSkin
? new Color32(0xFF, 0x94, 0x00, 0xFF)
: new Color32(0xB1, 0x0B, 0x0B, 0xFF);
s_cachedNotConfiguredStyle = notConfiguredStyle;
return notConfiguredStyle;
}
public static GUIStyle GetTextFilterNormalStyle()
{
ClearCacheIfSkinChanged();
Color32 selectedColor = GetTextFilterSelectedBackColor();
Texture2D selectedBackTexture = GetSmallTexture(selectedColor);
Color32 normalColor = GetTextFilterBackColor();
Texture2D normalBackTexture = GetSmallTexture(normalColor);
var normalStyle = new GUIStyle(EditorStyles.label); // Cannot use during initialization
normalStyle.normal.background = normalBackTexture;
normalStyle.active.background = selectedBackTexture;
return normalStyle;
}
public static GUIStyle GetTextFilterSelectedStyle()
{
ClearCacheIfSkinChanged();
Color32 selectedColor = GetTextFilterSelectedBackColor();
Texture2D selectedBackTexture = GetSmallTexture(selectedColor);
var selectedStyle = new GUIStyle(EditorStyles.label); // Cannot use during initialization
selectedStyle.normal.background = selectedBackTexture;
selectedStyle.active.background = selectedBackTexture;
selectedStyle.normal.textColor = Color.white;
return selectedStyle;
}
public static GUIStyle GetTabActiveStyle()
{
ClearCacheIfSkinChanged();
if (s_cachedTabActiveStyle != null)
{
return s_cachedTabActiveStyle;
}
var style = new GUIStyle(EditorStyles.toolbarButton);
style.normal.textColor = new Color32(0xFF, 0xAA, 0x00, 0xFF); // Amazon Orange
style.hover.textColor = new Color32(0xFF, 0xAA, 0x00, 0xFF); // Amazon Orange
style.fontStyle = FontStyle.Bold;
s_cachedTabActiveStyle = style;
return style;
}
public static GUIStyle GetTabNormalStyle()
{
return EditorStyles.toolbarButton;
}
private static Texture2D GetSmallTexture(Color color)
{
var texture = new Texture2D(1, 1);
texture.SetPixel(0, 0, color);
texture.Apply();
return texture;
}
private static Color32 GetTextFilterSelectedBackColor()
{
return new Color32(0x33, 0x33, 0xCC, 0xFF);
}
private static Color32 GetTextFilterBackColor()
{
return EditorGUIUtility.isProSkin ? new Color32(0x51, 0x51, 0x51, 0xFF) : new Color32(0xDF, 0xDF, 0xDF, 0xFF);
}
private static void ClearCacheIfSkinChanged()
{
if (s_cachedProSkin == EditorGUIUtility.isProSkin)
{
return;
}
s_cachedProSkin = EditorGUIUtility.isProSkin;
s_cachedConfiguredStyle = null;
s_cachedHyperLinkStyle = null;
s_cachedInfoLabelStyle = null;
s_cachedMessageStyles = null;
s_cachedNotConfiguredStyle = null;
s_cachedRadioButtonStyle = null;
s_cachedTabActiveStyle = null;
}
}
}
| 252 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using UnityEditor;
namespace AmazonGameLift.Editor
{
[Serializable]
internal sealed class Status : IReadStatus
{
public string Message { get; private set; }
public MessageType Type { get; private set; }
public bool IsDisplayed { get; set; }
public event Action Changed = default;
public void SetMessage(string value, MessageType type)
{
if (Message != value || Type != type)
{
Message = value;
Type = type;
Changed?.Invoke();
}
}
}
}
| 31 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Draws a scrollable list of items and a filter text field.
/// </summary>
[Serializable]
public sealed class TextFilter
{
private readonly float _selectionHeightPixels;
private readonly string _defaultText;
private string _currentText = "";
private string _confirmedText = "";
private int _currentIndex = 0;
private int _confirmedIndex = -1;
private List<string> _options = new List<string>();
private string[] _filteredOptions;
private GUIStyle _normalStyle;
private GUIStyle _selectedStyle;
private Vector2 _scrollPosition;
private Boolean _areOptionsUpdated = false;
public string CurrentText
{
get => _currentText;
set => _currentText = value;
}
public string ConfirmedOption =>
_confirmedIndex >= 0 && _confirmedIndex < _filteredOptions.Length
? _filteredOptions[_confirmedIndex]
: _defaultText;
/// <summary>
/// Don't call this from Unity field initializers.
/// </summary>
public TextFilter(string defaultText, float selectionHeightPixels)
{
_defaultText = defaultText;
_selectionHeightPixels = selectionHeightPixels;
}
public void SetOptions(IReadOnlyList<string> value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
_options = value.ToList();
_currentText = value.Count == 0 ? _defaultText : string.Empty;
_areOptionsUpdated = true;
}
public void Draw()
{
if (_normalStyle == null)
{ // If is not set up
SetUp();
}
EditorGUILayout.BeginVertical();
{
_currentText = EditorGUILayout.TextField(_currentText);
if (_areOptionsUpdated)
{
_filteredOptions = _options.ToArray();
_areOptionsUpdated = false;
}
if (_currentText != _confirmedText)
{
_confirmedText = _currentText;
_confirmedIndex = _currentIndex = -1;
_filteredOptions = _options.Where(option => option.Contains(_currentText)).ToArray();
}
if (_filteredOptions == null)
{
_filteredOptions = _options.ToArray();
}
_currentIndex = DrawSelection(_currentIndex, _filteredOptions, _selectionHeightPixels);
if (_currentIndex != _confirmedIndex)
{
_confirmedIndex = _currentIndex;
_confirmedText = ConfirmedOption;
_currentText = _confirmedText;
}
}
EditorGUILayout.EndVertical();
}
private int DrawSelection(int currentOption, string[] filteredOptions, float height)
{
_scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition, _normalStyle, GUILayout.Height(height));
for (int i = 0; i < filteredOptions.Length; i++)
{
if (GUILayout.Button(filteredOptions[i], currentOption == i ? _selectedStyle : _normalStyle))
{
currentOption = i;
}
}
EditorGUILayout.EndScrollView();
return currentOption;
}
private void SetUp()
{
_normalStyle = ResourceUtility.GetTextFilterNormalStyle();
_selectedStyle = ResourceUtility.GetTextFilterSelectedStyle();
}
}
}
| 127 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using CoreErrorCode = AmazonGameLiftPlugin.Core.Shared.ErrorCode;
namespace AmazonGameLift.Editor
{
internal sealed class TextProvider
{
private readonly Dictionary<string, string> _errorMessagesByCode = new Dictionary<string, string>
{
{ CoreErrorCode.AwsError, "AWS error."},
{ CoreErrorCode.BucketDoesNotExist, "The bucket does not exist."},
{ CoreErrorCode.BucketNameAlreadyExists, "The bucket already exists."},
{ CoreErrorCode.BucketNameCanNotBeEmpty, "The bucket name cannot be empty."},
{ CoreErrorCode.BucketNameIsWrong, "There was a problem with the bucket name."},
{ CoreErrorCode.ChangeSetAlreadyExists, "The changeset already exists."},
{ CoreErrorCode.ChangeSetNotFound, "The changeset was not found."},
{ CoreErrorCode.ConflictError, "There was a conflict."},
{ CoreErrorCode.FileNotFound, "The file was not found."},
{ CoreErrorCode.InsufficientCapabilities, "Insufficient capabilities."},
{ CoreErrorCode.InvalidBucketPolicy, "There was a problem with the bucket policy."},
{ CoreErrorCode.InvalidCfnTemplate, "There was a problem with the template."},
{ CoreErrorCode.InvalidChangeSetStatus, "There was a problem with the changeset status."},
{ CoreErrorCode.InvalidIdToken, "There was a problem with the ID token."},
{ CoreErrorCode.InvalidParameters, "There was a problem with the parameters."},
{ CoreErrorCode.InvalidParametersFile, "There was a problem with the parameters file."},
{ CoreErrorCode.InvalidRegion, "There was a problem with the Region."},
{ CoreErrorCode.InvalidSettingsFile, "There was a problem with the settings file."},
{ CoreErrorCode.LimitExceeded, "Limit exceeded."},
{ CoreErrorCode.NoGameSessionWasFound, "No game session was found."},
{ CoreErrorCode.NoProfileFound, "The profile was not found."},
{ CoreErrorCode.NoSettingsFileFound, "The settings file was not found."},
{ CoreErrorCode.NoSettingsKeyFound, "The settings key was not found."},
{ CoreErrorCode.ParametersFileNotFound, "The parameters file was not found."},
{ CoreErrorCode.ProfileAlreadyExists, "The profile already exists."},
{ CoreErrorCode.ResourceWithTheNameRequestetAlreadyExists, "A resource with the requested name already exists."},
{ CoreErrorCode.StackDoesNotExist, "The stack does not exist."},
{ CoreErrorCode.StackDoesNotHaveChanges, "The stack does not have changes."},
{ CoreErrorCode.TemplateFileNotFound, "Template file was not found."},
{ CoreErrorCode.TokenAlreadyExists, "The token already exists."},
{ CoreErrorCode.UnknownError, "Unknown error."},
{ CoreErrorCode.UserNotConfirmed, "The user did not confirm registration."},
{ ErrorCode.ChangeSetStatusInvalid, "There was a problem with the changeset status."},
{ ErrorCode.OperationCancelled, "The operation was cancelled."},
{ ErrorCode.OperationInvalid, "There was a problem with the operation."},
{ ErrorCode.ReadingFileFailed, "There was a problem reading the file."},
{ ErrorCode.StackStatusInvalid, "There was a problem with the stack status."},
{ ErrorCode.ValueInvalid, "There was a problem with the value."},
{ ErrorCode.WritingFileFailed, "There was a problem writing to the file."},
};
private readonly Dictionary<string, string> _textsByKey = new Dictionary<string, string>
{
{ Strings.LabelBootstrapBucketCosts, "Using S3 will incur costs to your account via Storage, Transfer, etc. See S3 Pricing Plan (https://aws.amazon.com/s3/pricing/) for details."},
{ Strings.LabelBootstrapBucketName, "Bucket Name"},
{ Strings.LabelBootstrapCreateButton, "Create"},
{ Strings.LabelBootstrapCreateMode, "Create a new S3 bucket"},
{ Strings.LabelBootstrapBucketLifecycle, "Policy"},
{ Strings.LabelBootstrapLifecycleWarning, "With lifecycle policy configured on the S3 bucket, stale build artifacts in S3 will be deleted automatically, and will cause fleet creation to fail when created with a build referencing the deleted artifacts."},
{ Strings.LabelBootstrapBucketSelectionLoading, "Loading S3 Buckets..."},
{ Strings.LabelBootstrapRegion, "AWS Region"},
{ Strings.LabelBootstrapSelectButton, "Update"},
{ Strings.LabelBootstrapSelectMode, "Choose existing S3 bucket"},
{ Strings.LabelBootstrapCurrentBucket, "Current S3 bucket"},
{ Strings.LabelBootstrapS3Console, "Go to S3 console"},
{ Strings.LabelCredentialsCreateButton, "Create Credentials Profile"},
{ Strings.LabelCredentialsCreateMode, "Create new credentials profile"},
{ Strings.LabelCredentialsUpdateButton, "Update Credentials Profile"},
{ Strings.LabelCredentialsUpdateMode, "Choose existing credentials profile"},
{ Strings.LabelCredentialsHelp, "How do I create AWS credentials?"},
{ Strings.LabelCredentialsCreateProfileName, "New Profile Name"},
{ Strings.LabelCredentialsCurrentProfileName, "Current Profile"},
{ Strings.LabelCredentialsSelectProfileName, "Profile Name"},
{ Strings.LabelCredentialsAccessKey, "AWS Access Key ID"},
{ Strings.LabelCredentialsRegion, "AWS Region"},
{ Strings.LabelCredentialsSecretKey, "AWS Secret Key"},
{ Strings.LabelDefaultFolderName, "New"},
{ Strings.LabelDeploymentApiGateway, "API Gateway Endpoint"},
{ Strings.LabelDeploymentBootstrapWarning, "You must configure your AWS credentials and a bootstrapping location before deploying a scenario.."},
{ Strings.LabelDeploymentBucket, "S3 Bucket"},
{ Strings.LabelDeploymentBuildFilePath, "Game Server Executable Path"},
{ Strings.LabelDeploymentBuildFolderPath, "Game Server Build Folder Path"},
{ Strings.LabelDeploymentCancelDialogBody, "Are you sure you want to cancel?"},
{ Strings.LabelDeploymentCancelDialogCancelButton, "No"},
{ Strings.LabelDeploymentCancelDialogOkButton, "Yes"},
{ Strings.LabelDeploymentCloudFormationConsole, "View AWS CloudFormation Console"},
{ Strings.LabelDeploymentCosts, "Deploying and running various AWS resources in the CloudFormation template will incur costs to your account. See AWS Pricing Plan (https://aws.amazon.com/pricing/) for details on the cost of each resource in the CloudFormation template."},
{ Strings.LabelDeploymentCognitoClientId, "Cognito Client ID"},
{ Strings.LabelDeploymentCustomMode, "Custom scenario"},
{ Strings.LabelDeploymentHelp, "How to deploy your first game?"},
{ Strings.LabelDeploymentGameName, "Game Name"},
{ Strings.LabelDeploymentCurrentStack, "Deployment Status"},
{ Strings.LabelDeploymentRegion, "AWS Region"},
{ Strings.LabelDeploymentScenarioHelp, "Learn more"},
{ Strings.LabelDeploymentScenarioPath, "Scenario Path"},
{ Strings.LabelDeploymentSelectionMode, "Scenario"},
{ Strings.LabelDeploymentStartButton, "Start Deployment"},
{ Strings.LabelDeploymentCancelButton, "Cancel Deployment"},
{ Strings.LabelLocalTestingJarPath, "GameLift Local .jar File Path"},
{ Strings.LabelLocalTestingWindowsServerPath, "Game Server Executable Path"},
{ Strings.LabelLocalTestingMacOsServerPath, "Game Server Executable Path"},
{ Strings.LabelLocalTestingStartButton, "Deploy & Run"},
{ Strings.LabelLocalTestingStopButton, "Stop"},
{ Strings.LabelLocalTestingPort, "GameLift Local Port"},
{ Strings.LabelLocalTestingHelp, "How to test with GameLift Local?"},
{ Strings.LabelSettingsAwsCredentialsSetUpButton, "AWS Credentials"},
{ Strings.LabelAwsCredentialsUpdateButton, "Update AWS Credentials"},
{ Strings.LabelPasswordHide, "Hide"},
{ Strings.LabelPasswordShow, "Show"},
{ Strings.LabelSettingsAllConfigured, "The GameLift Plugin is configured. You can build the sample game client and server and deploy a sample deployment scenario."},
{ Strings.LabelSettingsAwsCredentialsTitle, "AWS Credentials"},
{ Strings.LabelSettingsBootstrapTitle, "AWS Account Bootstrapping"},
{ Strings.LabelSettingsBootstrapButton, "Update Account Bootstrap"},
{ Strings.LabelSettingsBootstrapWarning, "To bootstrap your AWS account, configure your AWS credentials"},
{ Strings.LabelSettingsConfigured, "Configured"},
{ Strings.LabelSettingsNotConfigured, "Not Configured"},
{ Strings.LabelSettingsLocalTestingButton, "Download GameLift Local"},
{ Strings.LabelSettingsLocalTestingTitle, "Local Testing"},
{ Strings.LabelSettingsLocalTestingSetPathButton, "GameLift Local Path"},
{ Strings.LabelSettingsDotNetButton, "Use .NET 4.x"},
{ Strings.LabelSettingsDotNetTitle, ".NET Settings"},
{ Strings.LabelSettingsJavaButton, "Download JRE"},
{ Strings.LabelSettingsJavaTitle, "JRE"},
{ Strings.LabelSettingsSdkTab, "SDK"},
{ Strings.LabelSettingsDeployTab, "Deploy"},
{ Strings.LabelSettingsTestTab, "Test"},
{ Strings.LabelSettingsHelpTab, "Help"},
{ Strings.LabelSettingsOpenAwsHelp, "Open AWS documentation"},
{ Strings.LabelSettingsOpenForums, "Open AWS GameTech Forums"},
{ Strings.LabelSettingsOpenDeployment, "Open Deployment UI"},
{ Strings.LabelSettingsOpenLocalTest, "Open Local Test UI"},
{ Strings.LabelSettingsPingSdk, "Show SDK DLL Files"},
{ Strings.LabelSettingsReportSecurity, "Report security vulnerabilities"},
{ Strings.LabelSettingsReportBugs, "Report bugs/issues"},
{ Strings.LabelStackUpdateCancelButton, "Cancel"},
{ Strings.LabelStackUpdateCountTemplate, "Resources with action {0}: {1}"},
{ Strings.LabelStackUpdateConfirmButton, "Deploy"},
{ Strings.LabelStackUpdateConsole, "View the changeset in CloudFormation console"},
{ Strings.LabelStackUpdateConsoleWarning, "Do not \"Execute\" the changeset when previewing it in the AWS CloudFormation console."},
{ Strings.LabelStackUpdateQuestion, "Do you want to redeploy your current stack?"},
{ Strings.LabelStackUpdateRemovalHeader, "The following resources will be removed during deployment:"},
{ Strings.LifecycleNone, "No Lifecycle Policy"},
{ Strings.LifecycleSevenDays, "7 days"},
{ Strings.LifecycleThirtyDays, "30 days"},
{ Strings.StatusDeploymentExePathInvalid, "There was a problem with deployment. The build exe is not in the build folder."},
{ Strings.StatusDeploymentFailure, "There was a problem with deployment. Error: {0}."},
{ Strings.StatusDeploymentStarting, "Preparing to deploy the scenario..."},
{ Strings.StatusDeploymentSuccess, "Deployment success."},
{ Strings.StatusExceptionThrown, "An exception was thrown. See the exception details in the Console."},
{ Strings.StatusNothingDeployed, "Nothing is deployed. Click on the «Deploy» button below."},
{ Strings.StatusProfileCreated, "Profile Created. Please bootstrap the account"},
{ Strings.StatusProfileUpdated, "Credentials Updated. Please bootstrap account if necessary"},
{ Strings.StatusBootstrapComplete, "Account bootstrap S3 bucket created!"},
{ Strings.StatusBootstrapUpdateComplete, "Account bootstrapped."},
{ Strings.StatusBootstrapFailedTemplate, "{0} {1}"},
{ Strings.StatusGetProfileFailed, "There was a problem getting the current AWS profile."},
{ Strings.StatusGetRegionFailed, "There was a problem getting the current AWS Region."},
{ Strings.StatusRegionUpdateFailedWithError, "There was a problem updating the AWS Region: {0}."},
{ Strings.StatusLocalTestErrorTemplate, "There was a problem starting GameLift local: {0}"},
{ Strings.StatusLocalTestServerErrorTemplate, "There was a problem starting the game server: {0}"},
{ Strings.StatusLocalTestRunning, "The game server is running locally"},
{ Strings.TitleAwsCredentials, "AWS Credentials"},
{ Strings.TitleBootstrap, "Account Bootstrapping"},
{ Strings.TitleDeployment, "Deployment"},
{ Strings.TitleDeploymentCancelDialog, "Cancel Current Deployment?"},
{ Strings.TitleDeploymentServerFileDialog, "Select a server build executable file"},
{ Strings.TitleDeploymentServerFolderDialog, "Select a server build folder"},
{ Strings.TitleLocalTesting, "Local Testing"},
{ Strings.TitleLocalTestingServerPathDialog, "Select a server game build"},
{ Strings.TitleLocalTestingGameLiftPathDialog, "Select the GameLift Local JAR"},
{ Strings.TitleSettings, "GameLift Plugin Settings"},
{ Strings.TitleStackUpdateDialog, "Review Deployment"},
{ Strings.TooltipCredentialsAccessKey, "Enter the key ID."},
{ Strings.TooltipCredentialsCreateProfile, "Enter your AWS account name."},
{ Strings.TooltipCredentialsRegion, "Select the AWS Region to create the S3 bucket."},
{ Strings.TooltipCredentialsSecretKey, "Enter the secret key."},
{ Strings.TooltipCredentialsSelectProfile, "Select the AWS account name."},
{ Strings.TooltipDeploymentBucket, "You can change this parameter in the Plugin Settings > Update Account Bootstrap menu if needed"},
{ Strings.TooltipDeploymentRegion, "You can change this parameter in the Plugin Settings > Update AWS Credentials menu if needed"},
{ Strings.TooltipLocalTestingPort, "A free TCP port to run GameLift Local."},
{ Strings.TooltipLocalTestingServerPath, "Your server build to test."},
{ Strings.TooltipSettingsAwsCredentials, "Setup credentials used for account bootstrapping and CloudFormation deployment."},
{ Strings.TooltipSettingsBootstrap, "Create an S3 bucket to store GameLift build artifacts and lambda function source code."},
{ Strings.TooltipSettingsDotNet, "Opt in to change \"API Compatibility Level\" of the project to 4.x, which is the latest version of .NET Framework API that the current GameLift Server SDK supports."},
{ Strings.TooltipSettingsJava, "Download and install the latest Java Runtime Environment (JRE) in order to run GameLift Local.\nNOTE: If you have JDK installed, this may show as \"Not Configured\", but local testing will work as long as you have \"java\" in your PATH environment variable"},
{ Strings.TooltipSettingsLocalTesting, "Download the GameLift Local jar bundled in \"Managed GameLift Server SDK\" on AWS website, the set the GameLift Local Path to GameLiftLocal.jar in the extracted files.\nNOTE: \"Download GameLift Local\" opens your browser to download a ZIP file from AWS website to your system's Download folder."},
{ Strings.TooltipBootstrapBucketLifecycle, "Specify an expiration date of your S3 bucket."},
{ Strings.TooltipBootstrapCurrentBucket, "This is the name of the S3 bucket which is used currently."},
{ Strings.StackDetailsTemplate, "Scenario: {1}\r\nGame Name: {2}\r\nAWS Region: {0}\r\nLast Updated: {3}"},
{ Strings.StackStatusTemplate, "Deployment Status: {0}"},
{ Strings.SettingsUIDeployNextStepLabel, "The Deployment settings are configured. You can continue by building the sample game server then deploying a sample deployment scenario."},
{ Strings.SettingsUITestNextStepLabel, "The Test settings are configured. You can continue by building the sample game server, and the sample client with local testing configurations, then connect the client to the local server."},
{ Strings.SettingsUISdkNextStepLabel, "The SDK settings are configured. You can find an usage example by going to \"(Top Menu Bar) > GameLift > Import Sample Game\", and look at \"Assets\\Scripts\\Server\\GameLiftServer.cs\"."},
{ Strings.LabelOpenSdkIntegrationDoc, "Open SDK Integration Guide"},
{ Strings.LabelOpenSdkApiDoc, "Open SDK API Reference"},
};
public string GetError(string errorCode = null)
{
if (errorCode is null)
{
return "Unknown error";
}
if (_errorMessagesByCode.TryGetValue(errorCode, out string message))
{
return message;
}
return errorCode;
}
/// <exception cref="ArgumentNullException"></exception>
public string Get(string key)
{
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
if (_textsByKey.TryGetValue(key, out string text))
{
return text;
}
return key;
}
}
}
| 233 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal static class TextProviderFactory
{
private static TextProvider s_textProvider;
public static TextProvider Create()
{
if (s_textProvider == null)
{
s_textProvider = new TextProvider();
}
return s_textProvider;
}
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.Shared;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal sealed class UnityLogger : ILogger
{
private readonly TextProvider _textProvider;
public UnityLogger(TextProvider textProvider) => _textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
public void Log(string message, LogType logType)
{
switch (logType)
{
case LogType.Error:
Debug.LogError(message);
break;
case LogType.Assert:
Debug.LogAssertion(message);
break;
case LogType.Warning:
Debug.LogWarning(message);
break;
case LogType.Log:
Debug.Log(message);
break;
default:
throw new ArgumentOutOfRangeException(nameof(logType));
}
}
public void LogException(Exception ex)
{
Debug.LogException(ex);
}
public void LogResponseError(Response response, LogType logType)
{
if (response is null)
{
throw new ArgumentNullException(nameof(response));
}
Log($"{_textProvider.GetError(response.ErrorCode)} {response.ErrorMessage}", logType);
}
}
}
| 53 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal static class UnityLoggerFactory
{
private static UnityLogger s_textProvider;
public static UnityLogger Create(TextProvider textProvider)
{
if (s_textProvider == null)
{
s_textProvider = new UnityLogger(textProvider);
}
return s_textProvider;
}
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal static class Urls
{
public const string AwsCloudFormationChangeSetTemplate = "https://{0}.console.aws.amazon.com/cloudformation/home?region={0}#/stacks/changesets/changes?stackId={1}&changeSetId={2}";
public const string AwsCloudFormationConsole = "https://console.aws.amazon.com/cloudformation/";
public const string AwsGameLiftLocal = "https://gamelift-release.s3-us-west-2.amazonaws.com/GameLift_06_03_2021.zip";
public const string AwsGameTechForums = "https://forums.awsgametech.com/";
public const string AwsHelpCredentials = "https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html";
public const string AwsHelpDeployment = "https://docs.aws.amazon.com/gamelift/latest/developerguide/unity-plug-in-scenario.html";
public const string AwsHelpGameLiftLocal = "https://docs.aws.amazon.com/gamelift/latest/developerguide/integration-testing-local.html";
public const string AwsHelpGameLiftUnity = "https://docs.aws.amazon.com/gamelift/latest/developerguide/unity-plug-in.html";
public const string AwsS3Console = "https://s3.console.aws.amazon.com/s3/home";
public const string AwsS3BucketTemplate = "https://s3.console.aws.amazon.com/s3/buckets/{0}?region={1}";
public const string AwsSecurity = "https://aws.amazon.com/security/vulnerability-reporting/";
public const string GitHubAwsLabs = "https://github.com/awslabs/amazon-gamelift-plugin-unity/issues";
public const string JavaDownload = "https://www.java.com/en/download/";
public const string GameLiftServerCSharpSdkIntegrationDoc = "https://docs.aws.amazon.com/gamelift/latest/developerguide/integration-engines-unity-using.html";
public const string GameLiftServerCSharpSdkApiDoc = "https://docs.aws.amazon.com/gamelift/latest/developerguide/integration-server-sdk-csharp-ref.html";
}
}
| 25 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Text.RegularExpressions;
namespace AmazonGameLift.Editor
{
internal class BootstrapBucketFormatter : IBucketNameFormatter
{
/// <inheritdoc/>
public string FormatBucketName(string accountId, string region)
{
string key1 = FormatBucketKey(accountId);
string key2 = FormatBucketKey(region);
return $"gamelift-bootstrap-{key1}-{key2}";
}
/// <inheritdoc/>
public string FormatBucketKey(string value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
string lowercase = value.ToLowerInvariant();
return Regex.Replace(lowercase, "[^a-z0-9-]", string.Empty);
}
/// <inheritdoc/>
public bool ValidateBucketKey(string value)
{
return Regex.IsMatch(value, "^[a-z0-9][a-z0-9-]*[a-z0-9]$");
}
}
}
| 39 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.AccountManagement.Models;
using AmazonGameLiftPlugin.Core.BucketManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// A view model for <see cref="BootstrapWindow"/>.
/// </summary>
internal class BootstrapSettings
{
public const int CreationMode = 0;
public const int SelectionMode = 1;
public const int NoneLifeCyclePolicyIndex = 0;
private const int DefaultLifeCyclePolicyIndex = 0;
private readonly Status _status = new Status();
private readonly BucketUrlFormatter _bucketUrlFormatter = new BucketUrlFormatter();
private readonly BucketPolicy[] _lifecyclePolicies;
private readonly TextProvider _textProvider;
private readonly IBucketNameFormatter _bucketFormatter;
private readonly ILogger _logger;
private readonly CoreApi _coreApi;
private readonly BootstrapUtility _bootstrapUtility;
private List<string> _existingBuckets = new List<string>();
public IReadStatus Status => _status;
public IReadOnlyList<string> ExistingBuckets => _existingBuckets;
public string[] AllLifecyclePolicyNames { get; }
/// <summary>
/// Is set by <see cref="Refresh"/>, <see cref="RefreshBucketName"/> or <see cref="RefreshCurrentBucket"/>.
/// </summary>
public string CurrentRegion { get; private set; }
/// <summary>
/// Updated in <see cref="CreateBucket"/> or <see cref="SaveSelectedBucket"/>.
/// </summary>
public string CurrentBucketName { get; private set; }
public string CurrentBucketUrl { get; private set; }
public bool HasCurrentBucket { get; private set; }
/// <summary>
/// Generated from <see cref="GameName"/>.
/// </summary>
public string BucketName { get; set; }
public int LifeCyclePolicyIndex { get; set; }
public bool CanCreate => !string.IsNullOrEmpty(BucketName);
public bool IsBucketListLoaded { get; private set; }
public bool CanSaveSelectedBucket =>
_existingBuckets.Count != 0
&& CurrentRegion != null
&& !string.IsNullOrEmpty(BucketName);
public int SelectedMode { get; set; }
public event Action<IReadOnlyList<string>> OnBucketsLoaded = default;
public BootstrapSettings(IEnumerable<BucketPolicy> lifecyclePolicies,
IEnumerable<string> lifecyclePolicyNames, TextProvider textProvider,
IBucketNameFormatter bucketFormatter, ILogger logger, CoreApi coreApi = null,
BootstrapUtility bootstrapUtility = null)
{
if (lifecyclePolicies is null)
{
throw new ArgumentNullException(nameof(lifecyclePolicies));
}
if (lifecyclePolicyNames is null)
{
throw new ArgumentNullException(nameof(lifecyclePolicyNames));
}
_lifecyclePolicies = lifecyclePolicies.ToArray();
_textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
_bucketFormatter = bucketFormatter ?? throw new ArgumentNullException(nameof(bucketFormatter));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_coreApi = coreApi ?? CoreApi.SharedInstance;
_bootstrapUtility = bootstrapUtility ?? BootstrapUtility.SharedInstance;
LifeCyclePolicyIndex = DefaultLifeCyclePolicyIndex;
AllLifecyclePolicyNames = lifecyclePolicyNames.ToArray();
}
public async Task SetUp(CancellationToken cancellationToken = default)
{
await RefreshExistingBuckets(cancellationToken);
}
public void SelectBucket(string name)
{
if (BucketName == name)
{
return;
}
BucketName = name;
// Reset if we select a new valid bucket
_status.IsDisplayed &= string.IsNullOrEmpty(BucketName);
}
public void CreateBucket()
{
if (!CanCreate)
{
return;
}
GetBootstrapDataResponse bootstrapResponse = _bootstrapUtility.GetBootstrapData();
if (!bootstrapResponse.Success)
{
OnBucketCreationFailure(bootstrapResponse);
return;
}
CreateBucketResponse createResponse = _coreApi.CreateBucket(bootstrapResponse.Profile, bootstrapResponse.Region, BucketName);
if (createResponse.Success)
{
OnBucketCreated(bootstrapResponse.Profile, bootstrapResponse.Region, BucketName);
}
else
{
OnBucketCreationFailure(createResponse);
}
}
public void SaveSelectedBucket()
{
if (!CanSaveSelectedBucket)
{
_logger.Log(DevStrings.OperationInvalid, LogType.Error);
return;
}
PutSettingResponse bucketNameResponse = _coreApi.PutSetting(SettingsKeys.CurrentBucketName, BucketName);
if (!bucketNameResponse.Success)
{
SetErrorStatus(Strings.StatusBootstrapFailedTemplate, bucketNameResponse);
_logger.LogResponseError(bucketNameResponse);
return;
}
HasCurrentBucket = true;
CurrentBucketName = BucketName;
CurrentBucketUrl = _bucketUrlFormatter.Format(CurrentBucketName, CurrentRegion);
SetInfoStatus(Strings.StatusBootstrapUpdateComplete);
}
/// <summary>
/// Sets <see cref="IsBucketListLoaded"/> to <c>true</c> when complete.
/// </summary>
public async Task RefreshExistingBuckets(CancellationToken cancellationToken = default)
{
IsBucketListLoaded = false;
_status.IsDisplayed = false;
_existingBuckets.Clear();
try
{
GetSettingResponse profileResponse = _coreApi.GetSetting(SettingsKeys.CurrentProfileName);
if (!profileResponse.Success)
{
SetErrorStatus(Strings.StatusGetProfileFailed);
_logger.LogResponseError(profileResponse);
return;
}
GetSettingResponse regionResponse = _coreApi.GetSetting(SettingsKeys.CurrentRegion);
if (!regionResponse.Success || !_coreApi.IsValidRegion(regionResponse.Value))
{
SetErrorStatus(Strings.StatusGetRegionFailed);
_logger.LogResponseError(regionResponse);
return;
}
GetBucketsResponse bucketsResponse = await Task.Run(() => _coreApi.ListBuckets(profileResponse.Value, regionResponse.Value), cancellationToken);
if (!bucketsResponse.Success)
{
SetErrorStatus(Strings.StatusBootstrapFailedTemplate, bucketsResponse);
_logger.LogResponseError(bucketsResponse);
return;
}
_existingBuckets = bucketsResponse.Buckets.ToList();
}
catch (TaskCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.LogException(ex);
throw;
}
finally
{
IsBucketListLoaded = true;
OnBucketsLoaded?.Invoke(_existingBuckets);
}
}
public void Refresh()
{
RefreshBucketName();
RefreshCurrentBucket();
}
public void RefreshCurrentBucket()
{
GetSettingResponse bucketNameResponse = _coreApi.GetSetting(SettingsKeys.CurrentBucketName);
CurrentBucketName = bucketNameResponse.Success ? bucketNameResponse.Value : null;
GetSettingResponse currentRegionResponse = _coreApi.GetSetting(SettingsKeys.CurrentRegion);
bool isRegionValid = _coreApi.IsValidRegion(currentRegionResponse.Value);
CurrentRegion = currentRegionResponse.Success && isRegionValid ? currentRegionResponse.Value : null;
HasCurrentBucket = !string.IsNullOrEmpty(CurrentBucketName) && isRegionValid;
if (HasCurrentBucket)
{
CurrentBucketUrl = _bucketUrlFormatter.Format(CurrentBucketName, CurrentRegion);
return;
}
CurrentBucketName = null;
CurrentBucketUrl = null;
if (!isRegionValid)
{
CurrentRegion = null;
}
}
public void RefreshBucketName()
{
CurrentRegion = null;
BucketName = null;
GetSettingResponse currentRegionResponse = _coreApi.GetSetting(SettingsKeys.CurrentRegion);
if (!currentRegionResponse.Success || !_coreApi.IsValidRegion(currentRegionResponse.Value))
{
SetErrorStatus(Strings.StatusGetRegionFailed);
_logger.LogResponseError(currentRegionResponse);
return;
}
CurrentRegion = currentRegionResponse.Value;
GetSettingResponse profileResponse = _coreApi.GetSetting(SettingsKeys.CurrentProfileName);
if (!profileResponse.Success)
{
SetErrorStatus(Strings.StatusGetProfileFailed);
_logger.LogResponseError(profileResponse);
return;
}
RetrieveAccountIdByCredentialsResponse accountIdResponse = _coreApi.RetrieveAccountId(profileResponse.Value);
if (!accountIdResponse.Success)
{
SetErrorStatus(Strings.StatusBootstrapFailedTemplate, accountIdResponse);
_logger.LogResponseError(accountIdResponse);
return;
}
BucketName = _bucketFormatter.FormatBucketName(accountIdResponse.AccountId, CurrentRegion);
}
private void SetInfoStatus(string statusKey)
{
SetStatus(statusKey, MessageType.Info);
}
private void SetErrorStatus(string statusKey)
{
SetStatus(statusKey, MessageType.Error);
}
private void SetErrorStatus(string statusKey, Response errorResponse)
{
string errorTemplate = _textProvider.Get(statusKey);
string message = string.Format(errorTemplate, _textProvider.GetError(errorResponse.ErrorCode), errorResponse.ErrorMessage);
_status.SetMessage(message, MessageType.Error);
_status.IsDisplayed = true;
}
private void SetStatus(string statusKey, MessageType messageType)
{
_status.SetMessage(_textProvider.Get(statusKey), messageType);
_status.IsDisplayed = true;
}
private void OnBucketCreated(string profileName, string region, string bucketName)
{
PutSettingResponse bucketNameResponse = _coreApi.PutSetting(SettingsKeys.CurrentBucketName, bucketName);
if (!bucketNameResponse.Success)
{
OnBucketCreationFailure(bucketNameResponse);
return;
}
BucketPolicy policy = _lifecyclePolicies[LifeCyclePolicyIndex];
if (policy != BucketPolicy.None)
{
PutLifecycleConfigurationResponse putPolicyResponse = _coreApi.PutBucketLifecycleConfiguration(profileName, region, bucketName, policy);
if (!putPolicyResponse.Success)
{
_logger.LogResponseError(putPolicyResponse);
}
}
SetInfoStatus(Strings.StatusBootstrapComplete);
RefreshCurrentBucket();
}
private void OnBucketCreationFailure(Response response)
{
SetErrorStatus(Strings.StatusBootstrapFailedTemplate, response);
_logger.LogResponseError(response);
}
}
}
| 348 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.BucketManagement.Models;
namespace AmazonGameLift.Editor
{
internal class BootstrapSettingsFactory
{
public static BootstrapSettings Create()
{
var allBucketLifecyclePolicies = (BucketPolicy[])Enum.GetValues(typeof(BucketPolicy));
BucketLifecyclePolicyTextProvider bucketLifecyclePolicyTextProvider = BucketLifecyclePolicyTextProviderFactory.Create();
IEnumerable<string> allBucketLifecyclePolicyNames = bucketLifecyclePolicyTextProvider.GetAllLifecyclePolicies();
TextProvider textProvider = TextProviderFactory.Create();
UnityLogger logger = UnityLoggerFactory.Create(textProvider);
return new BootstrapSettings(allBucketLifecyclePolicies, allBucketLifecyclePolicyNames,
textProvider, new BootstrapBucketFormatter(), logger);
}
}
}
| 24 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class BootstrapWindow : EditorWindow
{
private const float WindowWidthPixels = 560f;
private const float WindowSelectionHeightPixels = 340f;
private const float WindowCreationHeightPixels = 300f;
private const float WarningHeightPixels = 45f;
private const float TopMarginPixels = 15f;
private const float LeftMarginPixels = 15f;
private const float RightMarginPixels = 13f;
private const float SelectionTextFieldHeight = 20f;
private const float SelectionHeightPixels = 110f;
private const float LabelWidthPixels = 150f;
private const float VerticalSpacingPixels = 5f;
private const float SpinnerSizePixels = 23f;
private HyperLinkButton _consoleHyperLinkButton;
private TextFilter _bucketsTextFilter;
private StatusLabel _statusLabel;
private BootstrapSettings _bootstrapSettings;
private int _confirmedMode = -1;
private ImageSequenceDrawer _spinnerDrawer;
private ControlDrawer _controlDrawer;
private TextProvider _textProvider;
private string[] _uiModes = new string[0];
private string _labelBootstrapCreateButton;
private string _labelBootstrapCurrentBucket;
private string _labelBootstrapSelectButton;
private string _labelBootstrapBucketName;
private string _labelBootstrapRegion;
private string _labelBootstrapBucketLifecycle;
private string _tooltipBootstrapBucketLifecycle;
private string _tooltipRegion;
private string _tooltipCurrentBucket;
private string _labelBucketCosts;
private string _labelLoading;
private string _policyWarning;
private int _cachedPolicy = -1;
private bool _needResize;
private CancellationTokenSource _refreshBucketsCancellation;
private void SetUp()
{
_textProvider = TextProviderFactory.Create();
titleContent = new GUIContent(_textProvider.Get(Strings.TitleBootstrap));
_bootstrapSettings = BootstrapSettingsFactory.Create();
_bucketsTextFilter = new TextFilter(string.Empty, SelectionHeightPixels);
_statusLabel = new StatusLabel();
_controlDrawer = ControlDrawerFactory.Create();
_spinnerDrawer = SpinnerDrawerFactory.Create(size: SpinnerSizePixels);
_consoleHyperLinkButton = new HyperLinkButton(_textProvider.Get(Strings.LabelBootstrapS3Console),
Urls.AwsS3Console, ResourceUtility.GetHyperLinkStyle());
_bootstrapSettings.OnBucketsLoaded += OnBucketsLoaded;
_bootstrapSettings.Status.Changed += OnStatusChanged;
_uiModes = new[]
{
_textProvider.Get(Strings.LabelBootstrapCreateMode),
_textProvider.Get(Strings.LabelBootstrapSelectMode),
};
_labelBootstrapCurrentBucket = _textProvider.Get(Strings.LabelBootstrapCurrentBucket);
_labelBootstrapCreateButton = _textProvider.Get(Strings.LabelBootstrapCreateButton);
_labelBootstrapSelectButton = _textProvider.Get(Strings.LabelBootstrapSelectButton);
_labelBootstrapBucketName = _textProvider.Get(Strings.LabelBootstrapBucketName);
_labelBootstrapRegion = _textProvider.Get(Strings.LabelBootstrapRegion);
_labelBootstrapBucketLifecycle = _textProvider.Get(Strings.LabelBootstrapBucketLifecycle);
_tooltipBootstrapBucketLifecycle = _textProvider.Get(Strings.TooltipBootstrapBucketLifecycle);
_tooltipRegion = _textProvider.Get(Strings.TooltipDeploymentRegion);
_tooltipCurrentBucket = _textProvider.Get(Strings.TooltipBootstrapCurrentBucket);
_labelBucketCosts = _textProvider.Get(Strings.LabelBootstrapBucketCosts);
_policyWarning = _textProvider.Get(Strings.LabelBootstrapLifecycleWarning);
_labelLoading = _textProvider.Get(Strings.LabelBootstrapBucketSelectionLoading);
_refreshBucketsCancellation = new CancellationTokenSource();
_bootstrapSettings.SetUp(_refreshBucketsCancellation.Token)
.ContinueWith(task =>
{
_confirmedMode = _bootstrapSettings.SelectedMode;
_bootstrapSettings.RefreshCurrentBucket();
UpdateWindowSize();
}, TaskContinuationOptions.ExecuteSynchronously);
}
private void OnEnable()
{
SetUp();
}
private void OnDisable()
{
_refreshBucketsCancellation?.Cancel();
_bootstrapSettings.Status.Changed -= OnStatusChanged;
_bootstrapSettings.OnBucketsLoaded -= OnBucketsLoaded;
}
private void OnGUI()
{
EditorGUIUtility.labelWidth = LabelWidthPixels;
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(LeftMarginPixels);
using (new EditorGUILayout.VerticalScope())
{
GUILayout.Space(TopMarginPixels);
DrawControls();
}
GUILayout.Space(RightMarginPixels);
}
}
private void OnInspectorUpdate()
{
if (_bootstrapSettings.IsBucketListLoaded)
{
_spinnerDrawer.Stop();
}
else
{
_spinnerDrawer.Start();
}
if (_spinnerDrawer.IsRunning)
{
Repaint();
}
}
private void DrawControls()
{
SetUpForSelectedMode();
DrawModeSelection();
if (_bootstrapSettings.SelectedMode == BootstrapSettings.CreationMode)
{
DrawBucketCreation();
}
else
{
DrawBucketSelection();
}
_controlDrawer.DrawSeparator();
DrawCurrentBucket();
GUILayout.Space(10f);
if (_bootstrapSettings.SelectedMode == BootstrapSettings.CreationMode)
{
DrawCreateButton();
}
else
{
DrawSelectButton();
}
if (_bootstrapSettings.Status.IsDisplayed)
{
DrawStatus();
}
}
private void SetUpForSelectedMode()
{
if (_bootstrapSettings.SelectedMode == _confirmedMode)
{
return;
}
_confirmedMode = _bootstrapSettings.SelectedMode;
_bootstrapSettings.RefreshCurrentBucket();
if (_bootstrapSettings.SelectedMode == BootstrapSettings.CreationMode)
{
_refreshBucketsCancellation?.Cancel();
_bootstrapSettings.RefreshBucketName();
}
else
{
_refreshBucketsCancellation = new CancellationTokenSource();
_ = _bootstrapSettings.RefreshExistingBuckets(_refreshBucketsCancellation.Token);
}
GUI.FocusControl(null);
UpdateWindowSize();
}
#region Form controls
private void DrawCurrentBucket()
{
_controlDrawer.DrawReadOnlyText(_labelBootstrapCurrentBucket, _bootstrapSettings.CurrentBucketName, _tooltipCurrentBucket);
if (!_bootstrapSettings.HasCurrentBucket)
{
GUILayout.Space(EditorGUIUtility.singleLineHeight);
return;
}
_consoleHyperLinkButton.Url = _bootstrapSettings.CurrentBucketUrl;
DrawLink(_consoleHyperLinkButton);
}
private void DrawCreateButton()
{
using (new EditorGUI.DisabledScope(!_bootstrapSettings.CanCreate))
{
if (GUILayout.Button(_labelBootstrapCreateButton))
{
_bootstrapSettings.CreateBucket();
}
}
}
private void DrawSelectButton()
{
using (new EditorGUI.DisabledScope(!_bootstrapSettings.CanSaveSelectedBucket))
{
if (GUILayout.Button(_labelBootstrapSelectButton))
{
_bootstrapSettings.SaveSelectedBucket();
}
}
}
private void DrawModeSelection()
{
_bootstrapSettings.SelectedMode = GUILayout.SelectionGrid(_bootstrapSettings.SelectedMode, _uiModes, 1, EditorStyles.radioButton);
}
private void DrawBucketCreation()
{
EditorGUILayout.HelpBox(_labelBucketCosts, MessageType.Warning);
_bootstrapSettings.BucketName = _controlDrawer.DrawTextField(_labelBootstrapBucketName, _bootstrapSettings.BucketName);
_controlDrawer.DrawReadOnlyText(_labelBootstrapRegion, _bootstrapSettings.CurrentRegion, _tooltipRegion);
GUILayout.Space(VerticalSpacingPixels);
_bootstrapSettings.LifeCyclePolicyIndex = _controlDrawer.DrawPopup(
_labelBootstrapBucketLifecycle,
_bootstrapSettings.LifeCyclePolicyIndex, _bootstrapSettings.AllLifecyclePolicyNames,
_tooltipBootstrapBucketLifecycle);
if (_cachedPolicy != _bootstrapSettings.LifeCyclePolicyIndex)
{
_cachedPolicy = _bootstrapSettings.LifeCyclePolicyIndex;
_needResize = true;
}
if (_bootstrapSettings.LifeCyclePolicyIndex != BootstrapSettings.NoneLifeCyclePolicyIndex)
{
EditorGUILayout.HelpBox(_policyWarning, MessageType.Warning);
}
GUILayout.Space(VerticalSpacingPixels);
if (_needResize)
{
UpdateWindowSize();
}
}
private void DrawBucketSelection()
{
EditorGUILayout.PrefixLabel(_labelBootstrapBucketName);
if (!_bootstrapSettings.IsBucketListLoaded)
{
using (new EditorGUILayout.HorizontalScope(GUILayout.Height(SelectionHeightPixels + SelectionTextFieldHeight)))
{
GUILayout.Label(_labelLoading);
_spinnerDrawer.Draw();
}
}
else
{
_bucketsTextFilter.Draw();
}
_bootstrapSettings.SelectBucket(_bucketsTextFilter.ConfirmedOption);
}
private void DrawStatus()
{
_statusLabel.Draw(_bootstrapSettings.Status.Message, _bootstrapSettings.Status.Type);
}
#endregion
private void DrawLink(HyperLinkButton link)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5f);
link.Draw();
}
}
private void UpdateWindowSize()
{
switch (_bootstrapSettings.SelectedMode)
{
case BootstrapSettings.CreationMode:
float heightPixels = _cachedPolicy == BootstrapSettings.NoneLifeCyclePolicyIndex
? WindowCreationHeightPixels
: WindowCreationHeightPixels + WarningHeightPixels;
SetWindowSize(heightPixels);
break;
default:
SetWindowSize(WindowSelectionHeightPixels);
break;
}
}
private void SetWindowSize(float height)
{
this.SetConstantSize(new Vector2(x: WindowWidthPixels, y: height));
}
private void OnBucketsLoaded(IReadOnlyList<string> buckets)
{
_bucketsTextFilter.SetOptions(buckets);
Repaint();
}
private void OnStatusChanged()
{
Repaint();
}
}
}
| 342 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using AmazonGameLiftPlugin.Core.BucketManagement.Models;
namespace AmazonGameLift.Editor
{
internal class BucketLifecyclePolicyTextProvider
{
private readonly TextProvider _textProvider;
private string[] _cachedTexts;
internal BucketLifecyclePolicyTextProvider(TextProvider textProvider) => _textProvider = textProvider;
public virtual IEnumerable<string> GetAllLifecyclePolicies()
{
if (_cachedTexts == null)
{
_cachedTexts = GetPolicyTexts().ToArray();
}
return _cachedTexts;
}
private IEnumerable<string> GetPolicyTexts()
{
var bucketPolicies = (BucketPolicy[])Enum.GetValues(typeof(BucketPolicy));
foreach (BucketPolicy policy in bucketPolicies)
{
switch (policy)
{
case BucketPolicy.None:
yield return _textProvider.Get(Strings.LifecycleNone);
break;
case BucketPolicy.SevenDaysLifecycle:
yield return _textProvider.Get(Strings.LifecycleSevenDays);
break;
case BucketPolicy.ThirtyDaysLifecycle:
yield return _textProvider.Get(Strings.LifecycleThirtyDays);
break;
default:
yield return policy.ToString();
break;
}
}
}
}
}
| 53 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal static class BucketLifecyclePolicyTextProviderFactory
{
private static BucketLifecyclePolicyTextProvider s_textProvider;
public static BucketLifecyclePolicyTextProvider Create()
{
if (s_textProvider == null)
{
s_textProvider = new BucketLifecyclePolicyTextProvider(TextProviderFactory.Create());
}
return s_textProvider;
}
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
namespace AmazonGameLift.Editor
{
internal sealed class BucketUrlFormatter
{
public const int MaxBucketNameLength = 63;
/// <exception cref="ArgumentNullException">For all arguments.</exception>
/// <exception cref="ArgumentException">For <paramref name="bucketName"/>, if it is longer
/// than <see cref="MaxBucketNameLength"/>.</exception>
public string Format(string bucketName, string region)
{
if (bucketName is null)
{
throw new ArgumentNullException(nameof(bucketName));
}
if (region is null)
{
throw new ArgumentNullException(nameof(region));
}
if (bucketName.Length > MaxBucketNameLength)
{
throw new ArgumentException(DevStrings.BucketNameTooLong, nameof(region));
}
return string.Format(Urls.AwsS3BucketTemplate, bucketName, region);
}
}
}
| 36 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal interface IBucketNameFormatter
{
/// <exception cref="ArgumentNullException">For all arguments.</exception>
string FormatBucketName(string accountId, string region);
/// <summary>
/// Removes all symbols except lowercase latin letters, digits and middle dashes. Can result in an empty string.
/// </summary>
string FormatBucketKey(string value);
/// <exception cref="ArgumentNullException"></exception>
bool ValidateBucketKey(string value);
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Linq;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Keeps the region UI state and saves it to settings.
/// </summary>
internal class RegionBootstrap
{
private const int DefaultIndex = -1;
private readonly CoreApi _coreApi;
private int _currentIndex = -1;
public string[] AllRegions { get; private set; } = Array.Empty<string>();
public virtual bool CanSave => IsRegionInRange();
public int RegionIndex { get; set; }
public RegionBootstrap(CoreApi coreApi)
{
_coreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
AllRegions = _coreApi.ListAvailableRegions().ToArray();
}
public virtual void Refresh()
{
GetSettingResponse getResponse = _coreApi.GetSetting(SettingsKeys.CurrentRegion);
if (!getResponse.Success)
{
RegionIndex = DefaultIndex;
return;
}
RegionIndex = Array.IndexOf(AllRegions, getResponse.Value);
if (RegionIndex < 0)
{
RegionIndex = DefaultIndex;
return;
}
_currentIndex = RegionIndex;
}
public virtual (bool success, string errorCode) Save()
{
if (!IsRegionInRange())
{
return (false, ErrorCode.ValueInvalid);
}
if (_currentIndex == RegionIndex)
{
return (false, null);
}
if (!CanSave)
{
return (false, null);
}
if (!CanSave)
{
return (false, ErrorCode.ValueInvalid);
}
string region = AllRegions[RegionIndex];
Response putResponse = _coreApi.PutSetting(SettingsKeys.CurrentRegion, region);
if (!putResponse.Success)
{
return (false, putResponse.ErrorCode);
}
_currentIndex = RegionIndex;
return (true, null);
}
private bool IsRegionInRange()
{
return RegionIndex >= 0 && RegionIndex < AllRegions.Length;
}
}
}
| 94 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// A class to draw some common form field controls, with optional tooltips.
/// </summary>
internal class ControlDrawer
{
public void DrawSeparator()
{
GUILayout.Space(10f);
EditorGUILayout.LabelField(string.Empty, GUI.skin.horizontalSlider);
}
public string DrawTextField(string label, string value, string tooltip = null)
{
using (new EditorGUILayout.HorizontalScope())
{
value = EditorGUILayout.TextField(new GUIContent(label, tooltip), value);
}
return value;
}
public string DrawPasswordField(string label, string value, string tooltip = null)
{
using (new EditorGUILayout.HorizontalScope())
{
value = EditorGUILayout.PasswordField(new GUIContent(label, tooltip), value);
}
return value;
}
public int DrawIntField(string label, int value, string tooltip = null)
{
using (new EditorGUILayout.HorizontalScope())
{
value = EditorGUILayout.IntField(new GUIContent(label, tooltip), value);
}
return value;
}
public int DrawPopup(string label, int selectedIndex, string[] displayedOptions, string tooltip = null)
{
return EditorGUILayout.Popup(new GUIContent(label, tooltip), selectedIndex, displayedOptions);
}
public string DrawFilePathField(string label, string value, string extension, string fileDialogTitle, string tooltip = null)
{
using (new EditorGUILayout.HorizontalScope())
{
value = EditorGUILayout.TextField(new GUIContent(label, tooltip), value);
if (GUILayout.Button("...", EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)))
{
value = EditorUtility.OpenFilePanel(fileDialogTitle, Application.dataPath, extension);
GUI.FocusControl(null);
}
}
return value;
}
public string DrawFolderPathField(string label, string value, string defaultName, string folderDialogTitle, string tooltip = null)
{
using (new EditorGUILayout.HorizontalScope())
{
value = EditorGUILayout.TextField(new GUIContent(label, tooltip), value);
if (GUILayout.Button("...", EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)))
{
value = EditorUtility.OpenFolderPanel(folderDialogTitle, Application.dataPath, defaultName);
GUI.FocusControl(null);
}
}
return value;
}
public void DrawReadOnlyText(string label, string value, string tooltip = null)
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel(new GUIContent(label, tooltip));
EditorGUILayout.SelectableLabel(value, GUILayout.Height(EditorGUIUtility.singleLineHeight));
}
}
/// <summary>
/// Returns total height.
/// </summary>
public float DrawReadOnlyTextWrapped(string label, string value, string tooltip = null)
{
var scope = new EditorGUILayout.HorizontalScope();
using (scope)
{
EditorGUILayout.PrefixLabel(new GUIContent(label, tooltip));
EditorGUILayout.SelectableLabel(value, EditorStyles.wordWrappedLabel);
}
return scope.rect.height;
}
}
}
| 113 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
/// <summary>
/// Provides a <see cref="ControlDrawer"/> object.
/// </summary>
internal static class ControlDrawerFactory
{
private static ControlDrawer s_controlDrawer;
public static ControlDrawer Create()
{
if (s_controlDrawer == null)
{
s_controlDrawer = new ControlDrawer();
}
return s_controlDrawer;
}
}
}
| 24 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal abstract class Dialog : EditorWindow
{
private const float TopMarginPixels = 10f;
private const float LeftMarginPixels = 10f;
private const float RightMarginPixels = 10f;
private readonly List<DialogAction> _actions = new List<DialogAction>();
private float _cachedContentsHeightPixels;
protected TextProvider TextProvider { get; private set; }
protected float WindowHeightNoContentsPixels { get; } = 38f;
protected abstract bool IsModal { get; }
protected abstract float WindowWidthPixels { get; }
protected abstract string TitleKey { get; }
protected Action DefaultAction { get; set; }
public void AddAction(DialogAction action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
_actions.Add(action);
}
protected abstract void SetUpContents();
protected abstract Rect DrawContents();
private void OnEnable()
{
_actions.Clear();
TextProvider = TextProviderFactory.Create();
titleContent = new GUIContent(TextProvider.Get(TitleKey));
SetWindowSize(WindowHeightNoContentsPixels);
SetUpContents();
ShowUtility();
}
private void OnDisable()
{
DefaultAction?.Invoke();
DefaultAction = null;
_actions.Clear();
}
private void OnGUI()
{
if (IsModal && focusedWindow != this)
{
FocusWindowIfItsOpen(GetType());
}
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(LeftMarginPixels);
using (new EditorGUILayout.VerticalScope())
{
GUILayout.Space(TopMarginPixels);
DrawControls();
}
GUILayout.Space(RightMarginPixels);
}
}
private void DrawControls()
{
Rect contentsRect = DrawContents();
using (new EditorGUILayout.HorizontalScope())
{
foreach (DialogAction item in _actions)
{
if (GUILayout.Button(TextProvider.Get(item.LabelKey)))
{
item.Action();
Close();
break;
}
}
}
if (Event.current.type == EventType.Repaint && _cachedContentsHeightPixels != contentsRect.height)
{
_cachedContentsHeightPixels = contentsRect.height;
SetWindowSize(WindowHeightNoContentsPixels + _cachedContentsHeightPixels);
}
}
private void SetWindowSize(float height)
{
this.SetConstantSize(new Vector2(x: WindowWidthPixels, y: height));
}
}
}
| 114 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
namespace AmazonGameLift.Editor
{
internal sealed class DialogAction
{
public string LabelKey { get; }
public Action Action { get; }
public DialogAction(string labelKey, Action action)
{
LabelKey = labelKey ?? throw new ArgumentNullException(nameof(labelKey));
Action = action ?? throw new ArgumentNullException(nameof(action));
}
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal sealed class GuiLayoutImageSequenceDrawer : ImageSequenceDrawer
{
private readonly float _height;
private readonly float _width;
public GuiLayoutImageSequenceDrawer(float height, float width,
IReadOnlyList<Texture2D> sequence, float framesPerSecond, Func<double> getTime)
: base(sequence, framesPerSecond, getTime)
{
_height = height;
_width = width;
}
protected override void Draw(Texture2D texture)
{
GUILayout.Label(texture, GUILayout.Height(_height), GUILayout.Width(_width));
}
}
}
| 29 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Draws an image. When running, switches the textures periodically to create animation.
/// The client EditorWindow needs to have this code:
/// private void OnInspectorUpdate()
/// {
/// if (_imageSequenceDrawer.IsRunning)
/// {
/// Repaint();
/// }
/// }
/// </summary>
internal abstract class ImageSequenceDrawer
{
private readonly IReadOnlyList<Texture2D> _sequence;
private readonly Func<double> _getTime;
private readonly double _delay;
private int _currentIndex;
private double _previousDrawTime;
public bool IsRunning { get; private set; }
public ImageSequenceDrawer(IReadOnlyList<Texture2D> sequence, float framesPerSecond, Func<double> getTime)
{
_sequence = sequence ?? throw new ArgumentNullException(nameof(sequence));
_getTime = getTime ?? throw new ArgumentNullException(nameof(getTime));
_delay = framesPerSecond > 0 ? 1f / framesPerSecond : float.MaxValue;
}
public void Start()
{
IsRunning = true;
}
public void Stop()
{
IsRunning = false;
}
public void Draw()
{
Draw(_sequence[_currentIndex]);
if (!IsRunning)
{
return;
}
double time = _getTime();
if (time - _previousDrawTime < _delay)
{
return;
}
_previousDrawTime = time;
_currentIndex = (_currentIndex + 1) % _sequence.Count;
}
protected abstract void Draw(Texture2D texture);
}
}
| 71 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Provides an <see cref="ImageSequenceDrawer"/> to draw a spinner UI animation.
/// </summary>
internal static class SpinnerDrawerFactory
{
private static IReadOnlyList<Texture2D> s_sequence;
public static ImageSequenceDrawer Create(float size)
{
if (s_sequence == null)
{
var imageLoader = new ImageLoader();
s_sequence = imageLoader.LoadImageSequence(AssetNames.SpinnerIcon, first: 1, last: 4);
}
return new GuiLayoutImageSequenceDrawer(size, size, s_sequence, framesPerSecond: 10f, () => EditorApplication.timeSinceStartup);
}
}
}
| 29 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Displays a message about a result of some operation like deployment, bootstrapping etc.
/// </summary>
internal sealed class StatusLabel
{
public void Draw(string message, MessageType messageType)
{
IReadOnlyDictionary<MessageType, GUIStyle> styles = ResourceUtility.GetMessageStyles();
using (new GUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
GUILayout.Label(message, styles[messageType]);
GUILayout.FlexibleSpace();
}
}
}
}
| 29 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Runtime.CompilerServices;
[assembly: System.Reflection.AssemblyCompany("Amazon Web Services")]
[assembly: System.Reflection.AssemblyTitle("GameLift Plugin Editor")]
[assembly: System.Reflection.AssemblyCopyright("Copyright 2021.")]
[assembly: InternalsVisibleTo("AmazonGameLiftPlugin.Editor.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
| 11 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
public class BootstrapUtility
{
private readonly CoreApi _coreApi;
public static BootstrapUtility SharedInstance { get; } = new BootstrapUtility();
internal BootstrapUtility(CoreApi coreApi = null) => _coreApi = coreApi ?? CoreApi.SharedInstance;
public virtual GetBootstrapDataResponse GetBootstrapData()
{
GetSettingResponse currentRegionResponse = _coreApi.GetSetting(SettingsKeys.CurrentRegion);
if (!currentRegionResponse.Success)
{
return GetFailResponse(currentRegionResponse);
}
GetSettingResponse currentProfileResponse = _coreApi.GetSetting(SettingsKeys.CurrentProfileName);
if (!currentProfileResponse.Success)
{
return GetFailResponse(currentProfileResponse);
}
string profileName = currentProfileResponse.Value;
string region = currentRegionResponse.Value;
return Response.Ok(new GetBootstrapDataResponse(profileName, region));
}
internal static GetBootstrapDataResponse GetFailResponse(Response internalErrorResponse = null)
{
var response = new GetBootstrapDataResponse()
{
ErrorCode = internalErrorResponse?.ErrorCode,
ErrorMessage = internalErrorResponse?.ErrorMessage
};
return Response.Fail(response);
}
}
}
| 49 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
public static class ChangeSetExecutionStatus
{
public const string Unavailable = "UNAVAILABLE";
public const string Available = "AVAILABLE";
public const string ExecuteInProgress = "EXECUTE_IN_PROGRESS";
public const string ExecuteComplete = "EXECUTE_COMPLETE";
public const string ExecuteFailed = "EXECUTE_FAILED";
public const string Obsolete = "OBSOLETE";
}
}
| 16 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
namespace AmazonGameLift.Editor
{
public delegate Task<bool> ConfirmChangesDelegate(ConfirmChangesRequest changes);
}
| 10 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.AccountManagement;
using AmazonGameLiftPlugin.Core.AccountManagement.Models;
using AmazonGameLiftPlugin.Core.BucketManagement;
using AmazonGameLiftPlugin.Core.BucketManagement.Models;
using AmazonGameLiftPlugin.Core.CredentialManagement;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.DeploymentManagement;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.GameLiftLocalTesting;
using AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models;
using AmazonGameLiftPlugin.Core.JavaCheck;
using AmazonGameLiftPlugin.Core.JavaCheck.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.FileSystem;
using AmazonGameLiftPlugin.Core.Shared.FileZip;
using AmazonGameLiftPlugin.Core.Shared.ProcessManagement;
using AmazonGameLiftPlugin.Core.Shared.S3Bucket;
namespace AmazonGameLift.Editor
{
public class CoreApi
{
private const int MinJavaMajorVersion = 8;
private static readonly ProcessWrapper s_process = new ProcessWrapper();
public static CoreApi SharedInstance { get; } = new CoreApi();
internal CoreApi()
{
_settingsStore = new SettingsStore(_fileWrapper, settingsFilePath: Paths.PluginSettingsFile);
Bootstrapper.Initialize();
}
#region File system
private readonly IFileWrapper _fileWrapper = new FileWrapper();
public virtual bool FolderExists(string path)
{
return _fileWrapper.DirectoryExists(path);
}
public virtual string GetUniqueTempFilePath()
{
return _fileWrapper.GetUniqueTempFilePath();
}
public virtual bool FileExists(string path)
{
return _fileWrapper.FileExists(path);
}
public virtual void FileDelete(string path)
{
_fileWrapper.Delete(path);
}
public virtual FileReadAllTextResponse FileReadAllText(string path)
{
try
{
string text = _fileWrapper.ReadAllText(path);
return Response.Ok(new FileReadAllTextResponse(text));
}
catch (Exception ex)
{
var response = new FileReadAllTextResponse()
{
ErrorCode = ErrorCode.ReadingFileFailed,
ErrorMessage = ex.Message
};
return Response.Fail(response);
}
}
public virtual Response FileWriteAllText(string path, string text)
{
try
{
_fileWrapper.WriteAllText(path, text);
return Response.Ok(new Response());
}
catch (Exception ex)
{
var response = new Response()
{
ErrorCode = ErrorCode.ReadingFileFailed,
ErrorMessage = ex.Message
};
return Response.Fail(response);
}
}
#endregion
#region Compression
private readonly IFileZip _fileZip = new FileZip();
public virtual void Zip(string sourceFolderPath, string targetFilePath)
{
_fileZip.Zip(sourceFolderPath, targetFilePath);
}
#endregion
#region Credentials
private readonly ICredentialsStore _credentialsStore = new CredentialsStore(new FileWrapper());
public virtual GetProfilesResponse ListCredentialsProfiles()
{
var request = new GetProfilesRequest();
return _credentialsStore.GetProfiles(request);
}
public virtual RetriveAwsCredentialsResponse RetrieveAwsCredentials(string profileName)
{
var request = new RetriveAwsCredentialsRequest() { ProfileName = profileName };
return _credentialsStore.RetriveAwsCredentials(request);
}
public virtual SaveAwsCredentialsResponse SaveAwsCredentials(string profileName, string accessKey, string secretKey)
{
var request = new SaveAwsCredentialsRequest()
{
ProfileName = profileName,
AccessKey = accessKey,
SecretKey = secretKey
};
return _credentialsStore.SaveAwsCredentials(request);
}
public virtual UpdateAwsCredentialsResponse UpdateAwsCredentials(string profileName, string accessKey, string secretKey)
{
var request = new UpdateAwsCredentialsRequest()
{
ProfileName = profileName,
AccessKey = accessKey,
SecretKey = secretKey
};
return _credentialsStore.UpdateAwsCredentials(request);
}
#endregion
#region Settings
private readonly ISettingsStore _settingsStore;
public virtual GetSettingResponse GetSetting(string key)
{
var request = new GetSettingRequest() { Key = key };
return _settingsStore.GetSetting(request);
}
public virtual PutSettingResponse PutSetting(string key, string value)
{
var request = new PutSettingRequest()
{
Key = key,
Value = value
};
return _settingsStore.PutSetting(request);
}
public virtual ClearSettingResponse ClearSetting(string key)
{
var request = new ClearSettingRequest() { Key = key };
return _settingsStore.ClearSetting(request);
}
public virtual Response PutSettingOrClear(string key, string value)
{
if (string.IsNullOrEmpty(value))
{
return _settingsStore.ClearSetting(new ClearSettingRequest() { Key = key });
}
return _settingsStore.PutSetting(new PutSettingRequest()
{
Key = key,
Value = value
});
}
#endregion
#region S3
public virtual IEnumerable<string> ListAvailableRegions()
{
return AwsRegionMapper.AvailableRegions();
}
public virtual bool IsValidRegion(string region)
{
return AwsRegionMapper.IsValidRegion(region);
}
public virtual RetrieveAccountIdByCredentialsResponse RetrieveAccountId(string profileName)
{
RetriveAwsCredentialsResponse credentialsResponse = RetrieveAwsCredentials(profileName);
var request = new RetrieveAccountIdByCredentialsRequest()
{
AccessKey = credentialsResponse.AccessKey,
SecretKey = credentialsResponse.SecretKey
};
var accountManager = new AccountManager(new AmazonSecurityTokenServiceClientWrapper());
return accountManager.RetrieveAccountIdByCredentials(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual GetBucketsResponse ListBuckets(string profileName, string region)
{
var bucketStore = new BucketStore(CreateS3Wrapper(profileName, region));
var request = new GetBucketsRequest()
{
Region = region
};
return bucketStore.GetBuckets(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual CreateBucketResponse CreateBucket(string profileName, string region, string bucketName)
{
var bucketStore = new BucketStore(CreateS3Wrapper(profileName, region));
var request = new CreateBucketRequest()
{
BucketName = bucketName,
Region = region
};
return bucketStore.CreateBucket(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual PutLifecycleConfigurationResponse PutBucketLifecycleConfiguration(
string profileName, string region, string bucketName, BucketPolicy expirationPolicy)
{
var bucketStore = new BucketStore(CreateS3Wrapper(profileName, region));
var request = new PutLifecycleConfigurationRequest()
{
BucketName = bucketName,
BucketPolicy = expirationPolicy
};
return bucketStore.PutLifecycleConfiguration(request);
}
internal virtual IAmazonS3Wrapper CreateS3Wrapper(string profileName, string region)
{
RetriveAwsCredentialsResponse response = RetrieveAwsCredentials(profileName);
if (!response.Success)
{
return CreateDefaultS3Wrapper();
}
string accessKey = response.AccessKey;
string secretKey = response.SecretKey;
return new AmazonS3Wrapper(accessKey, secretKey, region);
}
private static IAmazonS3Wrapper CreateDefaultS3Wrapper()
{
return new AmazonS3Wrapper(string.Empty, string.Empty, string.Empty);
}
#endregion
#region Deployment
private static readonly DeploymentFormatter s_deploymentFormatter = new DeploymentFormatter();
public virtual string GetBuildS3Key()
{
return s_deploymentFormatter.GetBuildS3Key();
}
public virtual string GetStackName(string gameName)
{
return s_deploymentFormatter.GetStackName(gameName);
}
public virtual string GetServerGamePath(string gameFilePathInBuild)
{
return s_deploymentFormatter.GetServerGamePath(gameFilePathInBuild);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual ValidateCfnTemplateResponse ValidateCfnTemplate(string profileName, string region, string templateFilePath)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new ValidateCfnTemplateRequest()
{
TemplateFilePath = templateFilePath
};
return deploymentManager.ValidateCfnTemplate(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual StackExistsResponse StackExists(string profileName, string region, string stackName)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new StackExistsRequest()
{
StackName = stackName
};
return deploymentManager.StackExists(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual CreateChangeSetResponse CreateChangeSet(string profileName, string region,
string bucketName, string stackName, string templateFilePath, string parametersFilePath,
string gameName, string lambdaFolderPath, string buildS3Key = null)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new CreateChangeSetRequest()
{
StackName = stackName,
TemplateFilePath = templateFilePath,
ParametersFilePath = parametersFilePath,
BootstrapBucketName = bucketName,
GameName = gameName,
LambdaSourcePath = lambdaFolderPath,
BuildS3Key = buildS3Key,
};
return deploymentManager.CreateChangeSet(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual DescribeChangeSetResponse DescribeChangeSet(string profileName, string region,
string stackName, string changeSetName)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new DescribeChangeSetRequest()
{
StackName = stackName,
ChangeSetName = changeSetName,
};
return deploymentManager.DescribeChangeSet(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual ExecuteChangeSetResponse ExecuteChangeSet(string profileName, string region, string stackName, string changeSetName)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new ExecuteChangeSetRequest
{
StackName = stackName,
ChangeSetName = changeSetName
};
return deploymentManager.ExecuteChangeSet(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual DeleteChangeSetResponse DeleteChangeSet(string profileName, string region,
string stackName, string changeSetName)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new DeleteChangeSetRequest()
{
StackName = stackName,
ChangeSetName = changeSetName,
};
return deploymentManager.DeleteChangeSet(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual DescribeStackResponse DescribeStack(string profileName, string region, string stackName)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new DescribeStackRequest
{
StackName = stackName,
OutputKeys = new List<string>
{
StackOutputKeys.ApiGatewayEndpoint,
StackOutputKeys.UserPoolClientId,
}
};
return deploymentManager.DescribeStack(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual DeleteStackResponse DeleteStack(string profileName, string region, string stackName)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new DeleteStackRequest
{
StackName = stackName
};
return deploymentManager.DeleteStack(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>.
/// </summary>
public virtual UploadServerBuildResponse UploadServerBuild(string profileName, string region,
string bucketName, string bucketKey, string filePath)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new UploadServerBuildRequest()
{
BucketName = bucketName,
BuildS3Key = bucketKey,
FilePath = filePath,
};
return deploymentManager.UploadServerBuild(request);
}
/// <summary>
/// Needs AWS credentials set up for <paramref name="profileName"/>. <paramref name="clientRequestToken"/> can be null.
/// </summary>
public virtual CancelDeploymentResponse CancelDeployment(string profileName, string region,
string stackName, string clientRequestToken)
{
IDeploymentManager deploymentManager = CreateDeploymentManager(profileName, region);
var request = new CancelDeploymentRequest()
{
StackName = stackName,
ClientRequestToken = clientRequestToken,
};
return deploymentManager.CancelDeployment(request);
}
internal virtual IDeploymentManager CreateDeploymentManager(string profileName, string region)
{
RetriveAwsCredentialsResponse response = RetrieveAwsCredentials(profileName);
string accessKey = response.Success ? response.AccessKey : string.Empty;
string secretKey = response.Success ? response.SecretKey : string.Empty;
var amazonS3Wrapper = new AmazonS3Wrapper(accessKey, secretKey, region);
IAmazonCloudFormationWrapper cloudFormationWrapper = new AmazonCloudFormationWrapper(accessKey, secretKey, region);
return new DeploymentManager(cloudFormationWrapper, amazonS3Wrapper, _fileWrapper, new FileZip());
}
#endregion
#region JRE
private readonly InstalledJavaVersionProvider _installedJavaVersionProvider =
new InstalledJavaVersionProvider(s_process);
public virtual bool CheckInstalledJavaVersion()
{
var request = new CheckInstalledJavaVersionRequest()
{
ExpectedMinimumJavaMajorVersion = MinJavaMajorVersion
};
CheckInstalledJavaVersionResponse response = _installedJavaVersionProvider.CheckInstalledJavaVersion(request);
return response.IsInstalled;
}
#endregion
#region Local Testing
private readonly GameLiftProcess _gameLiftProcess = new GameLiftProcess(s_process);
public virtual StartResponse StartGameLiftLocal(string gameLiftLocalFilePath, int port,
LocalOperatingSystem localOperatingSystem = LocalOperatingSystem.WINDOWS)
{
var request = new StartRequest()
{
GameLiftLocalFilePath = gameLiftLocalFilePath,
Port = port,
LocalOperatingSystem = localOperatingSystem
};
return _gameLiftProcess.Start(request);
}
public virtual StopResponse StopProcess(int processId,
LocalOperatingSystem localOperatingSystem = LocalOperatingSystem.WINDOWS)
{
var request = new StopRequest()
{
ProcessId = processId,
LocalOperatingSystem = localOperatingSystem
};
return _gameLiftProcess.Stop(request);
}
public virtual RunLocalServerResponse RunLocalServer(string exeFilePath, string applicationProductName,
LocalOperatingSystem localOperatingSystem = LocalOperatingSystem.WINDOWS)
{
var request = new RunLocalServerRequest()
{
FilePath = exeFilePath,
ShowWindow = true,
ApplicationProductName = applicationProductName,
LocalOperatingSystem = localOperatingSystem
};
return _gameLiftProcess.RunLocalServer(request);
}
#endregion
}
}
| 527 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading;
using System.Threading.Tasks;
namespace AmazonGameLift.Editor
{
public class Delay
{
public virtual Task Wait(int delayMs, CancellationToken cancellationToken = default)
{
return Task.Delay(delayMs, cancellationToken);
}
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
/// <summary>
/// A base type for the scenario scripts.
/// </summary>
public abstract class DeployerBase
{
private const int ChangeSetPollPeriodMs = 1000;
private readonly Delay _delay;
public abstract string DisplayName { get; }
public abstract string Description { get; }
public abstract string HelpUrl { get; }
public abstract string ScenarioFolder { get; }
public abstract bool HasGameServer { get; }
public virtual int PreferredUiOrder { get; }
internal DeploymentRequestFactory RequestFactory { get; set; }
protected CoreApi GameLiftCoreApi { get; }
protected DeployerBase(Delay delay, CoreApi coreApi)
{
_delay = delay ?? throw new ArgumentNullException(nameof(delay));
GameLiftCoreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
RequestFactory = new DeploymentRequestFactory(coreApi);
}
protected DeployerBase()
{
_delay = new Delay();
GameLiftCoreApi = CoreApi.SharedInstance;
RequestFactory = new DeploymentRequestFactory(GameLiftCoreApi);
}
/// <exception cref="ArgumentNullException">For all parameters.</exception>
public virtual async Task<DeploymentResponse> StartDeployment(string scenarioFolderPath, string buildFolderPath,
string gameName, bool isDevelopmentBuild, ConfirmChangesDelegate confirmChanges)
{
if (confirmChanges is null)
{
throw new ArgumentNullException(nameof(confirmChanges));
}
(DeploymentRequest request, bool success, Response failedResponse) = RequestFactory
.CreateRequest(scenarioFolderPath, gameName, isDevelopmentBuild);
if (!success)
{
return Response.Fail(new DeploymentResponse(failedResponse));
}
ValidateCfnTemplateResponse validateResponse = GameLiftCoreApi.ValidateCfnTemplate(
request.Profile, request.Region, request.CfnTemplatePath);
if (!validateResponse.Success)
{
return Response.Fail(new DeploymentResponse(validateResponse));
}
if (HasGameServer)
{
request = RequestFactory.WithServerBuild(request, buildFolderPath);
}
(DeploymentResponse createResponse, DescribeChangeSetResponse describeResponse) = await CreateChangeSet(request);
if (!createResponse.Success)
{
return createResponse;
}
(bool checkSuccess, bool checkConfirmed, Response checkFailedResponse) = await
CheckChangeConfirmation(request, describeResponse, confirmChanges);
if (!checkSuccess)
{
return Response.Fail(new DeploymentResponse(checkFailedResponse));
}
if (!checkConfirmed)
{
GameLiftCoreApi.DeleteChangeSet(request.Profile, request.Region, request.StackName, request.ChangeSetName);
return Response.Fail(new DeploymentResponse(ErrorCode.OperationCancelled));
}
DeploymentResponse deploymentResponse = await Task.Run(() => Deploy(request));
if (!deploymentResponse.Success)
{
return Response.Fail(deploymentResponse);
}
return Response.Ok(new DeploymentResponse(new DeploymentId(request, DisplayName)));
}
internal virtual async Task<(bool success, bool confirmed, Response failedResponse)> CheckChangeConfirmation(
DeploymentRequest request, DescribeChangeSetResponse changeSetResponse, ConfirmChangesDelegate confirmChanges)
{
DescribeStackResponse existsResponse = GameLiftCoreApi.DescribeStack(request.Profile, request.Region, request.StackName);
if (!existsResponse.Success)
{
return (false, false, existsResponse);
}
if (existsResponse.StackStatus == StackStatus.ReviewInProgress)
{
return (true, true, null);
}
var confirmRequest = new ConfirmChangesRequest
{
Region = request.Region,
StackId = changeSetResponse.StackId,
ChangeSetId = changeSetResponse.ChangeSetId,
Changes = changeSetResponse.Changes,
};
bool confirmed = await confirmChanges.Invoke(confirmRequest);
return (true, confirmed, null);
}
internal virtual async Task<(DeploymentResponse, DescribeChangeSetResponse)> CreateChangeSet(DeploymentRequest request)
{
CreateChangeSetResponse createResponse = GameLiftCoreApi.CreateChangeSet(
request.Profile, request.Region, request.BucketName, request.StackName,
request.CfnTemplatePath, request.ParametersPath, request.GameName, request.LambdaFolderPath, request.BuildS3Key);
if (!createResponse.Success)
{
return (Response.Fail(new DeploymentResponse(createResponse)), null);
}
var poller = new UntilResponseFailurePoller(_delay);
DescribeChangeSetResponse describeResponse = await poller.Poll(ChangeSetPollPeriodMs,
() => GameLiftCoreApi.DescribeChangeSet(request.Profile, request.Region, request.StackName, createResponse.CreatedChangeSetName),
stopCondition: target => target.ExecutionStatus != ChangeSetExecutionStatus.Unavailable);
if (!describeResponse.Success)
{
return (Response.Fail(new DeploymentResponse(describeResponse)), null);
}
if (describeResponse.ExecutionStatus != ChangeSetExecutionStatus.Available)
{
return (Response.Fail(new DeploymentResponse(ErrorCode.ChangeSetStatusInvalid)), null);
}
request.ChangeSetName = createResponse.CreatedChangeSetName;
return (Response.Ok(new DeploymentResponse()), describeResponse);
}
protected abstract Task<DeploymentResponse> Deploy(DeploymentRequest request);
}
}
| 172 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
namespace AmazonGameLift.Editor
{
public readonly struct DeploymentInfo
{
public string Region { get; }
public string GameName { get; }
public string ScenarioDisplayName { get; }
public DateTime LastUpdatedTime { get; }
public string StackStatus { get; }
public Dictionary<string, string> Outputs { get; }
public DeploymentInfo(DeploymentId deploymentId, DescribeStackResponse describeResponse, string scenarioDisplayName)
{
if (describeResponse is null)
{
throw new ArgumentNullException(nameof(describeResponse));
}
ScenarioDisplayName = scenarioDisplayName;
Region = deploymentId.Region;
GameName = describeResponse.GameName;
LastUpdatedTime = describeResponse.LastUpdatedTime;
StackStatus = describeResponse.StackStatus;
Outputs = describeResponse.Outputs;
}
public DeploymentInfo(string region, string gameName, string scenarioDisplayName,
DateTime lastUpdatedTime, string stackStatus, Dictionary<string, string> outputs)
{
ScenarioDisplayName = scenarioDisplayName;
Region = region;
GameName = gameName;
LastUpdatedTime = lastUpdatedTime;
StackStatus = stackStatus;
Outputs = outputs;
}
}
}
| 47 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.IO;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
internal class DeploymentRequestFactory
{
private CoreApi GameLiftCoreApi { get; }
internal DeploymentRequestFactory(CoreApi coreApi) =>
GameLiftCoreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
/// <exception cref="ArgumentNullException">For all parameters.</exception>
internal virtual (DeploymentRequest request, bool success, Response failedResponse) CreateRequest(
string scenarioFolderPath, string gameName, bool isDevelopmentBuild)
{
if (scenarioFolderPath is null)
{
throw new ArgumentNullException(nameof(scenarioFolderPath));
}
if (gameName is null)
{
throw new ArgumentNullException(nameof(gameName));
}
string stackName = GameLiftCoreApi.GetStackName(gameName);
string cfnTemplatePath = Path.Combine(scenarioFolderPath, Paths.CfnTemplateFileName);
string parametersPath = Path.Combine(scenarioFolderPath, Paths.ParametersFileName);
string lambdaFolderPath = Path.Combine(scenarioFolderPath, Paths.LambdaFolderPathInScenario);
GetSettingResponse currentProfileResponse = GameLiftCoreApi.GetSetting(SettingsKeys.CurrentProfileName);
if (!currentProfileResponse.Success)
{
return (null, false, currentProfileResponse);
}
GetSettingResponse currentRegionResponse = GameLiftCoreApi.GetSetting(SettingsKeys.CurrentRegion);
if (!currentRegionResponse.Success)
{
return (null, false, currentRegionResponse);
}
GetSettingResponse bucketResponse = GameLiftCoreApi.GetSetting(SettingsKeys.CurrentBucketName);
if (!bucketResponse.Success)
{
return (null, false, bucketResponse);
}
var request = new DeploymentRequest()
{
Profile = currentProfileResponse.Value,
Region = currentRegionResponse.Value,
BucketName = bucketResponse.Value,
StackName = stackName,
CfnTemplatePath = cfnTemplatePath,
ParametersPath = parametersPath,
IsDevelopmentBuild = isDevelopmentBuild,
GameName = gameName,
LambdaFolderPath = lambdaFolderPath,
};
return (request, true, null);
}
/// <exception cref="ArgumentNullException"></exception>
internal virtual DeploymentRequest WithServerBuild(DeploymentRequest request, string buildFolderPath)
{
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (buildFolderPath is null)
{
throw new ArgumentNullException(nameof(buildFolderPath));
}
request.BuildFolderPath = buildFolderPath;
request.BuildS3Key = GameLiftCoreApi.GetBuildS3Key();
return request;
}
}
}
| 92 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Waits until a stack change is applied and allows to cancel.
/// </summary>
public class DeploymentWaiter
{
private const int StackPollPeriodMs = 5000;
private readonly Delay _delay;
private DeploymentId _currentRequest;
private string _currentToken;
private bool _isCreating;
private bool _isWaiting;
public virtual bool CanCancel { get; private set; }
protected CoreApi GameLiftCoreApi { get; }
public virtual event Action<DeploymentInfo> InfoUpdated;
public DeploymentWaiter()
{
_delay = new Delay();
GameLiftCoreApi = CoreApi.SharedInstance;
}
internal DeploymentWaiter(Delay delay, CoreApi coreApi)
{
_delay = delay ?? throw new ArgumentNullException(nameof(delay));
GameLiftCoreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
}
public virtual Response CancelDeployment()
{
if (!CanCancel)
{
return Response.Fail(new Response() { ErrorCode = ErrorCode.OperationInvalid });
}
Response response;
if (_isCreating)
{
response = GameLiftCoreApi.DeleteStack(_currentRequest.Profile,
_currentRequest.Region, _currentRequest.StackName);
}
else
{
response = GameLiftCoreApi.CancelDeployment(_currentRequest.Profile,
_currentRequest.Region, _currentRequest.StackName, _currentToken);
}
if (response.Success)
{
CanCancel = false;
}
return response;
}
public virtual async Task<DeploymentResponse> WaitUntilDone(DeploymentId deploymentId)
{
if (_isWaiting)
{
return Response.Fail(new DeploymentResponse(ErrorCode.OperationInvalid));
}
_isWaiting = true;
_currentRequest = deploymentId;
try
{
return await PollStatusUntilDone(deploymentId);
}
finally
{
CleanUpCurrentDeployment();
}
}
public virtual Response CancelWaiting()
{
if (!_isWaiting)
{
return Response.Fail(new Response { ErrorCode = ErrorCode.OperationInvalid });
}
CleanUpCurrentDeployment();
return Response.Ok(new Response());
}
private async Task<DeploymentResponse> PollStatusUntilDone(DeploymentId deploymentId)
{
var poller = new UntilResponseFailurePoller(_delay);
DescribeStackResponse describeStackResponse = await poller.Poll(StackPollPeriodMs,
() =>
{
DescribeStackResponse response = GameLiftCoreApi.DescribeStack(deploymentId.Profile, deploymentId.Region, deploymentId.StackName);
if (!response.Success)
{
return response;
}
if (_currentToken == null
&& (response.StackStatus == StackStatus.UpdateInProgress || response.StackStatus == StackStatus.CreateInProgress))
{
CanCancel = true;
_currentToken = Guid.NewGuid().ToString();
_isCreating = response.StackStatus == StackStatus.CreateInProgress;
}
InfoUpdated?.Invoke(new DeploymentInfo(deploymentId, response, deploymentId.ScenarioName));
return response;
},
stopCondition: target => !_isWaiting || target.StackStatus.IsStackStatusOperationDone());
if (!describeStackResponse.Success)
{
return Response.Fail(new DeploymentResponse(describeStackResponse));
}
if (!_isWaiting)
{
return Response.Fail(new DeploymentResponse(ErrorCode.OperationCancelled));
}
if (describeStackResponse.StackStatus != StackStatus.CreateComplete
&& describeStackResponse.StackStatus != StackStatus.UpdateComplete
&& describeStackResponse.StackStatus != StackStatus.UpdateCompleteCleanUpInProgress)
{
return Response.Fail(new DeploymentResponse(ErrorCode.StackStatusInvalid, $"The '{deploymentId.StackName}' stack status is {describeStackResponse.StackStatus}"));
}
return Response.Ok(new DeploymentResponse(_currentRequest));
}
private void CleanUpCurrentDeployment()
{
_isWaiting = false;
_currentToken = null;
CanCancel = false;
_isCreating = false;
_currentRequest = default;
}
}
}
| 157 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
public static class ErrorCode
{
public static readonly string OperationCancelled = "OperationCancelled";
public static readonly string OperationInvalid = "OperationInvalid";
public static readonly string ReadingFileFailed = "ReadingFailed";
public static readonly string WritingFileFailed = "WritingFileFailed";
public static readonly string ChangeSetStatusInvalid = "ChangeSetStatusInvalid";
public static readonly string StackStatusInvalid = "StackStatusInvalid";
public static readonly string ValueInvalid = "ValueInvalid";
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
public interface IResponsePoller
{
/// <exception cref="ArgumentNullException">For <paramref name="action"/>.</exception>
Task<T> Poll<T>(int periodMs, Func<T> action, Predicate<T> stopCondition = null) where T : Response;
}
}
| 16 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
public static class Paths
{
public const string PluginSettingsFile = "GameLiftSettings.yaml";
public const string PackageName = "com.amazonaws.gamelift";
public const string SampleGameInPackage = "Samples~/SampleGame.unitypackage";
public const string ScenariosRootInPackage = "Editor/Resources/CloudFormation";
public const string LambdaFolderPathInScenario = "lambda";
public const string CfnTemplateFileName = "cloudformation.yml";
public const string ParametersFileName = "parameters.json";
public const string ServerSdkDllInPackage = "Runtime/Plugins/GameLiftServerSDKNet45.dll";
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
public sealed class ScenarioParameter
{
public string ParameterKey { get; set; }
public string ParameterValue { get; set; }
}
}
| 13 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
public static class ScenarioParameterKeys
{
public const string GameName = "GameNameParameter";
public const string LaunchPath = "LaunchPathParameter";
}
}
| 12 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
using Newtonsoft.Json;
using CoreErrorCode = AmazonGameLiftPlugin.Core.Shared.ErrorCode;
namespace AmazonGameLift.Editor
{
public class ScenarioParametersEditor
{
public static readonly string ErrorReadingFailed = "ReadingFailed";
public static readonly string ErrorWritingFailed = "WritingFailed";
public static readonly string ErrorEditingInProgress = "EditingInProgress";
public static readonly string ErrorEditingNotInProgress = "EditingNotInProgress";
private List<ScenarioParameter> _currentParameters;
/// <summary>
/// Possible errors: <see cref="ErrorCode.InvalidParameters"/> if <see cref="parameters"/> is null or empty,
/// <see cref="ErrorReadingFailed"/>, <see cref="ErrorEditingInProgress"/>.
/// </summary>
public virtual Response ReadParameters(string serializedParameters)
{
if (string.IsNullOrEmpty(serializedParameters))
{
return Response.Fail(new Response() { ErrorCode = CoreErrorCode.InvalidParameters });
}
if (_currentParameters != null)
{
return Response.Fail(new Response() { ErrorCode = ErrorEditingInProgress });
}
try
{
_currentParameters = JsonConvert.DeserializeObject<List<ScenarioParameter>>(serializedParameters);
return Response.Ok(new Response());
}
catch (JsonException ex)
{
var response = new Response()
{
ErrorCode = ErrorReadingFailed,
ErrorMessage = ex.Message
};
return Response.Fail(response);
}
}
/// <summary>
/// Possible errors: <see cref="ErrorWritingFailed"/>, <see cref="ErrorEditingNotInProgress"/>.
/// </summary>
public virtual SaveParametersResponse SaveParameters()
{
if (_currentParameters == null)
{
return Response.Fail(new SaveParametersResponse() { ErrorCode = ErrorEditingNotInProgress });
}
try
{
string serialized = JsonConvert.SerializeObject(_currentParameters);
_currentParameters = null;
return Response.Ok(new SaveParametersResponse(serialized));
}
catch (JsonException ex)
{
var response = new SaveParametersResponse()
{
ErrorCode = ErrorWritingFailed,
ErrorMessage = ex.Message
};
return Response.Fail(response);
}
}
/// <summary>
/// Possible errors: <see cref="ErrorCode.InvalidParameters"/> if <see cref="key"/>
/// or <see cref="value"/> is null or empty, <see cref="ErrorEditingNotInProgress"/>.
/// </summary>
public virtual Response SetParameter(string key, string value)
{
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value))
{
return Response.Fail(new Response() { ErrorCode = CoreErrorCode.InvalidParameters });
}
if (_currentParameters == null)
{
return Response.Fail(new SaveParametersResponse() { ErrorCode = ErrorEditingNotInProgress });
}
ScenarioParameter parameter = _currentParameters.Find(item => item.ParameterKey == key);
if (parameter == null)
{
parameter = new ScenarioParameter()
{
ParameterKey = key,
ParameterValue = value
};
_currentParameters.Add(parameter);
}
parameter.ParameterValue = value;
return Response.Ok(new Response());
}
}
}
| 112 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
public static class SettingsKeys
{
public const string CurrentBucketName = "CurrentBucketName";
public const string CurrentProfileName = "CurrentProfileName";
public const string CurrentRegion = "CurrentRegion";
public const string GameLiftLocalPath = "GameLiftLocalPath";
public const string GameLiftLocalPort = "GameLiftLocalPort";
public const string LocalServerPath = "LocalServerPath";
public const string DeploymentScenarioIndex = "DeploymentScenarioIndex";
public const string DeploymentGameName = "DeploymentGameName";
public const string DeploymentBuildFilePath = "DeploymentBuildFilePath";
public const string DeploymentBuildFolderPath = "DeploymentBuildFolderPath";
public const string WasSettingsWindowShown = "WasSettingsWindowShown";
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
public static class StackOutputKeys
{
public const string ApiGatewayEndpoint = "ApiGatewayEndpoint";
public const string UserPoolClientId = "UserPoolClientId";
}
}
| 12 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
namespace AmazonGameLift.Editor
{
/// <summary>
/// All statuses at https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html
/// </summary>
public static class StackStatus
{
public const string CreateComplete = "CREATE_COMPLETE";
public const string CreateFailed = "CREATE_FAILED";
public const string CreateInProgress = "CREATE_IN_PROGRESS";
public const string DeleteComplete = "DELETE_COMPLETE";
public const string DeleteFailed = "DELETE_FAILED";
public const string DeleteInProgress = "DELETE_IN_PROGRESS";
public const string ReviewInProgress = "REVIEW_IN_PROGRESS";
public const string RollbackComplete = "ROLLBACK_COMPLETE";
public const string RollbackFailed = "ROLLBACK_FAILED";
public const string RollbackInProgress = "ROLLBACK_IN_PROGRESS";
public const string UpdateComplete = "UPDATE_COMPLETE";
public const string UpdateCompleteCleanUpInProgress = "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS";
public const string UpdateFailed = "UPDATE_FAILED";
public const string UpdateInProgress = "UPDATE_IN_PROGRESS";
public const string UpdateRollbackInProgress = "UPDATE_ROLLBACK_IN_PROGRESS";
public const string UpdateRollbackComplete = "UPDATE_ROLLBACK_COMPLETE";
public static bool IsStackStatusOperationDone(this string stackStatus)
{
if (stackStatus is null)
{
throw new ArgumentNullException(nameof(stackStatus));
}
return stackStatus.Contains("_COMPLETE") || stackStatus.Contains("_FAILED");
}
public static bool IsStackStatusModifiable(this string stackStatus)
{
if (stackStatus is null)
{
throw new ArgumentNullException(nameof(stackStatus));
}
return stackStatus.Contains("_COMPLETE")
&& stackStatus != DeleteComplete
&& stackStatus != RollbackComplete;
}
}
}
| 53 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
internal sealed class UntilResponseFailurePoller : IResponsePoller
{
private readonly Delay _delay;
public UntilResponseFailurePoller(Delay delay) => _delay = delay;
public async Task<T> Poll<T>(int periodMs, Func<T> action, Predicate<T> stopCondition = null) where T : Response
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
T response;
while (true)
{
response = action();
if (!response.Success)
{
break;
}
if (stopCondition != null && stopCondition(response))
{
break;
}
await Task.Delay(periodMs);
}
return response;
}
}
}
| 46 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
namespace AmazonGameLift.Editor
{
public sealed class ConfirmChangesRequest
{
public string Region { get; set; }
public string StackId { get; set; }
public string ChangeSetId { get; set; }
public IEnumerable<Change> Changes { get; set; }
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
namespace AmazonGameLift.Editor
{
public readonly struct DeploymentId
{
public string Profile { get; }
public string Region { get; }
public string StackName { get; }
public string ScenarioName { get; }
public DeploymentId(DeploymentRequest deploymentRequest, string scenarioName)
{
if (deploymentRequest is null)
{
throw new ArgumentNullException(nameof(deploymentRequest));
}
Profile = deploymentRequest.Profile;
Region = deploymentRequest.Region;
StackName = deploymentRequest.StackName;
ScenarioName = scenarioName ?? throw new ArgumentNullException(nameof(scenarioName));
}
public DeploymentId(string profile, string region, string stackName, string scenarioName)
{
Profile = profile ?? throw new ArgumentNullException(nameof(profile));
Region = region ?? throw new ArgumentNullException(nameof(region));
StackName = stackName ?? throw new ArgumentNullException(nameof(stackName));
ScenarioName = scenarioName ?? throw new ArgumentNullException(nameof(scenarioName));
}
}
}
| 37 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
public sealed class DeploymentRequest
{
public string Profile { get; set; }
public string Region { get; set; }
public string BucketName { get; set; }
public string CfnTemplatePath { get; set; }
public string ParametersPath { get; set; }
public string StackName { get; set; }
public bool IsDevelopmentBuild { get; set; }
public string GameName { get; set; }
public string LambdaFolderPath { get; set; }
public string ChangeSetName { get; set; }
public string BuildFolderPath { get; set; }
public string BuildS3Key { get; set; }
}
}
| 22 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
public sealed class DeploymentResponse : Response
{
public DeploymentId DeploymentId { get; }
public DeploymentResponse()
{
}
public DeploymentResponse(Response failedResponse)
{
if (failedResponse is null)
{
throw new ArgumentNullException(nameof(failedResponse));
}
ErrorCode = failedResponse.ErrorCode;
ErrorMessage = failedResponse.ErrorMessage;
}
public DeploymentResponse(DeploymentId deploymentId) => DeploymentId = deploymentId;
public DeploymentResponse(string errorCode, string errorMessage = null)
{
if (errorCode is null)
{
throw new ArgumentNullException(nameof(errorCode));
}
ErrorCode = errorCode;
ErrorMessage = errorMessage;
}
}
}
| 42 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
public sealed class FileReadAllTextResponse : Response
{
public string Text { get; }
internal FileReadAllTextResponse(string text) => Text = text
?? throw new ArgumentNullException(nameof(text));
internal FileReadAllTextResponse()
{
}
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
public sealed class GetBootstrapDataResponse : Response
{
public string Profile { get; }
public string Region { get; }
internal GetBootstrapDataResponse(string profile, string region)
{
Profile = profile ?? throw new ArgumentNullException(nameof(profile));
Region = region ?? throw new ArgumentNullException(nameof(region));
}
internal GetBootstrapDataResponse()
{
}
}
}
| 26 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
public sealed class SaveParametersResponse : Response
{
public string SerializedParameters { get; }
internal SaveParametersResponse(string serializedParameters) => SerializedParameters = serializedParameters
?? throw new ArgumentNullException(nameof(serializedParameters));
internal SaveParametersResponse()
{
}
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Linq;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
namespace AmazonGameLift.Editor
{
internal class AwsCredentials
{
private const int NewProfileMode = 0;
private const int SelectProfileMode = 1;
private readonly CoreApi _coreApi;
private int _selectedMode;
private int _confirmedMode = -1;
public bool IsNewProfileMode => SelectedMode == NewProfileMode;
public int SelectedMode
{
get => _selectedMode;
set
{
_selectedMode = value;
SetUpSelectedMode();
}
}
public AwsCredentialsCreation Creation { get; private set; }
public AwsCredentialsUpdate Update { get; private set; }
public bool CanSelect { get; private set; }
public AwsCredentials(TextProvider textProvider, ILogger logger, CoreApi coreApi = null)
{
_coreApi = coreApi ?? CoreApi.SharedInstance;
var regionBootstrap = new RegionBootstrap(_coreApi);
Creation = new AwsCredentialsCreation(textProvider, regionBootstrap, _coreApi, logger);
Update = new AwsCredentialsUpdate(textProvider, regionBootstrap, _coreApi, logger);
Creation.OnCreated += OnCreated;
}
internal AwsCredentials(AwsCredentialsCreation creation, AwsCredentialsUpdate update, CoreApi coreApi = null)
{
_coreApi = coreApi ?? CoreApi.SharedInstance;
Creation = creation ?? throw new ArgumentNullException(nameof(creation));
Update = update ?? throw new ArgumentNullException(nameof(update));
Creation.OnCreated += OnCreated;
}
public void SetUp()
{
Refresh();
SelectedMode = CanSelect ? SelectProfileMode : NewProfileMode;
}
public void Refresh()
{
GetProfilesResponse response = _coreApi.ListCredentialsProfiles();
CanSelect = response.Success && response.Profiles.Any();
}
private void SetUpSelectedMode()
{
if (_confirmedMode == SelectedMode)
{
return;
}
_confirmedMode = SelectedMode;
Refresh();
if (IsNewProfileMode)
{
Creation.Refresh();
}
else
{
Update.Refresh();
}
}
private void OnCreated()
{
Refresh();
}
}
}
| 89 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Linq;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class AwsCredentialsCreation
{
private readonly CoreApi _coreApi;
private readonly ILogger _logger;
private readonly TextProvider _textProvider;
private readonly Status _status = new Status();
public IReadStatus Status => _status;
public RegionBootstrap RegionBootstrap { get; }
public bool CanCreate =>
!string.IsNullOrEmpty(ProfileName)
&& !string.IsNullOrEmpty(AccessKeyId)
&& !string.IsNullOrEmpty(SecretKey)
&& RegionBootstrap.CanSave;
public string CurrentProfileName { get; private set; }
public string ProfileName { get; set; }
public string AccessKeyId { get; set; }
public string SecretKey { get; set; }
public event Action OnCreated;
public AwsCredentialsCreation(TextProvider textProvider, RegionBootstrap regionBootstrap,
CoreApi coreApi, ILogger logger)
{
_coreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
RegionBootstrap = regionBootstrap ?? throw new ArgumentNullException(nameof(regionBootstrap));
}
public virtual void Refresh()
{
_status.IsDisplayed = false;
RegionBootstrap.Refresh();
CurrentProfileName = null;
GetProfilesResponse response = _coreApi.ListCredentialsProfiles();
if (!response.Success)
{
_logger.LogResponseError(response);
return;
}
string[] allProlfileNames = response.Profiles.ToArray();
if (allProlfileNames.Length == 0)
{
return;
}
GetSettingResponse getCurrentResponse = _coreApi.GetSetting(SettingsKeys.CurrentProfileName);
if (!getCurrentResponse.Success)
{
return;
}
int currentIndex = Array.IndexOf(allProlfileNames, getCurrentResponse.Value);
if (currentIndex >= 0)
{
CurrentProfileName = allProlfileNames[currentIndex];
}
}
public void Create()
{
if (!CanCreate)
{
_logger.Log(DevStrings.OperationInvalid, LogType.Error);
return;
}
Response response = _coreApi.SaveAwsCredentials(ProfileName, AccessKeyId, SecretKey);
if (!response.Success)
{
SetErrorStatus(response.ErrorCode);
_logger.LogResponseError(response);
return;
}
Response writeResponse = _coreApi.PutSetting(SettingsKeys.CurrentProfileName, ProfileName);
if (!writeResponse.Success)
{
SetErrorStatus(writeResponse.ErrorCode);
_logger.LogResponseError(writeResponse);
return;
}
CurrentProfileName = ProfileName;
RegionBootstrap.Save();
_status.SetMessage(_textProvider.Get(Strings.StatusProfileCreated), MessageType.Info);
_status.IsDisplayed = true;
OnCreated?.Invoke();
}
private void SetErrorStatus(string errorCode = null)
{
string message = _textProvider.GetError(errorCode);
_status.SetMessage(message, MessageType.Error);
_status.IsDisplayed = true;
}
}
}
| 125 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class AwsCredentialsCreationPanel
{
private readonly HyperLinkButton _hyperLinkButton;
private readonly ControlDrawer _controlDrawer;
private readonly StatusLabel _statusLabel;
private readonly TextProvider _textProvider;
private readonly AwsCredentialsCreation _model;
private readonly PasswordDrawer _awsKeyPasswordDrawer;
private readonly PasswordDrawer _awsSecretKeyPasswordDrawer;
private readonly string _labelCreateProfileName;
private readonly string _labelCurrentProfileName;
private readonly string _tooltipCreateProfile;
private readonly string _tooltipRegion;
private readonly string _labelCreateButton;
private readonly string _labelRegion;
public AwsCredentialsCreationPanel(AwsCredentialsCreation model, StatusLabel statusLabel,
TextProvider textProvider, ControlDrawer controlDrawer)
{
_statusLabel = statusLabel ?? throw new ArgumentNullException(nameof(statusLabel));
_textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
_controlDrawer = controlDrawer ?? throw new ArgumentNullException(nameof(controlDrawer));
_model = model ?? throw new ArgumentNullException(nameof(model));
_hyperLinkButton = new HyperLinkButton(_textProvider.Get(Strings.LabelCredentialsHelp),
Urls.AwsHelpCredentials, ResourceUtility.GetHyperLinkStyle());
_awsKeyPasswordDrawer = new PasswordDrawer(textProvider, controlDrawer, Strings.LabelCredentialsAccessKey, Strings.TooltipCredentialsAccessKey);
_awsSecretKeyPasswordDrawer = new PasswordDrawer(textProvider, controlDrawer, Strings.LabelCredentialsSecretKey, Strings.TooltipCredentialsSecretKey);
_labelCreateButton = _textProvider.Get(Strings.LabelCredentialsCreateButton);
_labelCreateProfileName = _textProvider.Get(Strings.LabelCredentialsCreateProfileName);
_labelRegion = _textProvider.Get(Strings.LabelCredentialsRegion);
_labelCurrentProfileName = _textProvider.Get(Strings.LabelCredentialsCurrentProfileName);
_tooltipCreateProfile = _textProvider.Get(Strings.TooltipCredentialsCreateProfile);
_tooltipRegion = _textProvider.Get(Strings.TooltipCredentialsRegion);
}
public void Draw()
{
_model.ProfileName = _controlDrawer.DrawTextField(_labelCreateProfileName, _model.ProfileName, _tooltipCreateProfile);
_model.AccessKeyId = _awsKeyPasswordDrawer.Draw(_model.AccessKeyId);
_model.SecretKey = _awsSecretKeyPasswordDrawer.Draw(_model.SecretKey);
_model.RegionBootstrap.RegionIndex = _controlDrawer.DrawPopup(
_labelRegion, _model.RegionBootstrap.RegionIndex, _model.RegionBootstrap.AllRegions, _tooltipRegion);
_controlDrawer.DrawSeparator();
_controlDrawer.DrawReadOnlyText(_labelCurrentProfileName, _model.CurrentProfileName);
DrawLink();
GUILayout.Space(13f);
using (new EditorGUI.DisabledGroupScope(!_model.CanCreate))
{
if (GUILayout.Button(_labelCreateButton))
{
_model.Create();
}
}
if (_model.Status.IsDisplayed)
{
_statusLabel.Draw(_model.Status.Message, _model.Status.Type);
}
}
public void CleanUp()
{
_awsKeyPasswordDrawer.Hide();
_awsSecretKeyPasswordDrawer.Hide();
}
private void DrawLink()
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5f);
_hyperLinkButton.Draw();
}
}
}
}
| 90 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal class AwsCredentialsFactory
{
public static AwsCredentials Create()
{
TextProvider textProvider = TextProviderFactory.Create();
return new AwsCredentials(textProvider, UnityLoggerFactory.Create(textProvider));
}
}
}
| 16 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Linq;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class AwsCredentialsUpdate
{
private readonly CoreApi _coreApi;
private readonly ILogger _logger;
private readonly TextProvider _textProvider;
private readonly Status _status = new Status();
private int _selectedProfileIndex;
private string _currentAccessKeyId;
private string _currentSecretKey;
public IReadStatus Status => _status;
public RegionBootstrap RegionBootstrap { get; }
public bool CanUpdate =>
SelectedProfileIndex >= 0 && _selectedProfileIndex < AllProlfileNames.Length
&& !string.IsNullOrEmpty(AccessKeyId)
&& !string.IsNullOrEmpty(SecretKey)
&& (SelectedProfileIndex != CurrentProfileIndex || CanUpdateCurrentProfile || RegionBootstrap.CanSave);
public bool CanUpdateCurrentProfile =>
CurrentProfileIndex >= 0
&& (AccessKeyId != _currentAccessKeyId || SecretKey != _currentSecretKey);
public string CurrentProfileName { get; private set; }
public int CurrentProfileIndex { get; private set; } = -1;
public string[] AllProlfileNames { get; private set; } = new string[0];
public string AccessKeyId { get; set; }
public string SecretKey { get; set; }
/// <summary>
/// When changed, loads <see cref="AccessKeyId"/> and <see cref="SecretKey"/>.
/// </summary>
public int SelectedProfileIndex
{
get => _selectedProfileIndex;
set
{
if (_selectedProfileIndex == value)
{
return;
}
_selectedProfileIndex = value;
Load();
}
}
public AwsCredentialsUpdate(TextProvider textProvider, RegionBootstrap regionBootstrap,
CoreApi coreApi, ILogger logger)
{
_coreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
RegionBootstrap = regionBootstrap ?? throw new ArgumentNullException(nameof(regionBootstrap));
}
/// <summary>
/// Loads <see cref="AccessKeyId"/> and <see cref="SecretKey"/>.
/// </summary>
public void Load()
{
AccessKeyId = null;
SecretKey = null;
if (_selectedProfileIndex < 0 || _selectedProfileIndex >= AllProlfileNames.Length)
{
return;
}
string profileName = AllProlfileNames[_selectedProfileIndex];
RetriveAwsCredentialsResponse response = _coreApi.RetrieveAwsCredentials(profileName);
if (!response.Success)
{
SetErrorStatus(response.ErrorCode);
return;
}
AccessKeyId = response.AccessKey;
SecretKey = response.SecretKey;
if (_selectedProfileIndex == CurrentProfileIndex)
{
_currentAccessKeyId = AccessKeyId;
_currentSecretKey = SecretKey;
}
}
/// <summary>
/// Sets the profile by <see cref="SelectedProfileIndex"/> as current, saves its credentials.
/// </summary>
public void Update()
{
if (!CanUpdate)
{
_logger.Log(DevStrings.OperationInvalid, LogType.Error);
return;
}
string profileName = AllProlfileNames[_selectedProfileIndex];
Response response = _coreApi.UpdateAwsCredentials(profileName, AccessKeyId, SecretKey);
if (!response.Success)
{
SetErrorStatus(response.ErrorCode);
_logger.LogResponseError(response);
return;
}
Response writeResponse = _coreApi.PutSetting(SettingsKeys.CurrentProfileName, profileName);
if (!writeResponse.Success)
{
SetErrorStatus(writeResponse.ErrorCode);
_logger.LogResponseError(writeResponse);
return;
}
(bool success, string errorCode) = RegionBootstrap.Save();
if (!success && errorCode != null)
{
string messageFormat = _textProvider.Get(Strings.StatusRegionUpdateFailedWithError);
string error = _textProvider.GetError(errorCode);
error = string.Format(messageFormat, error);
_status.SetMessage(error, MessageType.Error);
}
else
{
_status.SetMessage(_textProvider.Get(Strings.StatusProfileUpdated), MessageType.Info);
}
_coreApi.ClearSetting(SettingsKeys.CurrentBucketName);
CurrentProfileIndex = SelectedProfileIndex;
CurrentProfileName = profileName;
_currentAccessKeyId = AccessKeyId;
_currentSecretKey = SecretKey;
_status.IsDisplayed = true;
}
/// <summary>
/// Loads profile names, sets <see cref="AllProlfileNames"/>.
/// If any profiles are loaded and one of them is selected in settings,
/// sets <see cref="SelectedProfileIndex"/> to match it.
/// </summary>
/// <returns></returns>
public virtual void Refresh()
{
RegionBootstrap.Refresh();
SelectedProfileIndex = -1;
CurrentProfileName = null;
_currentAccessKeyId = null;
_currentSecretKey = null;
AllProlfileNames = Array.Empty<string>();
GetProfilesResponse response = _coreApi.ListCredentialsProfiles();
if (!response.Success)
{
_logger.LogResponseError(response);
return;
}
AllProlfileNames = response.Profiles.ToArray();
if (AllProlfileNames.Length == 0)
{
return;
}
GetSettingResponse getCurrentResponse = _coreApi.GetSetting(SettingsKeys.CurrentProfileName);
if (!getCurrentResponse.Success)
{
return;
}
int currentIndex = Array.IndexOf(AllProlfileNames, getCurrentResponse.Value);
if (currentIndex >= 0)
{
SelectedProfileIndex = currentIndex;
CurrentProfileIndex = currentIndex;
CurrentProfileName = AllProlfileNames[CurrentProfileIndex];
Load();
}
}
private void SetErrorStatus(string errorCode = null)
{
string message = _textProvider.GetError(errorCode);
_status.SetMessage(message, MessageType.Error);
_status.IsDisplayed = true;
}
}
}
| 214 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class AwsCredentialsUpdatePanel
{
private readonly HyperLinkButton _hyperLinkButton;
private readonly ControlDrawer _controlDrawer;
private readonly StatusLabel _statusLabel;
private readonly TextProvider _textProvider;
private readonly AwsCredentialsUpdate _model;
private readonly PasswordDrawer _awsKeyPasswordDrawer;
private readonly PasswordDrawer _awsSecretKeyPasswordDrawer;
private readonly string _labelRegion;
private readonly string _tooltipSelectProfile;
private readonly string _tooltipRegion;
private readonly string _labelUpdateButton;
private readonly string _labelSelectProfileName;
private readonly string _labelCurrentProfileName;
public AwsCredentialsUpdatePanel(AwsCredentialsUpdate model, StatusLabel statusLabel, TextProvider textProvider, ControlDrawer controlDrawer)
{
_model = model ?? throw new ArgumentNullException(nameof(model));
_textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
_hyperLinkButton = new HyperLinkButton(
_textProvider.Get(Strings.LabelCredentialsHelp),
Urls.AwsHelpCredentials, ResourceUtility.GetHyperLinkStyle());
_controlDrawer = controlDrawer ?? throw new ArgumentNullException(nameof(controlDrawer));
_statusLabel = statusLabel ?? throw new ArgumentNullException(nameof(statusLabel));
_awsKeyPasswordDrawer = new PasswordDrawer(textProvider, controlDrawer, Strings.LabelCredentialsAccessKey, Strings.TooltipCredentialsAccessKey);
_awsSecretKeyPasswordDrawer = new PasswordDrawer(textProvider, controlDrawer, Strings.LabelCredentialsSecretKey, Strings.TooltipCredentialsSecretKey);
_labelUpdateButton = _textProvider.Get(Strings.LabelCredentialsUpdateButton);
_labelSelectProfileName = _textProvider.Get(Strings.LabelCredentialsSelectProfileName);
_labelRegion = _textProvider.Get(Strings.LabelCredentialsRegion);
_labelCurrentProfileName = _textProvider.Get(Strings.LabelCredentialsCurrentProfileName);
_tooltipSelectProfile = _textProvider.Get(Strings.TooltipCredentialsSelectProfile);
_tooltipRegion = _textProvider.Get(Strings.TooltipCredentialsRegion);
}
public void Draw()
{
_model.SelectedProfileIndex = _controlDrawer.DrawPopup(
_labelSelectProfileName, _model.SelectedProfileIndex, _model.AllProlfileNames, _tooltipSelectProfile);
_model.AccessKeyId = _awsKeyPasswordDrawer.Draw(_model.AccessKeyId);
_model.SecretKey = _awsSecretKeyPasswordDrawer.Draw(_model.SecretKey);
_model.RegionBootstrap.RegionIndex = _controlDrawer.DrawPopup(
_labelRegion, _model.RegionBootstrap.RegionIndex, _model.RegionBootstrap.AllRegions, _tooltipRegion);
_controlDrawer.DrawSeparator();
_controlDrawer.DrawReadOnlyText(_labelCurrentProfileName, _model.CurrentProfileName);
DrawLink();
GUILayout.Space(13f);
using (new EditorGUI.DisabledGroupScope(!_model.CanUpdate))
{
if (GUILayout.Button(_labelUpdateButton))
{
_model.Update();
}
}
if (_model.Status.IsDisplayed)
{
_statusLabel.Draw(_model.Status.Message, _model.Status.Type);
}
}
public void CleanUp()
{
_awsKeyPasswordDrawer.Hide();
_awsSecretKeyPasswordDrawer.Hide();
}
private void DrawLink()
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5f);
_hyperLinkButton.Draw();
}
}
}
}
| 92 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class AwsCredentialsWindow : EditorWindow
{
private const float WindowWidthPixels = 415f;
private const float WindowCreationHeightPixels = 280f;
private const float TopMarginPixels = 17f;
private const float LeftMarginPixels = 15f;
private const float RightMarginPixels = 13f;
private const float LabelWidthPixels = 165f;
private AwsCredentials _awsCredentials;
private StatusLabel _statusLabel;
private AwsCredentialsCreationPanel _creationPanel;
private AwsCredentialsUpdatePanel _updatePanel;
private string[] _uiModes = new string[0];
private void SetUp()
{
ControlDrawer controlDrawer = ControlDrawerFactory.Create();
TextProvider textProvider = TextProviderFactory.Create();
titleContent = new GUIContent(textProvider.Get(Strings.TitleAwsCredentials));
this.SetConstantSize(new Vector2(x: WindowWidthPixels, y: WindowCreationHeightPixels));
_awsCredentials = AwsCredentialsFactory.Create();
_statusLabel = new StatusLabel();
_creationPanel = new AwsCredentialsCreationPanel(_awsCredentials.Creation, _statusLabel, textProvider, controlDrawer);
_updatePanel = new AwsCredentialsUpdatePanel(_awsCredentials.Update, _statusLabel, textProvider, controlDrawer);
_uiModes = new[]
{
textProvider.Get(Strings.LabelCredentialsCreateMode),
textProvider.Get(Strings.LabelCredentialsUpdateMode),
};
_awsCredentials.SetUp();
}
private void OnEnable()
{
SetUp();
_awsCredentials.Creation.Status.Changed += OnStatusChanged;
}
private void OnDisable()
{
_awsCredentials.Creation.Status.Changed -= OnStatusChanged;
}
private void OnGUI()
{
EditorGUIUtility.labelWidth = LabelWidthPixels;
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(LeftMarginPixels);
using (new EditorGUILayout.VerticalScope())
{
GUILayout.Space(TopMarginPixels);
DrawControls();
}
GUILayout.Space(RightMarginPixels);
}
}
private void DrawControls()
{
using (new EditorGUI.DisabledScope(!_awsCredentials.CanSelect))
{
int previousMode = _awsCredentials.SelectedMode;
_awsCredentials.SelectedMode = GUILayout.SelectionGrid(_awsCredentials.SelectedMode,
_uiModes, 1, EditorStyles.radioButton);
if (previousMode != _awsCredentials.SelectedMode)
{
GUI.FocusControl(null);
_creationPanel.CleanUp();
_updatePanel.CleanUp();
}
}
GUILayout.Space(7f);
if (_awsCredentials.IsNewProfileMode)
{
_creationPanel.Draw();
}
else
{
_updatePanel.Draw();
}
}
private void OnStatusChanged()
{
Repaint();
}
}
}
| 106 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class PasswordDrawer
{
private readonly ControlDrawer _controlDrawer;
private readonly TextProvider _textProvider;
private readonly string _labelPasswordShow;
private readonly string _labelPasswordHide;
private readonly string _label;
private readonly string _tooltip;
private bool _isValueShown;
public PasswordDrawer(TextProvider textProvider, ControlDrawer controlDrawer, string labelKey, string tooltipKey)
{
_textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
_controlDrawer = controlDrawer ?? throw new ArgumentNullException(nameof(controlDrawer));
_labelPasswordShow = _textProvider.Get(Strings.LabelPasswordShow);
_labelPasswordHide = _textProvider.Get(Strings.LabelPasswordHide);
_label = _textProvider.Get(labelKey);
_tooltip = _textProvider.Get(tooltipKey);
}
public string Draw(string value)
{
using (new EditorGUILayout.HorizontalScope())
{
string newValue = _isValueShown
? _controlDrawer.DrawTextField(_label, value, _tooltip)
: _controlDrawer.DrawPasswordField(_label, value, _tooltip);
string buttonText = _isValueShown ? _labelPasswordHide : _labelPasswordShow;
bool needSwitch = GUILayout.Button(buttonText, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false), GUILayout.Width(45f));
if (needSwitch)
{
_isValueShown = !_isValueShown;
GUI.FocusControl(null);
}
return newValue;
}
}
public void Hide()
{
_isValueShown = false;
}
}
}
| 57 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
/// <summary>
/// The keys for <see cref="TextProvider"/>. The strings should just be unique.
/// </summary>
public static class Strings
{
public const string LabelPasswordShow = "LabelPasswordShow";
public const string LabelPasswordHide = "LabelPasswordHide";
public const string LabelBootstrapS3Console = "LabelBootstrapS3Console";
public const string LabelBootstrapCreateMode = "LabelBootstrapCreateMode";
public const string LabelBootstrapSelectMode = "LabelBootstrapSelectMode";
public const string LabelBootstrapCurrentBucket = "LabelBootstrapCurrentBucket";
public const string LabelBootstrapCreateButton = "LabelBootstrapCreateButton";
public const string LabelBootstrapSelectButton = "LabelBootstrapSelectButton";
public const string LabelBootstrapBucketCosts = "LabelBootstrapBucketCosts";
public const string LabelBootstrapBucketName = "LabelBootstrapBucketName";
public const string LabelBootstrapLifecycleWarning = "LabelBootstrapLifecycleWarning";
public const string LabelBootstrapBucketSelectionLoading = "LabelBootstrapBucketSelectionLoading";
public const string LabelBootstrapRegion = "LabelBootstrapRegion";
public const string LabelBootstrapBucketLifecycle = "LabelBootstrapBucketLifecycle";
public const string LabelCredentialsHelp = "LabelCredentialsHelp";
public const string LabelCredentialsRegion = "LabelCredentialsRegion";
public const string LabelCredentialsCreateProfileName = "LabelCredentialsProfileName";
public const string LabelCredentialsAccessKey = "LabelCredentialsAccessKey";
public const string LabelCredentialsSecretKey = "LabelCredentialsSecretKey";
public const string LabelCredentialsCreateButton = "LabelCredentialsCreateButton";
public const string LabelCredentialsUpdateButton = "LabelCredentialsUpdateButton";
public const string LabelCredentialsUpdateMode = "LabelCredentialsUpdateMode";
public const string LabelCredentialsCreateMode = "LabelCredentialsCreateMode";
public const string LabelCredentialsSelectProfileName = "LabelCredentialsSelectProfileName";
public const string LabelCredentialsCurrentProfileName = "LabelCredentialsCurrentProfileName";
public const string LabelDefaultFolderName = "LabelDefaultFolderName";
public const string LabelDeploymentApiGateway = "LabelDeploymentApiGateway";
public const string LabelDeploymentCognitoClientId = "LabelDeploymentCognitoClientId";
public const string LabelDeploymentCloudFormationConsole = "LabelDeploymentCloudFormationConsole";
public const string LabelDeploymentCustomMode = "LabelDeploymentCustomMode";
public const string LabelDeploymentHelp = "LabelDeploymentHelp";
public const string LabelDeploymentSelectionMode = "LabelDeploymentSelectionMode";
public const string LabelDeploymentGameName = "LabelDeploymentGameName";
public const string LabelDeploymentCurrentStack = "LabelDeploymentCurrentStack";
public const string LabelDeploymentCosts = "LabelDeploymentCosts";
public const string LabelDeploymentBootstrapWarning = "LabelDeploymentBootstrapWarning";
public const string LifecycleNone = "LifecycleNone";
public const string LifecycleSevenDays = "LifecycleSevenDays";
public const string LifecycleThirtyDays = "LifecycleThirtyDays";
public const string StatusDeploymentExePathInvalid = "StatusDeploymentExePathInvalid";
public const string StatusDeploymentFailure = "StatusDeploymentFailure";
public const string StatusDeploymentStarting = "StatusDeploymentStarting";
public const string StatusDeploymentSuccess = "StatusDeploymentSuccess";
public const string StatusExceptionThrown = "StatusExceptionThrown";
public const string StatusNothingDeployed = "StatusNothingDeployed";
public const string StatusProfileCreated = "StatusProfileCreated";
public const string StatusProfileUpdated = "StatusProfileUpdated";
public const string StatusGetRegionFailed = "StatusGetRegionFailed";
public const string StatusGetProfileFailed = "StatusGetProfileFailed";
public const string StatusBootstrapComplete = "StatusBootstrapComplete";
public const string StatusBootstrapUpdateComplete = "StatusBootstrapUpdateComplete";
public const string StatusBootstrapFailedTemplate = "StatusBootstrapFailedTemplate";
public const string StatusRegionUpdateFailedWithError = "StatusRegionUpdateFailedWithError";
public const string TitleAwsCredentials = "TitleAwsCredentials";
public const string TitleBootstrap = "TitleBootstrap";
public const string TooltipBootstrapBucketLifecycle = "TooltipBootstrapBucketLifecycle";
public const string TooltipBootstrapCurrentBucket = "TooltipBootstrapCurrentBucket";
public const string TooltipSettingsBootstrap = "TooltipSettingsBootstrap";
public const string TooltipSettingsAwsCredentials = "TooltipSettingsAwsCredentials";
public const string LabelSettingsAwsCredentialsTitle = "LabelSettingsAwsCredentialsTitle";
public const string LabelSettingsAwsCredentialsSetUpButton = "LabelSettingsAwsCredentialsSetUpButton";
public const string LabelAwsCredentialsUpdateButton = "LabelAwsCredentialsUpdateButton";
public const string LabelSettingsDotNetTitle = "LabelSettingsDotNetTitle";
public const string TooltipSettingsDotNet = "TooltipSettingsDotNet";
public const string LabelSettingsDotNetButton = "LabelSettingsDotNetButton";
public const string TooltipSettingsLocalTesting = "TooltipSettingsLocalTesting";
public const string LabelSettingsLocalTestingButton = "LabelSettingsLocalTestingButton";
public const string LabelSettingsLocalTestingSetPathButton = "LabelSettingsLocalTestingSetPathButton";
public const string TitleLocalTestingGameLiftPathDialog = "TitleLocalTestingGameLiftPathDialog";
public const string LabelSettingsJavaButton = "LabelSettingsJavaButton";
public const string LabelSettingsJavaTitle = "LabelSettingsJavaTitle";
public const string TooltipSettingsJava = "TooltipSettingsJava";
public const string LabelSettingsAllConfigured = "LabelSettingsAllConfigured";
public const string LabelSettingsConfigured = "LabelSettingsConfigured";
public const string LabelSettingsNotConfigured = "LabelSettingsNotConfigured";
public const string LabelSettingsBootstrapTitle = "LabelSettingsBootstrapTitle";
public const string LabelSettingsBootstrapButton = "LabelSettingsBootstrapButton";
public const string LabelSettingsBootstrapWarning = "LabelSettingsBootstrapWarning";
public const string LabelSettingsLocalTestingTitle = "LabelSettingsLocalTestingTitle";
public const string LabelSettingsDeployTab = "LabelSettingsDeployTab";
public const string LabelSettingsTestTab = "LabelSettingsTestTab";
public const string LabelSettingsHelpTab = "LabelSettingsHelpTab";
public const string LabelSettingsSdkTab = "LabelSettingsSdkTab";
public const string LabelSettingsOpenForums = "LabelSettingsOpenForums";
public const string LabelSettingsOpenAwsHelp = "LabelSettingsOpenAwsHelp";
public const string LabelSettingsOpenDeployment = "LabelSettingsOpenDeployment";
public const string LabelSettingsOpenLocalTest = "LabelSettingsOpenLocalTest";
public const string LabelSettingsPingSdk = "LabelSettingsPingSdk";
public const string LabelSettingsReportSecurity = "LabelSettingsReportSecurity";
public const string LabelSettingsReportBugs = "LabelSettingsReportBugs";
public const string LabelStackUpdateCancelButton = "LabelStackUpdateCancelButton";
public const string LabelStackUpdateCountTemplate = "LabelStackUpdateCountTemplate";
public const string LabelStackUpdateConfirmButton = "LabelStackUpdateConfirmButton";
public const string LabelStackUpdateConsole = "LabelStackUpdateConsole";
public const string LabelStackUpdateConsoleWarning = "LabelStackUpdateConsoleWarning";
public const string LabelStackUpdateRemovalHeader = "LabelStackUpdateRemovalHeader";
public const string LabelStackUpdateQuestion = "LabelStackUpdateQuestion";
public const string StatusLocalTestErrorTemplate = "StatusLocalTestErrorTemplate";
public const string StatusLocalTestServerErrorTemplate = "StatusLocalTestServerErrorTemplate";
public const string StatusLocalTestRunning = "StatusLocalTestRunning";
public const string TitleLocalTesting = "TitleLocalTesting";
public const string LabelLocalTestingHelp = "LabelLocalTestingHelp";
public const string LabelLocalTestingWindowsServerPath = "LabelLocalTestingWindowsServerPath";
public const string LabelLocalTestingMacOsServerPath = "LabelLocalTestingMacOsServerPath";
public const string TitleLocalTestingServerPathDialog = "TitleLocalTestingServerPathDialog";
public const string TooltipLocalTestingServerPath = "TooltipLocalTestingServerPath";
public const string LabelLocalTestingJarPath = "LabelLocalTestingJarPath";
public const string LabelLocalTestingPort = "LabelLocalTestingPort";
public const string TooltipLocalTestingPort = "TooltipLocalTestingPort";
public const string LabelLocalTestingStartButton = "LabelLocalTestingStartButton";
public const string LabelLocalTestingStopButton = "LabelLocalTestingStopButton";
public const string LabelDeploymentBucket = "LabelDeploymentBucket";
public const string LabelDeploymentBuildFilePath = "LabelDeploymentBuildFilePath";
public const string LabelDeploymentBuildFolderPath = "LabelDeploymentBuildFolderPath";
public const string LabelDeploymentCancelButton = "LabelDeploymentCancelButton";
public const string LabelDeploymentCancelDialogBody = "LabelDeploymentCancelDialogBody";
public const string LabelDeploymentCancelDialogCancelButton = "LabelDeploymentCancelDialogCancelButton";
public const string LabelDeploymentCancelDialogOkButton = "LabelDeploymentCancelDialogOkButton";
public const string LabelDeploymentRegion = "LabelDeploymentRegion";
public const string LabelDeploymentScenarioHelp = "LabelDeploymentScenarioHelp";
public const string LabelDeploymentScenarioPath = "LabelDeploymentScenarioPath";
public const string LabelDeploymentStartButton = "LabelDeploymentStartButton";
public const string TooltipDeploymentBucket = "TooltipDeploymentBucket";
public const string TooltipDeploymentRegion = "TooltipDeploymentRegion";
public const string TooltipCredentialsCreateProfile = "TooltipCredentialsCreateProfile";
public const string TooltipCredentialsSelectProfile = "TooltipCredentialsSelectProfile";
public const string TooltipCredentialsAccessKey = "TooltipCredentialsAccessKey";
public const string TooltipCredentialsSecretKey = "TooltipCredentialsSecretKey";
public const string TooltipCredentialsRegion = "TooltipCredentialsRegion";
public const string TitleDeployment = "TitleDeployment";
public const string TitleDeploymentCancelDialog = "TitleDeploymentCancelDialog";
public const string TitleDeploymentServerFileDialog = "TitleDeploymentServerFileDialog";
public const string TitleDeploymentServerFolderDialog = "TitleDeploymentServerFolderDialog";
public const string TitleSettings = "TitleSettings";
public const string TitleStackUpdateDialog = "TitleStackUpdateDialog";
public const string StackStatusTemplate = "StackStatusTemplate";
public const string StackDetailsTemplate = "StackDetailsTemplate";
public const string SettingsUISdkNextStepLabel = "SettingsUISdkNextStepLabel";
public const string SettingsUITestNextStepLabel = "SettingsUITestNextStepLabel";
public const string SettingsUIDeployNextStepLabel = "SettingsUIDeployNextStepLabel";
public const string LabelOpenSdkIntegrationDoc = "LabelOpenSdkIntegrationDoc";
public const string LabelOpenSdkApiDoc = "LabelOpenSdkApiDoc";
}
}
| 155 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using UnityEngine.Networking;
namespace AmazonGameLift.Editor
{
internal sealed class ChangeSetUrlFormatter
{
/// <exception cref="ArgumentNullException"></exception>
public string Format(ConfirmChangesRequest request)
{
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
string stackIdUrlEncoded = UnityWebRequest.EscapeURL(request.StackId);
string changeSetIdUrlEncoded = UnityWebRequest.EscapeURL(request.ChangeSetId);
return string.Format(Urls.AwsCloudFormationChangeSetTemplate, request.Region, stackIdUrlEncoded, changeSetIdUrlEncoded);
}
}
}
| 25 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AmazonGameLift.Editor
{
internal class DelayedOperation
{
private readonly Action _action;
private readonly Delay _delay;
private readonly int _delayMs;
private CancellationTokenSource _cancellation;
public DelayedOperation(Action action, Delay delay, int delayMs)
{
_action = action ?? throw new ArgumentNullException(nameof(action));
_delay = delay ?? throw new ArgumentNullException(nameof(delay));
_delayMs = delayMs;
}
public async Task Request()
{
Cancel();
_cancellation = new CancellationTokenSource();
try
{
await _delay.Wait(_delayMs, _cancellation.Token);
_action();
}
catch (TaskCanceledException)
{
}
}
public void Cancel()
{
_cancellation?.Cancel();
}
}
}
| 45 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal class DeploymentIdContainer : IDeploymentIdContainer
{
private DeploymentId? _deploymentId;
public bool HasValue => _deploymentId.HasValue;
public void Clear()
{
_deploymentId = null;
}
public DeploymentId Get()
{
return _deploymentId.Value;
}
public void Set(DeploymentId value)
{
_deploymentId = value;
}
}
}
| 28 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal static class DeploymentIdContainerFactory
{
private static IDeploymentIdContainer s_cachedContainer;
public static IDeploymentIdContainer Create()
{
return s_cachedContainer ?? (s_cachedContainer = new DeploymentIdContainer());
}
}
}
| 16 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using UnityEditor;
using UnityEngine;
using CoreErrorCode = AmazonGameLiftPlugin.Core.Shared.ErrorCode;
namespace AmazonGameLift.Editor
{
/// <summary>
/// The main backend for deployment to AWS.
/// </summary>
internal class DeploymentSettings
{
private const int StackInfoRefreshDelayMs = 2000;
private readonly List<DeployerBase> _deployers = new List<DeployerBase>();
private readonly ScenarioLocator _scenarioLocator;
private readonly PathConverter _pathConverter;
private readonly CoreApi _coreApi;
private readonly ScenarioParametersUpdater _parametersUpdater;
private readonly TextProvider _textProvider;
private readonly DeploymentWaiter _deploymentWaiter;
private readonly DelayedOperation _delayedStackInfoRefresh;
private int _scenarioIndex;
private string _gameName;
private DeploymentStackInfo _currentStackInfo;
private readonly IDeploymentIdContainer _currentDeploymentId;
private readonly ILogger _logger;
private readonly Status _status = new Status();
public IReadStatus Status => _status;
#region Bootstrap parameters
public string CurrentProfile { get; private set; }
public string CurrentRegion { get; private set; }
public string CurrentBucketName { get; private set; }
public bool HasCurrentBucket { get; private set; }
public bool IsBootstrapped => CurrentProfile != null && HasCurrentBucket;
#endregion
public string[] AllScenarios { get; private set; } = new string[0];
public string ScenarioName { get; private set; }
public string ScenarioPath { get; private set; }
public string ScenarioDescription { get; private set; }
public string ScenarioHelpUrl { get; private set; }
#region Scenario parameters
public string GameName
{
get => _gameName;
set => _ = SetGameNameAsync(value);
}
public string BuildFolderPath { get; set; }
public string BuildFilePath { get; set; }
#endregion Scenario parameters
public int ScenarioIndex
{
get => _scenarioIndex;
set
{
if (_scenarioIndex == value)
{
return;
}
_scenarioIndex = value;
RefreshScenario();
}
}
public bool IsFormFilled => !string.IsNullOrWhiteSpace(GameName)
&& IsValidScenarioIndex
&& IsBuildFolderPathFilled
&& IsBuildFilePathFilled;
public bool IsBuildFilePathFilled => IsValidScenarioIndex
&& (!_deployers[ScenarioIndex].HasGameServer || _coreApi.FileExists(BuildFilePath));
public bool IsBuildFolderPathFilled => IsValidScenarioIndex
&& (!_deployers[ScenarioIndex].HasGameServer || _coreApi.FolderExists(BuildFolderPath));
public bool IsBuildRequired =>
IsValidScenarioIndex && _deployers[ScenarioIndex].HasGameServer;
public bool IsValidScenarioIndex => ScenarioIndex >= 0 && ScenarioIndex < _deployers.Count;
public bool DoesDeploymentExist { get; private set; }
public bool HasCurrentStack => CurrentStackInfo.Details != null;
public DeploymentStackInfo CurrentStackInfo
{
get => _currentStackInfo;
private set
{
_currentStackInfo = value;
CurrentStackInfoChanged?.Invoke();
}
}
public bool IsDeploymentRunning { get; private set; }
public bool CanCancel => _deploymentWaiter.CanCancel == true;
public bool CanDeploy => !IsDeploymentRunning && IsBootstrapped && IsFormFilled && IsCurrentStackModifiable;
public bool IsCurrentStackModifiable =>
CurrentStackInfo.StackStatus == null || CurrentStackInfo.StackStatus.IsStackStatusModifiable();
public event Action CurrentStackInfoChanged;
internal DeploymentSettings(ScenarioLocator scenarioLocator, PathConverter pathConverter,
CoreApi coreApi, ScenarioParametersUpdater parametersUpdater, TextProvider textProvider, DeploymentWaiter deploymentWaiter, IDeploymentIdContainer currentDeploymentId, Delay delay, ILogger logger)
{
_scenarioLocator = scenarioLocator ?? throw new ArgumentNullException(nameof(scenarioLocator));
_pathConverter = pathConverter ?? throw new ArgumentNullException(nameof(pathConverter));
_coreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
_parametersUpdater = parametersUpdater ?? throw new ArgumentNullException(nameof(parametersUpdater));
_textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
_deploymentWaiter = deploymentWaiter ?? throw new ArgumentNullException(nameof(deploymentWaiter));
_currentDeploymentId = currentDeploymentId ?? throw new ArgumentNullException(nameof(currentDeploymentId));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
ClearCurrentStackInfo();
_delayedStackInfoRefresh = new DelayedOperation(RefreshCurrentStackInfo, delay, StackInfoRefreshDelayMs);
}
public async Task SetGameNameAsync(string value)
{
if (_gameName == value)
{
return;
}
_gameName = value;
ClearCurrentStackInfo();
await _delayedStackInfoRefresh.Request();
}
public void Refresh()
{
IEnumerable<DeployerBase> deployers = _scenarioLocator.GetScenarios();
_deployers.Clear();
_deployers.AddRange(deployers);
AllScenarios = _deployers.Select(deployer => deployer.DisplayName).ToArray();
GetSettingResponse bucketNameResponse = _coreApi.GetSetting(SettingsKeys.CurrentBucketName);
CurrentBucketName = bucketNameResponse.Success ? bucketNameResponse.Value : null;
GetSettingResponse currentRegionResponse = _coreApi.GetSetting(SettingsKeys.CurrentRegion);
CurrentRegion = currentRegionResponse.Success ? currentRegionResponse.Value : null;
HasCurrentBucket = !string.IsNullOrEmpty(CurrentBucketName) && _coreApi.IsValidRegion(CurrentRegion);
GetSettingResponse profileResponse = _coreApi.GetSetting(SettingsKeys.CurrentProfileName);
CurrentProfile = profileResponse.Success ? profileResponse.Value : null;
RefreshScenario();
}
public void RefreshCurrentStackInfo()
{
if (IsDeploymentRunning)
{
return;
}
if (string.IsNullOrEmpty(GameName))
{
ClearCurrentStackInfo();
return;
}
if (string.IsNullOrEmpty(CurrentProfile))
{
_logger.Log(string.Format(DevStrings.FailedToDescribeStackTemplate, DevStrings.ProfileInvalid), LogType.Warning);
ClearCurrentStackInfo();
return;
}
if (!_coreApi.IsValidRegion(CurrentRegion))
{
_logger.Log(string.Format(DevStrings.FailedToDescribeStackTemplate, DevStrings.RegionInvalid), LogType.Warning);
ClearCurrentStackInfo();
return;
}
string stackName = _coreApi.GetStackName(GameName);
DescribeStackResponse describeResponse = _coreApi.DescribeStack(CurrentProfile, CurrentRegion, stackName);
if (!describeResponse.Success)
{
ClearCurrentStackInfo();
return;
}
CurrentStackInfo = DeploymentStackInfoFactory.Create(_textProvider, describeResponse, CurrentRegion, ScenarioName);
}
public void Restore()
{
ScenarioIndex = 1; // Selects "Single-Region Fleet" Deployment Scenario by default
BuildFilePath = null;
BuildFolderPath = null;
GetSettingResponse response = _coreApi.GetSetting(SettingsKeys.DeploymentGameName);
GameName = response.Success ? response.Value : null;
GetSettingResponse scenarioIndexResponse = _coreApi.GetSetting(SettingsKeys.DeploymentScenarioIndex);
if (scenarioIndexResponse.Success)
{
int? index = SettingsFormatter.ParseInt(scenarioIndexResponse.Value);
ScenarioIndex = index ?? 0;
}
GetSettingResponse serverPathResponse = _coreApi.GetSetting(SettingsKeys.DeploymentBuildFolderPath);
if (serverPathResponse.Success)
{
BuildFolderPath = serverPathResponse.Value;
}
GetSettingResponse serverExePathResponse = _coreApi.GetSetting(SettingsKeys.DeploymentBuildFilePath);
if (serverExePathResponse.Success)
{
BuildFilePath = serverExePathResponse.Value;
}
}
public void Save()
{
_coreApi.PutSetting(SettingsKeys.DeploymentScenarioIndex, SettingsFormatter.FormatInt(ScenarioIndex));
_coreApi.PutSettingOrClear(SettingsKeys.DeploymentBuildFolderPath, BuildFolderPath);
_coreApi.PutSettingOrClear(SettingsKeys.DeploymentBuildFilePath, BuildFilePath);
_coreApi.PutSettingOrClear(SettingsKeys.DeploymentGameName, GameName);
}
public async Task WaitForCurrentDeployment()
{
if (IsDeploymentRunning || !_currentDeploymentId.HasValue)
{
return;
}
try
{
IsDeploymentRunning = true;
_delayedStackInfoRefresh.Cancel();
_deploymentWaiter.InfoUpdated += OnDeploymentWaiterInfoUpdated;
DeploymentResponse response = await _deploymentWaiter.WaitUntilDone(_currentDeploymentId.Get());
LogWaitResponse(response);
if (response.ErrorCode != ErrorCode.OperationCancelled)
{
_currentDeploymentId.Clear();
}
}
catch (Exception)
{
_currentDeploymentId.Clear();
CurrentStackInfo = new DeploymentStackInfo(_textProvider.Get(Strings.StatusExceptionThrown));
throw;
}
finally
{
IsDeploymentRunning = false;
_deploymentWaiter.InfoUpdated -= OnDeploymentWaiterInfoUpdated;
}
}
private void LogWaitResponse(DeploymentResponse response)
{
if (response.Success || response.ErrorCode == ErrorCode.OperationCancelled)
{
return;
}
if (response.ErrorCode == ErrorCode.StackStatusInvalid
|| response.ErrorCode == CoreErrorCode.StackDoesNotExist)
{
_logger.LogResponseError(response, LogType.Log);
}
else
{
_logger.LogResponseError(response);
}
}
public void CancelWaitingForDeployment()
{
_deploymentWaiter.CancelWaiting();
}
public void CancelDeployment()
{
if (!CanCancel)
{
_logger.Log(DevStrings.OperationInvalid, LogType.Warning);
return;
}
Response response = _deploymentWaiter.CancelDeployment();
if (response.Success)
{
RefreshCurrentStackInfo();
}
else
{
_logger.LogResponseError(response);
}
}
public async Task StartDeployment(ConfirmChangesDelegate confirmChanges)
{
if (confirmChanges is null)
{
throw new ArgumentNullException(nameof(confirmChanges));
}
if (!IsFormFilled)
{
return;
}
string exeFilePath = null;
DeployerBase currentDeployer = _deployers[ScenarioIndex];
if (currentDeployer.HasGameServer)
{
exeFilePath = GetExeFilePathInBuildOrNull();
if (exeFilePath == null)
{
_status.IsDisplayed = true;
_status.SetMessage(_textProvider.Get(Strings.StatusDeploymentExePathInvalid), MessageType.Error);
return;
}
}
if (IsDeploymentRunning)
{
return;
}
IsDeploymentRunning = true;
_delayedStackInfoRefresh.Cancel();
string parametersPath = _pathConverter.GetParametersFilePath(ScenarioPath);
IReadOnlyDictionary<string, string> parameters = currentDeployer.HasGameServer
? PrepareParameters(exeFilePath)
: PrepareGameParameter();
_parametersUpdater.Update(parametersPath, parameters);
CurrentStackInfo = new DeploymentStackInfo(_textProvider.Get(Strings.StatusDeploymentStarting));
string stackName = _coreApi.GetStackName(GameName);
var deploymentId = new DeploymentId(CurrentProfile, CurrentRegion, stackName, currentDeployer.DisplayName);
_currentDeploymentId.Set(deploymentId);
try
{
DeploymentResponse response = await currentDeployer.StartDeployment(ScenarioPath, BuildFolderPath, GameName,
isDevelopmentBuild: EditorUserBuildSettings.development, confirmChanges);
if (!response.Success)
{
if (response.ErrorCode != ErrorCode.OperationCancelled)
{
_logger.LogResponseError(response);
string messageTemplate = _textProvider.Get(Strings.StatusDeploymentFailure);
string message = string.Format(messageTemplate, _textProvider.GetError(response.ErrorCode));
_status.SetMessage(message, MessageType.Error);
_status.IsDisplayed = true;
}
return;
}
_deploymentWaiter.InfoUpdated += OnDeploymentWaiterInfoUpdated;
response = await _deploymentWaiter.WaitUntilDone(deploymentId);
LogWaitResponse(response);
if (response.ErrorCode != ErrorCode.OperationCancelled)
{
_currentDeploymentId.Clear();
}
}
catch (Exception ex)
{
_currentDeploymentId.Clear();
_logger.LogException(ex);
string messageTemplate = _textProvider.Get(Strings.StatusDeploymentFailure);
string message = string.Format(messageTemplate, ex.Message);
_status.SetMessage(message, MessageType.Error);
_status.IsDisplayed = true;
throw;
}
finally
{
IsDeploymentRunning = false;
_deploymentWaiter.InfoUpdated -= OnDeploymentWaiterInfoUpdated;
RefreshCurrentStackInfo();
}
}
private void OnDeploymentWaiterInfoUpdated(DeploymentInfo info)
{
CurrentStackInfo = DeploymentStackInfoFactory.Create(_textProvider, info);
}
private IReadOnlyDictionary<string, string> PrepareGameParameter()
{
return new Dictionary<string, string>
{
{ ScenarioParameterKeys.GameName, GameName }
};
}
private IReadOnlyDictionary<string, string> PrepareParameters(string exeFilePathInBuild)
{
string launchPath = _coreApi.GetServerGamePath(exeFilePathInBuild);
return new Dictionary<string, string>
{
{ ScenarioParameterKeys.GameName, GameName },
{ ScenarioParameterKeys.LaunchPath, launchPath },
};
}
private string GetExeFilePathInBuildOrNull()
{
int index = BuildFilePath.IndexOf(BuildFolderPath);
if (index < 0)
{
return null;
}
return BuildFilePath.Remove(0, BuildFolderPath.Length).TrimStart('\\', '/');
}
private void RefreshScenario()
{
if (!IsValidScenarioIndex)
{
return;
}
DeployerBase deployer = _deployers[ScenarioIndex];
ScenarioName = deployer.DisplayName;
ScenarioDescription = deployer.Description;
ScenarioHelpUrl = deployer.HelpUrl;
ScenarioPath = _pathConverter.GetScenarioAbsolutePath(deployer.ScenarioFolder);
if (!deployer.HasGameServer)
{
BuildFolderPath = null;
BuildFilePath = null;
}
RefreshCurrentStackInfo();
}
private void ClearCurrentStackInfo()
{
CurrentStackInfo = new DeploymentStackInfo(_textProvider.Get(Strings.StatusNothingDeployed));
}
}
}
| 487 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal class DeploymentSettingsFactory
{
public static DeploymentSettings Create()
{
var parametersUpdater = new ScenarioParametersUpdater(CoreApi.SharedInstance, () => new ScenarioParametersEditor());
TextProvider textProvider = TextProviderFactory.Create();
UnityLogger logger = UnityLoggerFactory.Create(textProvider);
return new DeploymentSettings(ScenarioLocator.SharedInstance, PathConverter.SharedInstance,
CoreApi.SharedInstance, parametersUpdater, textProvider,
new DeploymentWaiter(), DeploymentIdContainerFactory.Create(), new Delay(), logger);
}
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
namespace AmazonGameLift.Editor
{
internal readonly struct DeploymentStackInfo : IEquatable<DeploymentStackInfo>
{
public string Details { get; }
public string Status { get; }
public string StackStatus { get; }
public string ApiGatewayEndpoint { get; }
public string UserPoolClientId { get; }
public DeploymentStackInfo(string formatterdStatus, string stackStatus = null, string details = null, string apiGatewayEndpoint = null, string userPoolClientId = null)
{
Status = formatterdStatus ?? throw new ArgumentNullException(nameof(formatterdStatus));
StackStatus = stackStatus;
Details = details;
ApiGatewayEndpoint = apiGatewayEndpoint;
UserPoolClientId = userPoolClientId;
}
public override bool Equals(object obj)
{
return obj is DeploymentStackInfo info && Equals(info);
}
public bool Equals(DeploymentStackInfo other)
{
return Details == other.Details
&& Status == other.Status
&& ApiGatewayEndpoint == other.ApiGatewayEndpoint
&& UserPoolClientId == other.UserPoolClientId;
}
public override int GetHashCode()
{
EqualityComparer<string> comparer = EqualityComparer<string>.Default;
int hashCode = 85359248;
const int c = -1521134295;
hashCode = hashCode * c + comparer.GetHashCode(Details);
hashCode = hashCode * c + comparer.GetHashCode(Status);
hashCode = hashCode * c + comparer.GetHashCode(ApiGatewayEndpoint);
hashCode = hashCode * c + comparer.GetHashCode(UserPoolClientId);
return hashCode;
}
}
}
| 52 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
namespace AmazonGameLift.Editor
{
internal static class DeploymentStackInfoFactory
{
public static DeploymentStackInfo Create(TextProvider textProvider,
DescribeStackResponse describeResponse, string currentRegion, string scenarioName)
{
string updateTime = FormatTime(describeResponse.LastUpdatedTime);
string statusFormat = textProvider.Get(Strings.StackStatusTemplate);
string status = string.Format(statusFormat, describeResponse.StackStatus);
string detailsFormat = textProvider.Get(Strings.StackDetailsTemplate);
string details = string.Format(detailsFormat, currentRegion, scenarioName, describeResponse.GameName, updateTime);
describeResponse.Outputs.TryGetValue(StackOutputKeys.ApiGatewayEndpoint, out string apiGatewayEndpoint);
describeResponse.Outputs.TryGetValue(StackOutputKeys.UserPoolClientId, out string userPoolClientId);
return new DeploymentStackInfo(status, describeResponse.StackStatus, details, apiGatewayEndpoint, userPoolClientId);
}
public static DeploymentStackInfo Create(TextProvider textProvider, DeploymentInfo info)
{
string updateTime = FormatTime(info.LastUpdatedTime);
string statusFormat = textProvider.Get(Strings.StackStatusTemplate);
string status = string.Format(statusFormat, info.StackStatus);
string detailsFormat = textProvider.Get(Strings.StackDetailsTemplate);
string details = string.Format(detailsFormat, info.Region, info.ScenarioDisplayName, info.GameName, updateTime);
info.Outputs.TryGetValue(StackOutputKeys.ApiGatewayEndpoint, out string apiGatewayEndpoint);
info.Outputs.TryGetValue(StackOutputKeys.UserPoolClientId, out string userPoolClientId);
return new DeploymentStackInfo(status, info.StackStatus, details, apiGatewayEndpoint, userPoolClientId);
}
private static string FormatTime(DateTime time)
{
return time != default
? time.ToString("yyyy-MM-dd hh:mm tt")
: "-";
}
}
}
| 46 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class DeploymentWindow : EditorWindow
{
private const float WindowWidthPixels = 600f;
#if UNITY_2019_1_OR_NEWER
private const float WindowIdleHeightNoFormPixels = 375f;
#else
private const float WindowIdleHeightNoFormPixels = 350f;
#endif
private const float TopMarginPixels = 18f;
private const float LeftMarginPixels = 15f;
private const float RightMarginPixels = 13f;
private const float LabelWidthPixels = 185f;
private const float VerticalSpacingPixels = 5f;
private const float SpinnerSizePixels = 23f;
private HyperLinkButton _cfnConsoleLinkButton;
private HyperLinkButton _deploymentHelpLinkButton;
private HyperLinkButton _scenarioHelpLinkButton;
private StatusLabel _statusLabel;
private DeploymentSettings _model;
private int _previousScenarioIndex = -1;
private bool? _previousBootstrapped;
private float _bootstrapWarningHeight;
private float _scenarioHeight;
private bool _isSizeDirty;
private TextProvider _textProvider;
private string _labelSelectionMode;
private string _labelCurrentStack;
private string _labelGameName;
private string _labelBuildFolderPath;
private string _labelBuildFilePath;
private string _labelRegion;
private string _tooltipRegion;
private string _labelBucket;
private string _tooltipBucket;
private string _labelScenarioHelp;
private string _labelStartButton;
private string _labelCancelButton;
private string _labelDefaultFolderName;
private string _labelApiGateway;
private string _labelCognitoClientId;
private string _labelDeploymentCosts;
private string _labelBootstrapWarning;
private string _titleServerFileDialog;
private string _titleServerFolderDialog;
private StackUpdateModelFactory _stackUpdateModelFactory;
private ImageSequenceDrawer _spinnerDrawer;
private ControlDrawer _controlDrawer;
private string _labelScenarioPath;
private bool IsFormDisabled => _model == null || _model.IsDeploymentRunning;
private void SetUp()
{
_stackUpdateModelFactory = new StackUpdateModelFactory(new ChangeSetUrlFormatter());
_textProvider = TextProviderFactory.Create();
_labelSelectionMode = _textProvider.Get(Strings.LabelDeploymentSelectionMode);
_labelCurrentStack = _textProvider.Get(Strings.LabelDeploymentCurrentStack);
_labelGameName = _textProvider.Get(Strings.LabelDeploymentGameName);
_labelBuildFilePath = _textProvider.Get(Strings.LabelDeploymentBuildFilePath);
_labelBuildFolderPath = _textProvider.Get(Strings.LabelDeploymentBuildFolderPath);
_labelRegion = _textProvider.Get(Strings.LabelDeploymentRegion);
_tooltipRegion = _textProvider.Get(Strings.TooltipDeploymentRegion);
_labelBucket = _textProvider.Get(Strings.LabelDeploymentBucket);
_tooltipBucket = _textProvider.Get(Strings.TooltipDeploymentBucket);
_labelScenarioPath = _textProvider.Get(Strings.LabelDeploymentScenarioPath);
_labelScenarioHelp = _textProvider.Get(Strings.LabelDeploymentScenarioHelp);
_labelStartButton = _textProvider.Get(Strings.LabelDeploymentStartButton);
_labelCancelButton = _textProvider.Get(Strings.LabelDeploymentCancelButton);
_labelDefaultFolderName = _textProvider.Get(Strings.LabelDefaultFolderName);
_labelApiGateway = _textProvider.Get(Strings.LabelDeploymentApiGateway);
_labelCognitoClientId = _textProvider.Get(Strings.LabelDeploymentCognitoClientId);
_labelDeploymentCosts = _textProvider.Get(Strings.LabelDeploymentCosts);
_labelBootstrapWarning = _textProvider.Get(Strings.LabelDeploymentBootstrapWarning);
_titleServerFileDialog = _textProvider.Get(Strings.TitleDeploymentServerFileDialog);
_titleServerFolderDialog = _textProvider.Get(Strings.TitleDeploymentServerFolderDialog);
titleContent = new GUIContent(_textProvider.Get(Strings.TitleDeployment));
_model = DeploymentSettingsFactory.Create();
string deploymentHelpLabelText = _textProvider.Get(Strings.LabelDeploymentHelp);
_deploymentHelpLinkButton = new HyperLinkButton(deploymentHelpLabelText, Urls.AwsHelpDeployment, ResourceUtility.GetHyperLinkStyle());
_scenarioHelpLinkButton = new HyperLinkButton(_labelScenarioHelp, string.Empty, ResourceUtility.GetHyperLinkStyle());
_statusLabel = new StatusLabel();
string goToCloudFormationConsoleLabelText = _textProvider.Get(Strings.LabelDeploymentCloudFormationConsole);
_cfnConsoleLinkButton = new HyperLinkButton(goToCloudFormationConsoleLabelText, Urls.AwsCloudFormationConsole, ResourceUtility.GetHyperLinkStyle());
SetWindowSize(WindowIdleHeightNoFormPixels);
_model.Refresh();
_model.Restore();
_spinnerDrawer = SpinnerDrawerFactory.Create(size: SpinnerSizePixels);
_controlDrawer = ControlDrawerFactory.Create();
_ = _model.WaitForCurrentDeployment();
}
private void OnEnable()
{
SetUp();
_model.CurrentStackInfoChanged += OnCurrentStackInfoChanged;
_model.Status.Changed += OnStatusChanged;
Settings.SharedInstance.AnySettingChanged += OnAnySettingChanged;
}
private void OnDisable()
{
Settings.SharedInstance.AnySettingChanged -= OnAnySettingChanged;
_model.Save();
_model.CancelWaitingForDeployment();
_model.Status.Changed -= OnStatusChanged;
_model.CurrentStackInfoChanged -= OnCurrentStackInfoChanged;
}
private void OnInspectorUpdate()
{
if (_spinnerDrawer.IsRunning)
{
Repaint();
}
}
private void OnGUI()
{
EditorGUIUtility.labelWidth = LabelWidthPixels;
float scenarioHeight;
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(LeftMarginPixels);
using (new EditorGUILayout.VerticalScope())
{
GUILayout.Space(TopMarginPixels);
EditorGUILayout.HelpBox(_labelDeploymentCosts, MessageType.Warning);
if (!_model.IsBootstrapped)
{
EditorGUILayout.HelpBox(_labelBootstrapWarning, MessageType.Warning);
}
GUILayout.Space(VerticalSpacingPixels);
using (new EditorGUI.DisabledScope(IsFormDisabled))
{
scenarioHeight = DrawScenarioSelection();
DrawSeparator();
scenarioHeight += DrawScenarioForm();
}
using (new EditorGUI.DisabledScope(false))
{
DrawSeparator();
GUILayout.Label(_labelCurrentStack);
GUILayout.Space(VerticalSpacingPixels);
using (new EditorGUILayout.HorizontalScope())
{
DrawInfo(_model.CurrentStackInfo.Status);
if (_model.IsDeploymentRunning)
{
_spinnerDrawer.Draw();
}
}
if (_model.IsDeploymentRunning)
{
GUILayout.Space(EditorGUIUtility.singleLineHeight - SpinnerSizePixels);
}
GUILayout.Space(VerticalSpacingPixels);
DrawInfo(_model.CurrentStackInfo.Details, GUILayout.Height(55));
DrawStackOutput(_labelCognitoClientId, _model.CurrentStackInfo.UserPoolClientId);
DrawStackOutput(_labelApiGateway, _model.CurrentStackInfo.ApiGatewayEndpoint);
GUILayout.Space(VerticalSpacingPixels);
DrawLink(_model.HasCurrentStack ? _cfnConsoleLinkButton : _deploymentHelpLinkButton);
GUILayout.Space(VerticalSpacingPixels);
DrawButtons();
if (_model.Status.IsDisplayed)
{
_statusLabel.Draw(_model.Status.Message, _model.Status.Type);
}
}
}
GUILayout.Space(RightMarginPixels);
}
UpdateWindowSize(scenarioHeight);
UpdateSpinnerDrawer();
}
private void UpdateSpinnerDrawer()
{
if (_model.IsDeploymentRunning)
{
_spinnerDrawer.Start();
}
else
{
_spinnerDrawer.Stop();
}
}
private void DrawStackOutput(string label, string output)
{
if (output != null)
{
_controlDrawer.DrawReadOnlyText(label, output);
}
else
{
GUILayout.Space(.5f * VerticalSpacingPixels);
GUILayout.Space(EditorGUIUtility.singleLineHeight);
}
}
private float DrawScenarioForm()
{
_model.GameName = DrawTextField(_labelGameName, _model.GameName);
using (new EditorGUI.DisabledScope(!_model.IsBuildRequired))
{
_model.BuildFolderPath = _controlDrawer.DrawFolderPathField(_labelBuildFolderPath,
_model.BuildFolderPath, _labelDefaultFolderName, _titleServerFolderDialog);
_model.BuildFilePath = _controlDrawer.DrawFilePathField(_labelBuildFilePath, _model.BuildFilePath, "", _titleServerFileDialog);
}
GUILayout.Space(VerticalSpacingPixels);
_controlDrawer.DrawReadOnlyText(_labelRegion, _model.CurrentRegion, _tooltipRegion);
_controlDrawer.DrawReadOnlyText(_labelBucket, _model.CurrentBucketName, _tooltipBucket);
const int fieldCount = 4;
return fieldCount * (VerticalSpacingPixels + EditorGUIUtility.singleLineHeight);
}
private void UpdateWindowSize(float scenarioHeight)
{
if (Event.current.type == EventType.Repaint)
{
UpdateIfScenarioChanged(scenarioHeight);
UpdateIfBootstrapStateChanged();
}
if (_isSizeDirty)
{
_isSizeDirty = false;
SetWindowSize(WindowIdleHeightNoFormPixels + _scenarioHeight + _bootstrapWarningHeight);
}
}
private void UpdateIfScenarioChanged(float scenarioHeight)
{
if (_model.ScenarioIndex == _previousScenarioIndex)
{
return;
}
_previousScenarioIndex = _model.ScenarioIndex;
_scenarioHeight = scenarioHeight;
_isSizeDirty = true;
_scenarioHelpLinkButton = new HyperLinkButton(_labelScenarioHelp, _model.ScenarioHelpUrl,
ResourceUtility.GetHyperLinkStyle());
}
private void UpdateIfBootstrapStateChanged()
{
if (_model.IsBootstrapped == _previousBootstrapped)
{
return;
}
_previousBootstrapped = _model.IsBootstrapped;
_bootstrapWarningHeight = _model.IsBootstrapped ? 0f : 40f;
_isSizeDirty = true;
}
#region Form controls
private float DrawScenarioSelection()
{
_model.ScenarioIndex = EditorGUILayout.Popup(_labelSelectionMode, _model.ScenarioIndex, _model.AllScenarios);
GUILayout.Space(VerticalSpacingPixels);
float pathHeight = _controlDrawer.DrawReadOnlyTextWrapped(_labelScenarioPath, _model.ScenarioPath);
GUILayout.Space(2 * VerticalSpacingPixels);
Rect descriptionRect = DrawInfo(_model.ScenarioDescription);
float height = 2 * VerticalSpacingPixels + descriptionRect.height + pathHeight - EditorGUIUtility.singleLineHeight;
if (!string.IsNullOrEmpty(_model.ScenarioHelpUrl))
{
GUILayout.Space(VerticalSpacingPixels);
DrawLink(_scenarioHelpLinkButton);
height += VerticalSpacingPixels + EditorGUIUtility.singleLineHeight;
}
return height;
}
private void DrawButtons()
{
using (new EditorGUILayout.HorizontalScope())
{
bool disabled = !_model.CanCancel;
using (new EditorGUI.DisabledScope(disabled))
{
if (GUILayout.Button(_labelCancelButton) && ConfirmCancel())
{
_model.CancelDeployment();
}
}
using (new EditorGUI.DisabledScope(!_model.CanDeploy))
{
if (GUILayout.Button(_labelStartButton))
{
_model.StartDeployment(ConfirmChangeSet)
.ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.LogException(task.Exception);
}
});
}
}
}
}
#endregion
private bool ConfirmCancel()
{
return EditorUtility.DisplayDialog(_textProvider.Get(Strings.TitleDeploymentCancelDialog),
_textProvider.Get(Strings.LabelDeploymentCancelDialogBody),
_textProvider.Get(Strings.LabelDeploymentCancelDialogOkButton),
_textProvider.Get(Strings.LabelDeploymentCancelDialogCancelButton));
}
private Rect DrawInfo(string text, params GUILayoutOption[] options)
{
var scope = new EditorGUILayout.HorizontalScope(options);
using (scope)
{
GUILayout.Space(5f);
EditorGUILayout.LabelField(text, ResourceUtility.GetInfoLabelStyle());
}
return scope.rect;
}
private void DrawLink(HyperLinkButton linkButton)
{
using (new EditorGUI.DisabledScope(false))
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5f);
linkButton.Draw();
}
}
}
private string DrawTextField(string label, string value)
{
return EditorGUILayout.TextField(label, value);
}
private void DrawSeparator()
{
EditorGUILayout.LabelField(string.Empty, GUI.skin.horizontalSlider);
}
private void SetWindowSize(float height)
{
this.SetConstantSize(new Vector2(x: WindowWidthPixels, y: height));
}
private Task<bool> ConfirmChangeSet(ConfirmChangesRequest request)
{
StackUpdateDialog dialog = GetWindow<StackUpdateDialog>();
return dialog.SetUp(_stackUpdateModelFactory.Create(request));
}
private void OnCurrentStackInfoChanged()
{
Repaint();
}
private void OnStatusChanged()
{
Repaint();
}
private void OnAnySettingChanged()
{
_model.Refresh();
Repaint();
}
}
}
| 410 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace AmazonGameLift.Editor
{
internal interface IDeploymentIdContainer
{
bool HasValue { get; }
DeploymentId Get();
void Set(DeploymentId value);
void Clear();
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.IO;
namespace AmazonGameLift.Editor
{
internal class PathConverter
{
private readonly CoreApi _coreApi;
public static PathConverter SharedInstance { get; } = new PathConverter(CoreApi.SharedInstance);
public PathConverter(CoreApi coreApi) =>
_coreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
/// <summary>Returns the absolute scenario folder path, if the plugin is located under 'Assets' or 'Packages'.</summary>
/// <exception cref="ArgumentException">If <paramref name="scenarioFolderName"/> is null or empty.</exception>
public virtual string GetScenarioAbsolutePath(string scenarioFolderName)
{
if (string.IsNullOrEmpty(scenarioFolderName))
{
throw new ArgumentException(DevStrings.StringNullOrEmpty, nameof(scenarioFolderName));
}
if (scenarioFolderName.StartsWith("Assets/"))
{
return Path.GetFullPath(scenarioFolderName);
}
string parametersInternalPath = $"{Paths.PackageName}/{Paths.ScenariosRootInPackage}/{scenarioFolderName}/{Paths.ParametersFileName}";
string parametersAssetPath = $"Assets/{parametersInternalPath}";
string parametersPath = Path.GetFullPath(parametersAssetPath);
if (!_coreApi.FileExists(parametersPath))
{
string parametersPackagePath = $"Packages/{parametersInternalPath}";
parametersPath = Path.GetFullPath(parametersPackagePath);
}
return Path.GetDirectoryName(parametersPath);
}
/// <exception cref="ArgumentException">If <paramref name="scenarioAssetFolderPath"/> is null or empty.</exception>
public virtual string GetCustomScenarioAbsolutePath(string scenarioAssetFolderPath)
{
if (string.IsNullOrEmpty(scenarioAssetFolderPath))
{
throw new ArgumentException(DevStrings.StringNullOrEmpty, nameof(scenarioAssetFolderPath));
}
string parametersAssetPath = $"{scenarioAssetFolderPath}/{Paths.ParametersFileName}";
string parametersPath = Path.GetFullPath(parametersAssetPath);
return Path.GetDirectoryName(parametersPath);
}
/// <exception cref="ArgumentException">If <paramref name="scenarioFolderPath"/> is null or empty.</exception>
public virtual string GetParametersFilePath(string scenarioFolderPath)
{
if (string.IsNullOrEmpty(scenarioFolderPath))
{
throw new ArgumentException(DevStrings.StringNullOrEmpty, nameof(scenarioFolderPath));
}
return Path.Combine(scenarioFolderPath, Paths.ParametersFileName);
}
}
}
| 70 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
namespace AmazonGameLift.Editor
{
/// <summary>
/// Locates the sceanrio deploymemt types and creates their instances.
/// </summary>
internal class ScenarioLocator
{
public static ScenarioLocator SharedInstance { get; } = new ScenarioLocator();
internal ScenarioLocator()
{
}
public virtual IEnumerable<DeployerBase> GetScenarios()
{
IEnumerable<Type> deployerTypes = AppDomain.CurrentDomain.GetAssemblies()
.Select(assembly => assembly.GetTypes().FirstOrDefault(IsNonProxyDelpoyerType))
.OfType<Type>();
DeployerBase[] deployers = deployerTypes
.Select(deployerType => (DeployerBase)Activator.CreateInstance(deployerType))
.ToArray();
Array.Sort(deployers, (item1, item2) => item1.PreferredUiOrder.CompareTo(item2.PreferredUiOrder));
return deployers;
}
// <class-name>Proxy is the pattern for dynamic mocked type
private static bool IsNonProxyDelpoyerType(Type type)
{
return type.IsPublic && type.IsSubclassOf(typeof(DeployerBase)) && !type.Name.EndsWith("Proxy");
}
}
}
| 42 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLift.Editor
{
internal class ScenarioParametersUpdater
{
private readonly CoreApi _coreApi;
private readonly Func<ScenarioParametersEditor> _editorFactory;
public ScenarioParametersUpdater(CoreApi coreApi, Func<ScenarioParametersEditor> editorFactory)
{
_coreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
_editorFactory = editorFactory ?? throw new ArgumentNullException(nameof(editorFactory));
}
/// <summary>
/// Possible errors: <see cref="ErrorCode.InvalidParameters"/> if <see cref="parameters"/> is null or empty,
/// and the errors from <see cref="ScenarioParametersEditor"/>.
/// </summary>
/// <exception cref="ArgumentNullException">For any parameter.</exception>
public virtual Response Update(string parametersFilePath, IReadOnlyDictionary<string, string> parameters)
{
if (parametersFilePath is null)
{
throw new ArgumentNullException(nameof(parametersFilePath));
}
if (parameters is null)
{
throw new ArgumentNullException(nameof(parameters));
}
FileReadAllTextResponse fileReadResponse = _coreApi.FileReadAllText(parametersFilePath);
if (!fileReadResponse.Success)
{
return fileReadResponse;
}
ScenarioParametersEditor parameterEditor = _editorFactory.Invoke();
Response readResponse = parameterEditor.ReadParameters(fileReadResponse.Text);
if (!readResponse.Success)
{
return readResponse;
}
foreach (KeyValuePair<string, string> pair in parameters)
{
Response setParameterResponse = parameterEditor.SetParameter(pair.Key, pair.Value);
if (!setParameterResponse.Success)
{
return setParameterResponse;
}
}
SaveParametersResponse saveResponse = parameterEditor.SaveParameters();
if (!saveResponse.Success)
{
return saveResponse;
}
Response fileWriteResponse = _coreApi.FileWriteAllText(parametersFilePath, saveResponse.SerializedParameters);
if (!fileWriteResponse.Success)
{
return fileWriteResponse;
}
return Response.Ok(new Response());
}
}
}
| 81 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal sealed class StackUpdateDialog : Dialog
{
private const float ScrollViewHeight = 100f;
private const float VerticalSpacingPixels = 5f;
private HyperLinkButton _helpLinkButton;
private Vector2 _scrollPosition;
private StackUpdateModel _model;
private string[] _changes;
private string[] _changeCount;
private string _labelQuestion;
private string _labelRemovalHeader;
private string _labelConsoleWarning;
protected override bool IsModal { get; } = true;
protected override float WindowWidthPixels { get; } = 450f;
protected override string TitleKey => Strings.TitleStackUpdateDialog;
public Task<bool> SetUp(StackUpdateModel model)
{
_model = model ?? throw new ArgumentNullException(nameof(model));
_changes = model.RemovalChanges
.Select(FormatChange)
.ToArray();
_changeCount = model.ChangesByAction
.Select(FormatChangeCount)
.ToArray();
_helpLinkButton.Url = _model.CloudFormationUrl;
var completionSource = new TaskCompletionSource<bool>();
AddAction(new DialogAction(Strings.LabelStackUpdateCancelButton, () => completionSource.TrySetResult(false)));
AddAction(new DialogAction(Strings.LabelStackUpdateConfirmButton, () => completionSource.TrySetResult(true)));
DefaultAction = () => completionSource.TrySetResult(false);
return completionSource.Task;
}
private string FormatChangeCount(KeyValuePair<string, Change[]> group)
{
string format = TextProvider.Get(Strings.LabelStackUpdateCountTemplate);
return string.Format(format, group.Key, group.Value.Count());
}
protected override void SetUpContents()
{
titleContent = new GUIContent(TextProvider.Get(Strings.TitleStackUpdateDialog));
_helpLinkButton = new HyperLinkButton(TextProvider.Get(Strings.LabelStackUpdateConsole),
"", ResourceUtility.GetHyperLinkStyle());
_labelQuestion = TextProvider.Get(Strings.LabelStackUpdateQuestion);
_labelRemovalHeader = TextProvider.Get(Strings.LabelStackUpdateRemovalHeader);
_labelConsoleWarning = TextProvider.Get(Strings.LabelStackUpdateConsoleWarning);
}
protected override Rect DrawContents()
{
if (_model == null)
{
return new Rect();
}
using (var mainScope = new EditorGUILayout.VerticalScope())
{
GUILayout.Label(_labelQuestion);
if (_model.HasRemovalChanges)
{
GUILayout.Space(2 * VerticalSpacingPixels);
GUILayout.Label(_labelRemovalHeader);
GUILayout.Space(2 * VerticalSpacingPixels);
using (var scope = new EditorGUILayout.ScrollViewScope(_scrollPosition, GUILayout.Height(ScrollViewHeight)))
{
_scrollPosition = scope.scrollPosition;
foreach (string item in _changes)
{
GUILayout.Label(item);
}
}
}
GUILayout.Space(3 * VerticalSpacingPixels);
foreach (string item in _changeCount)
{
GUILayout.Label(item);
}
GUILayout.Space(3 * VerticalSpacingPixels);
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5f);
_helpLinkButton.Draw();
}
GUILayout.Space(VerticalSpacingPixels);
EditorGUILayout.HelpBox(_labelConsoleWarning, MessageType.Warning);
GUILayout.Space(VerticalSpacingPixels);
return mainScope.rect;
}
}
private static string FormatChange(Change change)
{
return $"{change.LogicalId} ({change.ResourceType})";
}
}
}
| 125 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
namespace AmazonGameLift.Editor
{
internal sealed class StackUpdateModel
{
private const string RemoveChangeAction = "Remove";
public IReadOnlyDictionary<string, Change[]> ChangesByAction { get; }
public IEnumerable<Change> RemovalChanges { get; }
public bool HasRemovalChanges { get; }
public string CloudFormationUrl { get; internal set; }
/// <exception cref="ArgumentNullException"></exception>
public StackUpdateModel(ConfirmChangesRequest request, string cloudFormationUrl)
{
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
ChangesByAction = request.Changes
.GroupBy(change => change.Action)
.ToDictionary(change => change.Key, group => group.ToArray());
RemovalChanges = request.Changes
.Where(change => change.Action == RemoveChangeAction)
.ToArray();
HasRemovalChanges = RemovalChanges.Any();
CloudFormationUrl = cloudFormationUrl ?? throw new ArgumentNullException(nameof(cloudFormationUrl));
}
}
}
| 43 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
namespace AmazonGameLift.Editor
{
internal sealed class StackUpdateModelFactory
{
private readonly ChangeSetUrlFormatter _urlFormatter;
/// <exception cref="ArgumentNullException"></exception>
public StackUpdateModelFactory(ChangeSetUrlFormatter urlFormatter) =>
_urlFormatter = urlFormatter ?? throw new ArgumentNullException(nameof(urlFormatter));
/// <exception cref="ArgumentNullException"></exception>
public StackUpdateModel Create(ConfirmChangesRequest request)
{
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
string url = _urlFormatter.Format(request);
return new StackUpdateModel(request, url);
}
}
}
| 29 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
/// <summary>
/// A view model for <see cref="LocalTestWindow"/>.
/// </summary>
[Serializable]
internal class LocalTest
{
private const int GameLiftLocalReadinessDelayMs = 10000;
private const int MinPort = 1;
private const int MaxPort = 65535;
private CoreApi _coreApi;
private TextProvider _textProvider;
private Delay _delay;
private ILogger _logger;
[SerializeField]
private Status _status = new Status();
private int _glProcessId;
private int _serverProcessId;
private int _gameLiftLocalPort = 8080;
public IReadStatus Status => _status;
public bool IsDeploymentRunning { get; private set; }
public string GameLiftLocalPath { get; private set; }
public bool IsBuildExecutablePathFilled =>
OperatingSystemUtility.isMacOs() ? _coreApi.FolderExists(BuildExecutablePath) : _coreApi.FileExists(BuildExecutablePath);
public bool isGameLiftLocalPortValid => GameLiftLocalPort > 0;
public bool IsBootstrapped =>
GameLiftLocalPath != null && _coreApi.FileExists(GameLiftLocalPath);
public bool CanStart => !IsDeploymentRunning && IsBootstrapped && isGameLiftLocalPortValid && IsBuildExecutablePathFilled;
public bool CanStop => IsDeploymentRunning;
public string BuildExecutablePath { get; set; }
public int GameLiftLocalPort
{
get => _gameLiftLocalPort;
set => _gameLiftLocalPort = Mathf.Min(Mathf.Max(MinPort, value), MaxPort);
}
public LocalTest(CoreApi coreApi, TextProvider textProvider, Delay delay, ILogger logger) => Restore(coreApi, textProvider, delay, logger);
internal void Restore(CoreApi coreApi, TextProvider textProvider, Delay delay, ILogger logger)
{
_coreApi = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
_textProvider = textProvider ?? throw new ArgumentNullException(nameof(textProvider));
_delay = delay ?? throw new ArgumentNullException(nameof(delay));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public void Refresh()
{
GetSettingResponse response = _coreApi.GetSetting(SettingsKeys.GameLiftLocalPath);
GameLiftLocalPath = (response.Success && _coreApi.FileExists(response.Value)) ? response.Value : null;
GetSettingResponse portResponse = _coreApi.GetSetting(SettingsKeys.GameLiftLocalPort);
if (portResponse.Success)
{
int? port = SettingsFormatter.ParseInt(portResponse.Value);
GameLiftLocalPort = port.HasValue ? port.Value : GameLiftLocalPort;
}
GetSettingResponse serverPathResponse = _coreApi.GetSetting(SettingsKeys.LocalServerPath);
if (serverPathResponse.Success)
{
BuildExecutablePath = serverPathResponse.Value;
}
}
public void Save()
{
_coreApi.PutSettingOrClear(SettingsKeys.LocalServerPath, BuildExecutablePath);
_coreApi.PutSetting(SettingsKeys.GameLiftLocalPort, SettingsFormatter.FormatInt(GameLiftLocalPort));
}
public void Stop()
{
if (!CanStop)
{
return;
}
LocalOperatingSystem localOperatingSystem = OperatingSystemUtility.GetLocalOperatingSystem();
_coreApi.StopProcess(_glProcessId, localOperatingSystem);
_coreApi.StopProcess(_serverProcessId, localOperatingSystem);
IsDeploymentRunning = false;
_status.IsDisplayed = false;
}
public async Task Start(CancellationToken cancellationToken = default)
{
if (!CanStart)
{
return;
}
Debug.Log("Running GameLift Local...");
LocalOperatingSystem localOperatingSystem = OperatingSystemUtility.GetLocalOperatingSystem();
StartResponse response = _coreApi.StartGameLiftLocal(GameLiftLocalPath, GameLiftLocalPort, localOperatingSystem);
if (!response.Success)
{
Debug.LogError("Error occurred when running GameLift Local...");
_status.IsDisplayed = true;
string message = string.Format(_textProvider.Get(Strings.StatusLocalTestErrorTemplate), _textProvider.GetError(response.ErrorCode));
_status.SetMessage(message, MessageType.Error);
_logger.LogResponseError(response);
return;
}
IsDeploymentRunning = true;
_glProcessId = response.ProcessId;
await _delay.Wait(GameLiftLocalReadinessDelayMs, cancellationToken);
// If Stop() was called
if (!IsDeploymentRunning)
{
return;
}
Debug.Log("Running Game Server...");
RunLocalServerResponse serverResponse = _coreApi.RunLocalServer(BuildExecutablePath, Application.productName, localOperatingSystem);
if (!serverResponse.Success)
{
Debug.LogError("Error occurred when running game server...");
_status.IsDisplayed = true;
string message = string.Format(_textProvider.Get(Strings.StatusLocalTestServerErrorTemplate), _textProvider.GetError(serverResponse.ErrorCode));
_status.SetMessage(message, MessageType.Error);
_logger.LogResponseError(serverResponse);
return;
}
_serverProcessId = serverResponse.ProcessId;
SetStatus(Strings.StatusLocalTestRunning, MessageType.Info);
}
private void SetStatus(string statusKey, MessageType messageType)
{
_status.SetMessage(_textProvider.Get(statusKey), messageType);
_status.IsDisplayed = true;
}
}
}
| 169 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
namespace AmazonGameLift.Editor
{
internal class LocalTestFactory
{
public static LocalTest Create(TextProvider textProvider)
{
UnityLogger logger = UnityLoggerFactory.Create(textProvider);
return new LocalTest(CoreApi.SharedInstance, textProvider, new Delay(), logger);
}
public static void Restore(LocalTest target, TextProvider textProvider)
{
if (target is null)
{
throw new ArgumentNullException(nameof(target));
}
UnityLogger logger = UnityLoggerFactory.Create(textProvider);
target.Restore(CoreApi.SharedInstance, textProvider, new Delay(), logger);
}
}
}
| 28 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading;
using UnityEditor;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal class LocalTestWindow : EditorWindow
{
private const float WindowWidthPixels = 570f;
#if UNITY_2019_1_OR_NEWER
private const float WindowHeightPixels = 140f;
#else
private const float WindowHeightPixels = 130f;
#endif
private const float TopMarginPixels = 15f;
private const float LeftMarginPixels = 15f;
private const float RightMarginPixels = 13f;
private const float LabelWidthPixels = 180f;
private const float VerticalSpacingPixels = 5f;
private StatusLabel _statusLabel;
private HyperLinkButton _helpLinkButton;
private ControlDrawer _controlDrawer;
private LocalTest _model;
private string _labelServerPath;
private string _titleServerPathDialog;
private string _tooltipLocalTestingServerPath;
private string _labelLocalTestingPort;
private string _tooltipPort;
private string _labelStartButton;
private string _labelStopButton;
private string _labelGameLiftLocalPath;
[NonSerialized]
private bool _countedHeight;
private CancellationTokenSource _cancellation;
private void SetUp()
{
TextProvider textProvider = TextProviderFactory.Create();
titleContent = new GUIContent(textProvider.Get(Strings.TitleLocalTesting));
if (_model != null)
{
LocalTestFactory.Restore(_model, textProvider);
}
else
{
_model = LocalTestFactory.Create(textProvider);
}
_statusLabel = new StatusLabel();
_helpLinkButton = new HyperLinkButton(textProvider.Get(Strings.LabelLocalTestingHelp),
Urls.AwsHelpGameLiftLocal, ResourceUtility.GetHyperLinkStyle());
_controlDrawer = ControlDrawerFactory.Create();
this.SetConstantSize(new Vector2(x: WindowWidthPixels, y: WindowHeightPixels));
_labelServerPath = OperatingSystemUtility.isMacOs() ?
textProvider.Get(Strings.LabelLocalTestingMacOsServerPath) :
textProvider.Get(Strings.LabelLocalTestingWindowsServerPath);
_titleServerPathDialog = textProvider.Get(Strings.TitleLocalTestingServerPathDialog);
_tooltipLocalTestingServerPath = textProvider.Get(Strings.TooltipLocalTestingServerPath);
_labelLocalTestingPort = textProvider.Get(Strings.LabelLocalTestingPort);
_tooltipPort = textProvider.Get(Strings.TooltipLocalTestingPort);
_labelStartButton = textProvider.Get(Strings.LabelLocalTestingStartButton);
_labelStopButton = textProvider.Get(Strings.LabelLocalTestingStopButton);
_labelGameLiftLocalPath = textProvider.Get(Strings.LabelLocalTestingJarPath);
_model.Refresh();
}
private void OnEnable()
{
SetUp();
_cancellation = new CancellationTokenSource();
_model.Status.Changed += OnStatusChanged;
}
private void OnDisable()
{
_cancellation.Cancel();
_model.Save();
_model.Status.Changed -= OnStatusChanged;
}
private void OnGUI()
{
float uncountedHeight = 0f;
EditorGUIUtility.labelWidth = LabelWidthPixels;
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(LeftMarginPixels);
using (new EditorGUILayout.VerticalScope())
{
GUILayout.Space(TopMarginPixels);
uncountedHeight += DrawControls();
}
GUILayout.Space(RightMarginPixels);
}
if (!_countedHeight && Event.current.type == EventType.Repaint)
{
_countedHeight = true;
this.SetConstantSize(new Vector2(x: WindowWidthPixels, y: WindowHeightPixels + uncountedHeight));
}
}
private float DrawControls()
{
float uncountedHeight = 0f;
using (new EditorGUI.DisabledScope(_model.IsDeploymentRunning))
{
_model.BuildExecutablePath = _controlDrawer.DrawFilePathField(
_labelServerPath, _model.BuildExecutablePath, "", _titleServerPathDialog,
_tooltipLocalTestingServerPath);
GUILayout.Space(VerticalSpacingPixels);
float height = _controlDrawer.DrawReadOnlyTextWrapped(_labelGameLiftLocalPath, _model.GameLiftLocalPath);
GUILayout.Space(VerticalSpacingPixels + height);
_model.GameLiftLocalPort = _controlDrawer.DrawIntField(_labelLocalTestingPort, _model.GameLiftLocalPort, _tooltipPort);
uncountedHeight += height;
}
GUILayout.Space(2 * VerticalSpacingPixels);
DrawLink(_helpLinkButton);
GUILayout.Space(VerticalSpacingPixels);
using (new EditorGUILayout.HorizontalScope())
{
using (new EditorGUI.DisabledScope(!_model.CanStop))
{
if (GUILayout.Button(_labelStopButton))
{
_model.Stop();
}
}
using (new EditorGUI.DisabledScope(!_model.CanStart))
{
if (GUILayout.Button(_labelStartButton))
{
_ = _model.Start(_cancellation.Token);
}
}
}
if (_model.Status.IsDisplayed)
{
GUILayout.Space(VerticalSpacingPixels / 2f);
_statusLabel.Draw(_model.Status.Message, _model.Status.Type);
}
return uncountedHeight;
}
private void DrawLink(HyperLinkButton linkButton)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(5f);
linkButton.Draw();
}
}
private void OnStatusChanged()
{
Repaint();
}
}
}
| 179 |
Subsets and Splits