From d0a23344c4c04c844af7a25228066e8b46bdf1f2 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sun, 17 Jan 2021 00:29:38 +0000 Subject: [PATCH 01/31] Implement setpassword --- TCAdminApiSharp/Controllers/BaseController.cs | 4 ++-- TCAdminApiSharp/Entities/User/User.cs | 10 ++++++++++ TCAdminApiSharp/TCAdminApiSharp.csproj | 4 ++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index 2f5956d..8c3ddf7 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -31,7 +31,6 @@ protected BaseController(string baseResource) public RestRequest GenerateDefaultRequest() { - //Testchange2 return new(BaseResource); } @@ -70,7 +69,8 @@ internal T ExecuteRequest(RestRequest request, out IRestResponse restResponse internal async Task> ExecuteRequestAsync(RestRequest request) { - Logger.Debug("Request URL: " + TcaClient.RestClient.BuildUri(request)); + Logger.Verbose(JsonConvert.SerializeObject(request)); + Logger.Debug($"Request URL [{request.Method}]: {TcaClient.RestClient.BuildUri(request)}"); var restResponse = await TcaClient.RestClient.ExecuteAsync(request); Logger.Debug(restResponse.Content); Logger.Debug("Response Status: " + restResponse.ResponseStatus); diff --git a/TCAdminApiSharp/Entities/User/User.cs b/TCAdminApiSharp/Entities/User/User.cs index 4040d22..a5c8246 100644 --- a/TCAdminApiSharp/Entities/User/User.cs +++ b/TCAdminApiSharp/Entities/User/User.cs @@ -3,6 +3,7 @@ using TCAdminApiSharp.Controllers; using TCAdminApiSharp.Entities.Generic; using Microsoft.Extensions.DependencyInjection; +using RestSharp; namespace TCAdminApiSharp.Entities.User { @@ -85,6 +86,15 @@ public class User : ObjectBase, IObjectBaseCrud [JsonProperty("UserType")] public UserType UserType { get; set; } + public void SetPassword(string password) + { + var request = UsersController.GenerateDefaultRequest(); + request.Resource += $"setpassword/{UserId}"; + request.Method = Method.POST; + request.AddParameter("password", password, ParameterType.GetOrPost); + UsersController.ExecuteBaseResponseRequest(request); + } + public void Update(Action action) { throw new NotImplementedException(); diff --git a/TCAdminApiSharp/TCAdminApiSharp.csproj b/TCAdminApiSharp/TCAdminApiSharp.csproj index 6f2e1ef..45bc24c 100644 --- a/TCAdminApiSharp/TCAdminApiSharp.csproj +++ b/TCAdminApiSharp/TCAdminApiSharp.csproj @@ -12,8 +12,8 @@ https://avatars3.githubusercontent.com/u/67070230?s=200&v=4 https://github.com/TotalControlAdmin/TCAdminApiSharp TCAdmin, Wrapper, Rest, Api - 1.0.0 - 1.0.0 + 1.0.1 + 1.0.1 From f9dbdb4be4c68ee73095508eb42df78bf68c1039 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sun, 17 Jan 2021 00:34:32 +0000 Subject: [PATCH 02/31] Comment test --- TCAdminApiSharp/Entities/Service/Service.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index 4e961de..9ef99c3 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -254,6 +254,7 @@ public void Update(Action action) public void Delete() { + // todo: Luis hurry up implement pls throw new NotImplementedException(); } From e58413779781b9f8fcff52ce20e0752d0ad88315 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sun, 17 Jan 2021 00:35:06 +0000 Subject: [PATCH 03/31] Update publish.yml --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 3ba30ef..50a5aea 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -2,7 +2,7 @@ name: Deploy to Nuget on: push: - branches: [ master, dev ] + branches: [ master, dev-* ] jobs: build: From 8a6798e41c74a1778bc9787fe4a6cd94cfad284a Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sun, 17 Jan 2021 03:48:59 +0000 Subject: [PATCH 04/31] Fix circular ref --- TCAdminApiSharp/Controllers/BaseController.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index 8c3ddf7..5e5c217 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -69,7 +69,10 @@ internal T ExecuteRequest(RestRequest request, out IRestResponse restResponse internal async Task> ExecuteRequestAsync(RestRequest request) { - Logger.Verbose(JsonConvert.SerializeObject(request)); + Logger.Verbose(JsonConvert.SerializeObject(request, new JsonSerializerSettings() + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + })); Logger.Debug($"Request URL [{request.Method}]: {TcaClient.RestClient.BuildUri(request)}"); var restResponse = await TcaClient.RestClient.ExecuteAsync(request); Logger.Debug(restResponse.Content); From 4e74f26e080993e48f11822f71a91288c1298141 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Mon, 18 Jan 2021 14:59:13 +0000 Subject: [PATCH 05/31] Implemented querying --- .../Controllers/UsersController.cs | 17 +++++- .../Converters/ToStringJsonConverter.cs | 25 +++++++++ TCAdminApiSharp/Querying/ColumnOperator.cs | 20 +++++++ TCAdminApiSharp/Querying/QueryableInfo.cs | 40 ++++++++++++++ TCAdminApiSharp/Querying/Structs/WhereInfo.cs | 9 +++ TCAdminApiSharp/Querying/WhereList.cs | 55 +++++++++++++++++++ TCAdminApiSharp/Querying/WhereOperator.cs | 8 +++ 7 files changed, 173 insertions(+), 1 deletion(-) create mode 100644 TCAdminApiSharp/Converters/ToStringJsonConverter.cs create mode 100644 TCAdminApiSharp/Querying/ColumnOperator.cs create mode 100644 TCAdminApiSharp/Querying/QueryableInfo.cs create mode 100644 TCAdminApiSharp/Querying/Structs/WhereInfo.cs create mode 100644 TCAdminApiSharp/Querying/WhereList.cs create mode 100644 TCAdminApiSharp/Querying/WhereOperator.cs diff --git a/TCAdminApiSharp/Controllers/UsersController.cs b/TCAdminApiSharp/Controllers/UsersController.cs index 428cea5..e96cde3 100644 --- a/TCAdminApiSharp/Controllers/UsersController.cs +++ b/TCAdminApiSharp/Controllers/UsersController.cs @@ -1,8 +1,13 @@ -using System.Net; +using System; +using System.Linq.Expressions; +using System.Net; +using Newtonsoft.Json; +using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.User; using TCAdminApiSharp.Exceptions; using TCAdminApiSharp.Exceptions.API; +using TCAdminApiSharp.Querying; namespace TCAdminApiSharp.Controllers { @@ -47,6 +52,16 @@ public User GetMe() throw; } } + + public ListResponse FindUsers(QueryableInfo query) + { + var request = GenerateDefaultRequest(); + Logger.Debug(query.BuildQuery()); + request.Method = Method.POST; + request.Resource += $"users/{TcaClient.GetTokenUserId()}"; + request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); + return ExecuteListResponseRequest(request); + } public ListResponse GetMyUsers() { diff --git a/TCAdminApiSharp/Converters/ToStringJsonConverter.cs b/TCAdminApiSharp/Converters/ToStringJsonConverter.cs new file mode 100644 index 0000000..867ada7 --- /dev/null +++ b/TCAdminApiSharp/Converters/ToStringJsonConverter.cs @@ -0,0 +1,25 @@ +using System; +using Newtonsoft.Json; + +namespace TCAdminApiSharp.Converters +{ + public class ToStringJsonConverter : JsonConverter + { + public override bool CanConvert(Type objectType) + { + return true; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteValue(value.ToString()); + } + + public override bool CanRead => false; + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/ColumnOperator.cs b/TCAdminApiSharp/Querying/ColumnOperator.cs new file mode 100644 index 0000000..509622d --- /dev/null +++ b/TCAdminApiSharp/Querying/ColumnOperator.cs @@ -0,0 +1,20 @@ +namespace TCAdminApiSharp.Querying +{ + public enum ColumnOperator + { + Equal, + In, + TableEqual, + Different, + NotIn, + Like, + GreaterThan, + GreaterOrEqualTo, + LowerThan, + LowerOrEqualTo, + TableIn, + TableNotIn, + TableDifferent, + NotLike, + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/QueryableInfo.cs b/TCAdminApiSharp/Querying/QueryableInfo.cs new file mode 100644 index 0000000..ad4293b --- /dev/null +++ b/TCAdminApiSharp/Querying/QueryableInfo.cs @@ -0,0 +1,40 @@ +using Newtonsoft.Json; +using TCAdminApiSharp.Converters; + +namespace TCAdminApiSharp.Querying +{ + public class QueryableInfo + { + [JsonProperty("RowCount")] public int RowCount { get; set; } + + [JsonProperty("Offset")] public int Offset { get; set; } + + [JsonProperty("Where")] + [JsonConverter(typeof(ToStringJsonConverter))] + public WhereList WhereList { get; set; } + + public QueryableInfo() + { + } + + public QueryableInfo(int rowCount, int offset, WhereList whereList) + { + RowCount = rowCount; + Offset = offset; + WhereList = whereList; + } + + public QueryableInfo(WhereList whereList) + { + WhereList = whereList; + } + + public string BuildQuery() + { + return JsonConvert.SerializeObject(this, new JsonSerializerSettings() + { + NullValueHandling = NullValueHandling.Ignore + }); + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Structs/WhereInfo.cs b/TCAdminApiSharp/Querying/Structs/WhereInfo.cs new file mode 100644 index 0000000..00e3848 --- /dev/null +++ b/TCAdminApiSharp/Querying/Structs/WhereInfo.cs @@ -0,0 +1,9 @@ +namespace TCAdminApiSharp.Querying.Structs +{ + public struct WhereInfo + { + public string Column; + public object ColumnValue; + public ColumnOperator ColumnOperator; + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/WhereList.cs b/TCAdminApiSharp/Querying/WhereList.cs new file mode 100644 index 0000000..50581d7 --- /dev/null +++ b/TCAdminApiSharp/Querying/WhereList.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using TCAdminApiSharp.Querying.Structs; + +namespace TCAdminApiSharp.Querying +{ + public class WhereList : List + { + public WhereOperator WhereOperator { get; set; } + + public WhereList() => this.WhereOperator = WhereOperator.And; + + public WhereList(WhereInfo where) + { + this.WhereOperator = WhereOperator.And; + this.Add(where); + } + + public WhereList(string column, object value) + { + this.WhereOperator = WhereOperator.And; + this.Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); + } + + public WhereList(string column, ColumnOperator @operator, object value) + { + this.WhereOperator = WhereOperator.And; + this.Add(new WhereInfo + { + Column = column, + ColumnOperator = @operator, + ColumnValue = RuntimeHelpers.GetObjectValue(value) + }); + } + + public void Add(string column, object value) => + this.Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); + + public void Add(string column, ColumnOperator @operator, object value) => this.Add(new WhereInfo + { + Column = column, + ColumnOperator = @operator, + ColumnValue = value + }); + + public override string ToString() + { + return this.Aggregate("", + (current, whereInfo) => + current + + $"([{whereInfo.Column}] {whereInfo.ColumnOperator.ToString()} '{whereInfo.ColumnValue}')"); + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/WhereOperator.cs b/TCAdminApiSharp/Querying/WhereOperator.cs new file mode 100644 index 0000000..6ebb4f2 --- /dev/null +++ b/TCAdminApiSharp/Querying/WhereOperator.cs @@ -0,0 +1,8 @@ +namespace TCAdminApiSharp.Querying +{ + public enum WhereOperator + { + And, + Or + } +} \ No newline at end of file From c202d153f6d9d8239531c2bcf12f0a272f1ba514 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Mon, 18 Jan 2021 22:19:20 +0000 Subject: [PATCH 06/31] Interfaced query operations --- ...rter.cs => QueryOperationJsonConverter.cs} | 14 +++++++++++--- TCAdminApiSharp/Querying/IQueryOperation.cs | 9 +++++++++ TCAdminApiSharp/Querying/QueryableInfo.cs | 19 ++++++++++++------- TCAdminApiSharp/Querying/WhereList.cs | 10 +++++----- 4 files changed, 37 insertions(+), 15 deletions(-) rename TCAdminApiSharp/Converters/{ToStringJsonConverter.cs => QueryOperationJsonConverter.cs} (52%) create mode 100644 TCAdminApiSharp/Querying/IQueryOperation.cs diff --git a/TCAdminApiSharp/Converters/ToStringJsonConverter.cs b/TCAdminApiSharp/Converters/QueryOperationJsonConverter.cs similarity index 52% rename from TCAdminApiSharp/Converters/ToStringJsonConverter.cs rename to TCAdminApiSharp/Converters/QueryOperationJsonConverter.cs index 867ada7..39e399a 100644 --- a/TCAdminApiSharp/Converters/ToStringJsonConverter.cs +++ b/TCAdminApiSharp/Converters/QueryOperationJsonConverter.cs @@ -1,18 +1,26 @@ using System; using Newtonsoft.Json; +using TCAdminApiSharp.Querying; namespace TCAdminApiSharp.Converters { - public class ToStringJsonConverter : JsonConverter + public class QueryOperationJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return true; } - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { - writer.WriteValue(value.ToString()); + if (value != null && value.GetType().IsAssignableTo(typeof(IQueryOperation))) + { + writer.WriteValue(((IQueryOperation)value).GenerateQuery()); + } + else + { + throw new Exception($"Cannot convert {value?.GetType()} to {typeof(IQueryOperation)}"); + } } public override bool CanRead => false; diff --git a/TCAdminApiSharp/Querying/IQueryOperation.cs b/TCAdminApiSharp/Querying/IQueryOperation.cs new file mode 100644 index 0000000..fb1a972 --- /dev/null +++ b/TCAdminApiSharp/Querying/IQueryOperation.cs @@ -0,0 +1,9 @@ +namespace TCAdminApiSharp.Querying +{ + public interface IQueryOperation + { + string JsonKey { get; set; } + + string GenerateQuery(); + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/QueryableInfo.cs b/TCAdminApiSharp/Querying/QueryableInfo.cs index ad4293b..14d6e88 100644 --- a/TCAdminApiSharp/Querying/QueryableInfo.cs +++ b/TCAdminApiSharp/Querying/QueryableInfo.cs @@ -1,4 +1,6 @@ -using Newtonsoft.Json; +using System.Collections.Generic; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using TCAdminApiSharp.Converters; namespace TCAdminApiSharp.Querying @@ -9,9 +11,7 @@ public class QueryableInfo [JsonProperty("Offset")] public int Offset { get; set; } - [JsonProperty("Where")] - [JsonConverter(typeof(ToStringJsonConverter))] - public WhereList WhereList { get; set; } + [JsonIgnore] public List QueryOperations { get; set; } = new(); public QueryableInfo() { @@ -21,17 +21,22 @@ public QueryableInfo(int rowCount, int offset, WhereList whereList) { RowCount = rowCount; Offset = offset; - WhereList = whereList; + QueryOperations.Add(whereList); } public QueryableInfo(WhereList whereList) { - WhereList = whereList; + QueryOperations.Add(whereList); } public string BuildQuery() { - return JsonConvert.SerializeObject(this, new JsonSerializerSettings() + var jObject = JObject.FromObject(this); + foreach (var queryOperation in QueryOperations) + { + jObject.Add(queryOperation.JsonKey, queryOperation.GenerateQuery()); + } + return JsonConvert.SerializeObject(jObject, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); diff --git a/TCAdminApiSharp/Querying/WhereList.cs b/TCAdminApiSharp/Querying/WhereList.cs index 50581d7..2003d0e 100644 --- a/TCAdminApiSharp/Querying/WhereList.cs +++ b/TCAdminApiSharp/Querying/WhereList.cs @@ -5,12 +5,13 @@ namespace TCAdminApiSharp.Querying { - public class WhereList : List + public class WhereList : List, IQueryOperation { + public string JsonKey { get; set; } = "Where"; public WhereOperator WhereOperator { get; set; } public WhereList() => this.WhereOperator = WhereOperator.And; - + public WhereList(WhereInfo where) { this.WhereOperator = WhereOperator.And; @@ -44,12 +45,11 @@ public void Add(string column, ColumnOperator @operator, object value) => this.A ColumnValue = value }); - public override string ToString() + public string GenerateQuery() { return this.Aggregate("", (current, whereInfo) => current + - $"([{whereInfo.Column}] {whereInfo.ColumnOperator.ToString()} '{whereInfo.ColumnValue}')"); - } + $"([{whereInfo.Column}] {whereInfo.ColumnOperator.ToString()} '{whereInfo.ColumnValue}')"); } } } \ No newline at end of file From e0fcbdc03745d10e9e465c99134a82c9a4cca0e6 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 00:21:51 +0000 Subject: [PATCH 07/31] Better querying --- TCAdminApiSharp/Querying/ColumnOperator.cs | 20 ----- TCAdminApiSharp/Querying/IQueryOperation.cs | 6 +- .../Querying/Operations/OrderList.cs | 35 ++++++++ .../Querying/Operations/WhereList.cs | 85 +++++++++++++++++++ .../Querying/Operators/ColumnOperator.cs | 14 +++ .../Querying/Operators/OrderOperator.cs | 8 ++ .../Querying/{ => Operators}/WhereOperator.cs | 2 +- TCAdminApiSharp/Querying/QueryableInfo.cs | 14 +-- TCAdminApiSharp/Querying/Structs/OrderInfo.cs | 16 ++++ TCAdminApiSharp/Querying/Structs/WhereInfo.cs | 8 +- TCAdminApiSharp/Querying/WhereList.cs | 55 ------------ 11 files changed, 178 insertions(+), 85 deletions(-) delete mode 100644 TCAdminApiSharp/Querying/ColumnOperator.cs create mode 100644 TCAdminApiSharp/Querying/Operations/OrderList.cs create mode 100644 TCAdminApiSharp/Querying/Operations/WhereList.cs create mode 100644 TCAdminApiSharp/Querying/Operators/ColumnOperator.cs create mode 100644 TCAdminApiSharp/Querying/Operators/OrderOperator.cs rename TCAdminApiSharp/Querying/{ => Operators}/WhereOperator.cs (58%) create mode 100644 TCAdminApiSharp/Querying/Structs/OrderInfo.cs delete mode 100644 TCAdminApiSharp/Querying/WhereList.cs diff --git a/TCAdminApiSharp/Querying/ColumnOperator.cs b/TCAdminApiSharp/Querying/ColumnOperator.cs deleted file mode 100644 index 509622d..0000000 --- a/TCAdminApiSharp/Querying/ColumnOperator.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace TCAdminApiSharp.Querying -{ - public enum ColumnOperator - { - Equal, - In, - TableEqual, - Different, - NotIn, - Like, - GreaterThan, - GreaterOrEqualTo, - LowerThan, - LowerOrEqualTo, - TableIn, - TableNotIn, - TableDifferent, - NotLike, - } -} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/IQueryOperation.cs b/TCAdminApiSharp/Querying/IQueryOperation.cs index fb1a972..7c5fdf2 100644 --- a/TCAdminApiSharp/Querying/IQueryOperation.cs +++ b/TCAdminApiSharp/Querying/IQueryOperation.cs @@ -1,9 +1,11 @@ -namespace TCAdminApiSharp.Querying +using Newtonsoft.Json.Linq; + +namespace TCAdminApiSharp.Querying { public interface IQueryOperation { string JsonKey { get; set; } - string GenerateQuery(); + JToken GenerateQuery(); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operations/OrderList.cs b/TCAdminApiSharp/Querying/Operations/OrderList.cs new file mode 100644 index 0000000..8878bb2 --- /dev/null +++ b/TCAdminApiSharp/Querying/Operations/OrderList.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using TCAdminApiSharp.Querying.Operators; +using TCAdminApiSharp.Querying.Structs; + +namespace TCAdminApiSharp.Querying.Operations +{ + public class OrderList : List, IQueryOperation + { + [JsonIgnore] public string JsonKey { get; set; } = "Order"; + + public OrderList() + { + } + + public OrderList(string field, OrderOperator @operator) + { + this.Add(field, @operator); + } + + public void Add(string column, OrderOperator @operator) => this.Add(new OrderInfo + { + Column = column, + Operator = @operator + }); + + public JToken GenerateQuery() + { + return JToken.FromObject(this); + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operations/WhereList.cs b/TCAdminApiSharp/Querying/Operations/WhereList.cs new file mode 100644 index 0000000..577b4f9 --- /dev/null +++ b/TCAdminApiSharp/Querying/Operations/WhereList.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.Json.Serialization; +using Newtonsoft.Json.Linq; +using TCAdminApiSharp.Querying.Operators; +using TCAdminApiSharp.Querying.Structs; + +namespace TCAdminApiSharp.Querying.Operations +{ + public class WhereList : List, IQueryOperation + { + [JsonIgnore] public string JsonKey { get; set; } = "Where"; + [JsonIgnore] public WhereOperator WhereOperator { get; set; } + + public WhereList() => this.WhereOperator = WhereOperator.And; + + public WhereList(WhereInfo where) + { + this.WhereOperator = WhereOperator.And; + this.Add(where); + } + + public WhereList(string column, object value) + { + this.WhereOperator = WhereOperator.And; + this.Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); + } + + public WhereList(string column, ColumnOperator @operator, object value) + { + this.WhereOperator = WhereOperator.And; + this.Add(new WhereInfo + { + Column = column, + ColumnOperator = @operator, + ColumnValue = RuntimeHelpers.GetObjectValue(value) + }); + } + + public void Add(string column, object value) => + this.Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); + + public void Add(string column, ColumnOperator @operator, object value) => this.Add(new WhereInfo + { + Column = column, + ColumnOperator = @operator, + ColumnValue = value + }); + + public JToken GenerateQuery() + { + var temp = "("; + foreach (var info in this) + { + temp += $"[{info.Column}] {ConvertColumnOperator(info.ColumnOperator)} '{info.ColumnValue}'"; + if (!this.Last().Equals(info)) + { + // Add where operator + temp += $" {this.WhereOperator.ToString().ToUpper()} "; + } + } + + temp += ")"; + return new JValue(temp); + } + + public string ConvertColumnOperator(ColumnOperator columnOperator) + { + return columnOperator switch + { + ColumnOperator.Equal => "=", + ColumnOperator.NotEqual => "<>", + ColumnOperator.GreaterThan => ">", + ColumnOperator.GreaterOrEqualTo => ">=", + ColumnOperator.LowerThan => "<", + ColumnOperator.LowerOrEqualTo => "<=", + ColumnOperator.Like => "LIKE", + ColumnOperator.NotLike => "NOT LIKE", + _ => throw new ArgumentOutOfRangeException(nameof(columnOperator), columnOperator, null) + }; + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operators/ColumnOperator.cs b/TCAdminApiSharp/Querying/Operators/ColumnOperator.cs new file mode 100644 index 0000000..e82dd6c --- /dev/null +++ b/TCAdminApiSharp/Querying/Operators/ColumnOperator.cs @@ -0,0 +1,14 @@ +namespace TCAdminApiSharp.Querying.Operators +{ + public enum ColumnOperator + { + Equal, + NotEqual, + GreaterThan, + GreaterOrEqualTo, + LowerThan, + LowerOrEqualTo, + Like, + NotLike + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operators/OrderOperator.cs b/TCAdminApiSharp/Querying/Operators/OrderOperator.cs new file mode 100644 index 0000000..c39991c --- /dev/null +++ b/TCAdminApiSharp/Querying/Operators/OrderOperator.cs @@ -0,0 +1,8 @@ +namespace TCAdminApiSharp.Querying.Operators +{ + public enum OrderOperator + { + Ascending, + Descending + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/WhereOperator.cs b/TCAdminApiSharp/Querying/Operators/WhereOperator.cs similarity index 58% rename from TCAdminApiSharp/Querying/WhereOperator.cs rename to TCAdminApiSharp/Querying/Operators/WhereOperator.cs index 6ebb4f2..faafd5c 100644 --- a/TCAdminApiSharp/Querying/WhereOperator.cs +++ b/TCAdminApiSharp/Querying/Operators/WhereOperator.cs @@ -1,4 +1,4 @@ -namespace TCAdminApiSharp.Querying +namespace TCAdminApiSharp.Querying.Operators { public enum WhereOperator { diff --git a/TCAdminApiSharp/Querying/QueryableInfo.cs b/TCAdminApiSharp/Querying/QueryableInfo.cs index 14d6e88..48ef72e 100644 --- a/TCAdminApiSharp/Querying/QueryableInfo.cs +++ b/TCAdminApiSharp/Querying/QueryableInfo.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using TCAdminApiSharp.Converters; namespace TCAdminApiSharp.Querying { @@ -17,16 +16,19 @@ public QueryableInfo() { } - public QueryableInfo(int rowCount, int offset, WhereList whereList) + public QueryableInfo(int rowCount, int offset, IQueryOperation queryOperation) { RowCount = rowCount; Offset = offset; - QueryOperations.Add(whereList); + QueryOperations.Add(queryOperation); } - public QueryableInfo(WhereList whereList) + public QueryableInfo(params IQueryOperation[] queryOperations) { - QueryOperations.Add(whereList); + foreach (var queryOperation in queryOperations) + { + QueryOperations.Add(queryOperation); + } } public string BuildQuery() @@ -38,7 +40,7 @@ public string BuildQuery() } return JsonConvert.SerializeObject(jObject, new JsonSerializerSettings { - NullValueHandling = NullValueHandling.Ignore + NullValueHandling = NullValueHandling.Ignore, }); } } diff --git a/TCAdminApiSharp/Querying/Structs/OrderInfo.cs b/TCAdminApiSharp/Querying/Structs/OrderInfo.cs new file mode 100644 index 0000000..4dc4f3d --- /dev/null +++ b/TCAdminApiSharp/Querying/Structs/OrderInfo.cs @@ -0,0 +1,16 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using TCAdminApiSharp.Querying.Operators; + +namespace TCAdminApiSharp.Querying.Structs +{ + public struct OrderInfo + { + [JsonProperty("Field")] + public string Column; + + [JsonProperty("Direction")] + [JsonConverter(typeof(StringEnumConverter))] + public OrderOperator Operator; + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Structs/WhereInfo.cs b/TCAdminApiSharp/Querying/Structs/WhereInfo.cs index 00e3848..ca1ef96 100644 --- a/TCAdminApiSharp/Querying/Structs/WhereInfo.cs +++ b/TCAdminApiSharp/Querying/Structs/WhereInfo.cs @@ -1,9 +1,15 @@ -namespace TCAdminApiSharp.Querying.Structs +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using TCAdminApiSharp.Querying.Operators; + +namespace TCAdminApiSharp.Querying.Structs { public struct WhereInfo { public string Column; public object ColumnValue; + + [JsonConverter(typeof(StringEnumConverter))] public ColumnOperator ColumnOperator; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/WhereList.cs b/TCAdminApiSharp/Querying/WhereList.cs deleted file mode 100644 index 2003d0e..0000000 --- a/TCAdminApiSharp/Querying/WhereList.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; -using TCAdminApiSharp.Querying.Structs; - -namespace TCAdminApiSharp.Querying -{ - public class WhereList : List, IQueryOperation - { - public string JsonKey { get; set; } = "Where"; - public WhereOperator WhereOperator { get; set; } - - public WhereList() => this.WhereOperator = WhereOperator.And; - - public WhereList(WhereInfo where) - { - this.WhereOperator = WhereOperator.And; - this.Add(where); - } - - public WhereList(string column, object value) - { - this.WhereOperator = WhereOperator.And; - this.Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); - } - - public WhereList(string column, ColumnOperator @operator, object value) - { - this.WhereOperator = WhereOperator.And; - this.Add(new WhereInfo - { - Column = column, - ColumnOperator = @operator, - ColumnValue = RuntimeHelpers.GetObjectValue(value) - }); - } - - public void Add(string column, object value) => - this.Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); - - public void Add(string column, ColumnOperator @operator, object value) => this.Add(new WhereInfo - { - Column = column, - ColumnOperator = @operator, - ColumnValue = value - }); - - public string GenerateQuery() - { - return this.Aggregate("", - (current, whereInfo) => - current + - $"([{whereInfo.Column}] {whereInfo.ColumnOperator.ToString()} '{whereInfo.ColumnValue}')"); } - } -} \ No newline at end of file From fc73cd8d92e0fbd82b2f94c1abda5e4ddd1b81a1 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 00:41:41 +0000 Subject: [PATCH 08/31] Implemented Server --- .../Controllers/ServersController.cs | 54 ++++ TCAdminApiSharp/Entities/Server/Server.cs | 261 ++++++++++++++++++ 2 files changed, 315 insertions(+) create mode 100644 TCAdminApiSharp/Controllers/ServersController.cs create mode 100644 TCAdminApiSharp/Entities/Server/Server.cs diff --git a/TCAdminApiSharp/Controllers/ServersController.cs b/TCAdminApiSharp/Controllers/ServersController.cs new file mode 100644 index 0000000..42d82bd --- /dev/null +++ b/TCAdminApiSharp/Controllers/ServersController.cs @@ -0,0 +1,54 @@ +using System; +using System.Net; +using RestSharp; +using TCAdminApiSharp.Entities.API; +using TCAdminApiSharp.Entities.Server; +using TCAdminApiSharp.Entities.Service; +using TCAdminApiSharp.Exceptions; +using TCAdminApiSharp.Exceptions.API; + +namespace TCAdminApiSharp.Controllers +{ + public class ServersController : BaseController + { + public ServersController() : base("api/server") + { + } + + // public int CreateService(ServiceBuilder builder) + // { + // var body = builder.GenerateRequestBody(); + // var request = GenerateDefaultRequest(); + // request.Resource += "create"; + // request.Method = Method.POST; + // request.AddParameter("createinfo", body, ParameterType.GetOrPost); + // return ExecuteBaseResponseRequest(request).Result; + // } + + public Server GetServer(int serverId) + { + try + { + var request = GenerateDefaultRequest(); + request.Resource += serverId; + return ExecuteBaseResponseRequest(request).Result; + } + catch (ApiResponseException e) + { + if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) + { + throw new NotFoundException(typeof(Service), e, new []{serverId}); + } + + throw; + } + } + + public ListResponse GetServices() + { + var request = GenerateDefaultRequest(); + request.Resource += "servers"; + return ExecuteListResponseRequest(request); + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Server/Server.cs b/TCAdminApiSharp/Entities/Server/Server.cs new file mode 100644 index 0000000..cb02735 --- /dev/null +++ b/TCAdminApiSharp/Entities/Server/Server.cs @@ -0,0 +1,261 @@ +using System; +using Newtonsoft.Json; +using RestSharp; +using Microsoft.Extensions.DependencyInjection; +using TCAdminApiSharp.Controllers; +using TCAdminApiSharp.Entities.Generic; +using TCAdminApiSharp.Helpers; + +namespace TCAdminApiSharp.Entities.Server +{ + public class Server : ObjectBase, IObjectBaseCrud + { + [JsonIgnore] public readonly ServersController ServersController = + TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); + + [JsonProperty("DisableNewServices")] public bool DisableNewServices { get; set; } + + [JsonProperty("GameFilesPath")] public string GameFilesPath { get; set; } + + [JsonProperty("VSUseCustomGameFiles")] public bool VSUseCustomGameFiles { get; set; } + + [JsonProperty("ExtractSpeed")] public int ExtractSpeed { get; set; } + + [JsonProperty("UserFilesPath")] public string UserFilesPath { get; set; } + + [JsonProperty("FolderTemplate")] public string FolderTemplate { get; set; } + + [JsonProperty("KeepLocalCopy")] public bool KeepLocalCopy { get; set; } + + [JsonProperty("LastServiceCreationUtc")] + public DateTime LastServiceCreationUtc { get; set; } + + [JsonProperty("EnableFileSharing")] public bool EnableFileSharing { get; set; } + + [JsonProperty("EnableFastDownload")] public bool EnableFastDownload { get; set; } + + [JsonProperty("ServerFileProviderModuleId")] + public string ServerFileProviderModuleId { get; set; } + + [JsonProperty("ServerFileProviderId")] public int ServerFileProviderId { get; set; } + + [JsonProperty("ClientFileProviderModuleId")] + public string ClientFileProviderModuleId { get; set; } + + [JsonProperty("ClientFileProviderId")] public int ClientFileProviderId { get; set; } + + [JsonProperty("ClientFileProviderSourceId")] + public int ClientFileProviderSourceId { get; set; } + + [JsonProperty("FastDownloadFolderTemplate")] + public string FastDownloadFolderTemplate { get; set; } + + [JsonProperty("FastDownloadSavePath")] public string FastDownloadSavePath { get; set; } + + [JsonProperty("FastDownloadUrl")] public string FastDownloadUrl { get; set; } + + [JsonProperty("ClientFastDownloadProviderModuleId")] + public string ClientFastDownloadProviderModuleId { get; set; } + + [JsonProperty("ClientFastDownloadProviderId")] + public int ClientFastDownloadProviderId { get; set; } + + [JsonProperty("ClientFastDownloadProviderSourceId")] + public int ClientFastDownloadProviderSourceId { get; set; } + + [JsonProperty("NumberOfServices")] public int NumberOfServices { get; set; } + + [JsonProperty("NumberOfVoiceServices")] + public int NumberOfVoiceServices { get; set; } + + [JsonProperty("NumberOfSlots")] public int NumberOfSlots { get; set; } + + [JsonProperty("NumberOfVoiceSlots")] public int NumberOfVoiceSlots { get; set; } + + [JsonProperty("MaxSlots")] public int MaxSlots { get; set; } + + [JsonProperty("SkipSuspendedServices")] + public bool SkipSuspendedServices { get; set; } + + [JsonProperty("SeparateVoiceSots")] public bool SeparateVoiceSots { get; set; } + + [JsonProperty("MaxVoiceSlots")] public int MaxVoiceSlots { get; set; } + + [JsonProperty("MaxServices")] public int MaxServices { get; set; } + + [JsonProperty("SeparateVoiceServices")] + public bool SeparateVoiceServices { get; set; } + + [JsonProperty("MaxVoiceServices")] public int MaxVoiceServices { get; set; } + + [JsonProperty("ServerId")] public int ServerId { get; set; } + + [JsonProperty("PrivateNetworkId")] public int PrivateNetworkId { get; set; } + + [JsonProperty("PrivateNetworkIp")] public string PrivateNetworkIp { get; set; } + + [JsonProperty("DisableVirtualServerUser")] + public bool DisableVirtualServerUser { get; set; } + + [JsonProperty("UseCustomDatacenterId")] + public bool UseCustomDatacenterId { get; set; } + + [JsonProperty("DatacenterId")] public int DatacenterId { get; set; } + + [JsonProperty("OwnerId")] public int OwnerId { get; set; } + + [JsonProperty("OwnerIdFriendlyName")] public string OwnerIdFriendlyName { get; set; } + + [JsonProperty("IsMaster")] public bool IsMaster { get; set; } + + [JsonProperty("OperatingSystem")] public int OperatingSystem { get; set; } + + [JsonProperty("PrimaryIp")] public string PrimaryIp { get; set; } + + [JsonProperty("SecurePort")] public int SecurePort { get; set; } + + [JsonProperty("StandardPort")] public int StandardPort { get; set; } + + [JsonProperty("BindAllIps")] public bool BindAllIps { get; set; } + + [JsonProperty("FirewallIp")] public string FirewallIp { get; set; } + + [JsonProperty("Name")] public string Name { get; set; } + + [JsonProperty("Enabled")] public bool Enabled { get; set; } + + [JsonProperty("DisableUpdates")] public bool DisableUpdates { get; set; } + + [JsonProperty("MonitorVirtualDirectory")] + public string MonitorVirtualDirectory { get; set; } + + [JsonProperty("PublicVirtualDirectory")] + public string PublicVirtualDirectory { get; set; } + + [JsonProperty("ControlPanelEnableBasicAuth")] + public bool ControlPanelEnableBasicAuth { get; set; } + + [JsonProperty("ControlPanelRealm")] public string ControlPanelRealm { get; set; } + + [JsonProperty("ControlPanelLogOutUrl")] + public string ControlPanelLogOutUrl { get; set; } + + [JsonProperty("WindowsFirewallEnabled")] + public bool WindowsFirewallEnabled { get; set; } + + [JsonProperty("uPnPPortForwardingEnabled")] + public bool UPnPPortForwardingEnabled { get; set; } + + [JsonProperty("MonitorLogin")] public string MonitorLogin { get; set; } + + [JsonProperty("MonitorPassword")] public string MonitorPassword { get; set; } + + [JsonProperty("MonitorVersion")] public string MonitorVersion { get; set; } + + [JsonProperty("FileSystemComparison")] public int FileSystemComparison { get; set; } + + [JsonProperty("FileSystemDirectorySeparator")] + public string FileSystemDirectorySeparator { get; set; } + + [JsonProperty("DatacenterName")] public string DatacenterName { get; set; } + + [JsonProperty("IsVirtual")] public bool IsVirtual { get; set; } + + [JsonProperty("RealServerId")] public int RealServerId { get; set; } + + [JsonProperty("RealServerName")] public string RealServerName { get; set; } + + [JsonProperty("KeepAlive")] public int KeepAlive { get; set; } + + [JsonProperty("NumberOfProcessors")] public int NumberOfProcessors { get; set; } + + [JsonProperty("MaxNumaNode")] public int MaxNumaNode { get; set; } + + [JsonProperty("MonitorAffinity")] public int MonitorAffinity { get; set; } + + [JsonProperty("MonitorNumaNode")] public int MonitorNumaNode { get; set; } + + [JsonProperty("MonitorPriority")] public int MonitorPriority { get; set; } + + [JsonProperty("Affinity")] public int Affinity { get; set; } + + [JsonProperty("NumaNode")] public int NumaNode { get; set; } + + [JsonProperty("Memory")] public long Memory { get; set; } + + [JsonProperty("MemoryMB")] public int MemoryMB { get; set; } + + [JsonProperty("MemoryString")] public string MemoryString { get; set; } + + [JsonProperty("DiskSpace")] public int DiskSpace { get; set; } + + [JsonProperty("DiskSpaceMB")] public int DiskSpaceMB { get; set; } + + [JsonProperty("DiskSpaceString")] public string DiskSpaceString { get; set; } + + [JsonProperty("DiskDrive")] public string DiskDrive { get; set; } + + [JsonProperty("CustomField1")] public string CustomField1 { get; set; } + + [JsonProperty("CustomField2")] public string CustomField2 { get; set; } + + [JsonProperty("CustomField3")] public string CustomField3 { get; set; } + + [JsonProperty("CustomField4")] public string CustomField4 { get; set; } + + [JsonProperty("CustomField5")] public string CustomField5 { get; set; } + + [JsonProperty("CustomField6")] public string CustomField6 { get; set; } + + [JsonProperty("CustomField7")] public string CustomField7 { get; set; } + + [JsonProperty("CustomField8")] public string CustomField8 { get; set; } + + [JsonProperty("CustomField9")] public string CustomField9 { get; set; } + + [JsonProperty("CustomField10")] public string CustomField10 { get; set; } + + [JsonProperty("CustomField11")] public string CustomField11 { get; set; } + + [JsonProperty("CustomField12")] public string CustomField12 { get; set; } + + [JsonProperty("CustomField13")] public string CustomField13 { get; set; } + + [JsonProperty("CustomField14")] public string CustomField14 { get; set; } + + [JsonProperty("CustomField15")] public string CustomField15 { get; set; } + + [JsonProperty("BillingId")] public string BillingId { get; set; } + + [JsonProperty("BillingStatus")] public int BillingStatus { get; set; } + + [JsonProperty("PeakMemoryMB")] public double PeakMemoryMB { get; set; } + + [JsonProperty("PeakCPU")] public double PeakCPU { get; set; } + + [JsonProperty("DCSyncUrl")] public string DCSyncUrl { get; set; } + + [JsonProperty("DCDownloadServer")] public string DCDownloadServer { get; set; } + + [JsonProperty("DCDownloadUser")] public string DCDownloadUser { get; set; } + + [JsonProperty("DCDownloadPassword")] public string DCDownloadPassword { get; set; } + + public void Update(Action action) + { + var server = new Server(); + action(server); + var putJson = JsonConvert.SerializeObject(server, Constants.IgnoreDefaultValues); + var request = ServersController.GenerateDefaultRequest(); + request.Resource += this.ServerId; + request.Method = Method.PUT; + request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); + ServersController.ExecuteBaseResponseRequest(request); + } + + public void Delete() + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file From 3483d63e29b62fc000624f923233fbf7e40bb3be Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 00:41:56 +0000 Subject: [PATCH 09/31] Implemented Services search --- TCAdminApiSharp/Controllers/ServicesController.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/TCAdminApiSharp/Controllers/ServicesController.cs b/TCAdminApiSharp/Controllers/ServicesController.cs index 5a8149d..7e77311 100644 --- a/TCAdminApiSharp/Controllers/ServicesController.cs +++ b/TCAdminApiSharp/Controllers/ServicesController.cs @@ -3,8 +3,10 @@ using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Service; +using TCAdminApiSharp.Entities.User; using TCAdminApiSharp.Exceptions; using TCAdminApiSharp.Exceptions.API; +using TCAdminApiSharp.Querying; namespace TCAdminApiSharp.Controllers { @@ -24,6 +26,16 @@ public int CreateService(ServiceBuilder builder) return ExecuteBaseResponseRequest(request).Result; } + public ListResponse FindServices(QueryableInfo query) + { + var request = GenerateDefaultRequest(); + Logger.Debug(query.BuildQuery()); + request.Method = Method.POST; + request.Resource += "gameservices"; + request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); + return ExecuteListResponseRequest(request); + } + public Service GetService(int serviceId) { try From f42cac54d120015485319ba85d6a4f5c88580bf0 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 02:59:11 +0000 Subject: [PATCH 10/31] Object relationships --- .../Controllers/ServicesController.cs | 20 +++++++++++++++---- .../Controllers/UsersController.cs | 5 +---- TCAdminApiSharp/Entities/API/EmptyResponse.cs | 7 ------- TCAdminApiSharp/Entities/Service/Service.cs | 3 +++ TCAdminApiSharp/Entities/User/User.cs | 4 ++++ TCAdminApiSharp/TcaClient.cs | 3 +++ 6 files changed, 27 insertions(+), 15 deletions(-) delete mode 100644 TCAdminApiSharp/Entities/API/EmptyResponse.cs diff --git a/TCAdminApiSharp/Controllers/ServicesController.cs b/TCAdminApiSharp/Controllers/ServicesController.cs index 7e77311..7348543 100644 --- a/TCAdminApiSharp/Controllers/ServicesController.cs +++ b/TCAdminApiSharp/Controllers/ServicesController.cs @@ -7,6 +7,8 @@ using TCAdminApiSharp.Exceptions; using TCAdminApiSharp.Exceptions.API; using TCAdminApiSharp.Querying; +using TCAdminApiSharp.Querying.Operations; +using TCAdminApiSharp.Querying.Operators; namespace TCAdminApiSharp.Controllers { @@ -25,7 +27,7 @@ public int CreateService(ServiceBuilder builder) request.AddParameter("createinfo", body, ParameterType.GetOrPost); return ExecuteBaseResponseRequest(request).Result; } - + public ListResponse FindServices(QueryableInfo query) { var request = GenerateDefaultRequest(); @@ -35,7 +37,7 @@ public ListResponse FindServices(QueryableInfo query) request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); return ExecuteListResponseRequest(request); } - + public Service GetService(int serviceId) { try @@ -48,18 +50,28 @@ public Service GetService(int serviceId) { if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) { - throw new NotFoundException(typeof(Service), e, new []{serviceId}); + throw new NotFoundException(typeof(Service), e, new[] {serviceId}); } throw; } } - + public ListResponse GetServices() { var request = GenerateDefaultRequest(); request.Resource += "gameservices"; return ExecuteListResponseRequest(request); } + + public ListResponse GetServicesByBillingId(string billingId) + { + return FindServices(new QueryableInfo(new WhereList("BillingId", ColumnOperator.Equal, billingId))); + } + + public ListResponse GetServicesByUserId(int userId) + { + return FindServices(new QueryableInfo(new WhereList("UserId", ColumnOperator.Equal, userId))); + } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Controllers/UsersController.cs b/TCAdminApiSharp/Controllers/UsersController.cs index e96cde3..5394878 100644 --- a/TCAdminApiSharp/Controllers/UsersController.cs +++ b/TCAdminApiSharp/Controllers/UsersController.cs @@ -1,7 +1,4 @@ -using System; -using System.Linq.Expressions; -using System.Net; -using Newtonsoft.Json; +using System.Net; using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.User; diff --git a/TCAdminApiSharp/Entities/API/EmptyResponse.cs b/TCAdminApiSharp/Entities/API/EmptyResponse.cs deleted file mode 100644 index b4753a6..0000000 --- a/TCAdminApiSharp/Entities/API/EmptyResponse.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace TCAdminApiSharp.Entities.API -{ - public class EmptyResponse - { - - } -} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index 9ef99c3..c1c51d3 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -240,6 +240,9 @@ public class Service : ObjectBase, IObjectBaseCrud, IPowerable [JsonProperty("Notes")] public string Notes { get; set; } + public User.User User => ServicesController.TcaClient.UsersController.GetUser(this.UserId); + public Server.Server Server => ServicesController.TcaClient.ServersController.GetServer(this.ServerId); + public void Update(Action action) { var service = new Service(); diff --git a/TCAdminApiSharp/Entities/User/User.cs b/TCAdminApiSharp/Entities/User/User.cs index a5c8246..dbc4c37 100644 --- a/TCAdminApiSharp/Entities/User/User.cs +++ b/TCAdminApiSharp/Entities/User/User.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Newtonsoft.Json; using TCAdminApiSharp.Controllers; using TCAdminApiSharp.Entities.Generic; @@ -86,6 +87,9 @@ public class User : ObjectBase, IObjectBaseCrud [JsonProperty("UserType")] public UserType UserType { get; set; } + public IList Services => + UsersController.TcaClient.ServicesController.GetServicesByUserId(this.UserId).Result; + public void SetPassword(string password) { var request = UsersController.GenerateDefaultRequest(); diff --git a/TCAdminApiSharp/TcaClient.cs b/TCAdminApiSharp/TcaClient.cs index 71cd820..4e4ebbf 100644 --- a/TCAdminApiSharp/TcaClient.cs +++ b/TCAdminApiSharp/TcaClient.cs @@ -15,6 +15,7 @@ public class TcaClient internal static ServiceProvider ServiceProvider; internal readonly RestClient RestClient; public readonly ServicesController ServicesController; + public readonly ServersController ServersController; public readonly UsersController UsersController; public readonly TasksController TasksController; @@ -38,6 +39,7 @@ public TcaClient(string host, string apiKey, LogEventLevel minimumLogLevel = Log RestClient.AddDefaultHeader("api_key", apiKey); ServicesController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); + ServersController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); UsersController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); TasksController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); } @@ -52,6 +54,7 @@ private void CreateHostBuilder() ServiceProvider = new ServiceCollection() .AddTransient(_ => this) .AddScoped() + .AddScoped() .AddScoped() .AddScoped() .BuildServiceProvider(); From d71ded811656bbb39538fa1a6fef5cde4bce43de Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 03:03:46 +0000 Subject: [PATCH 11/31] Json Ignore new properties --- TCAdminApiSharp/Entities/Service/Service.cs | 4 ++-- TCAdminApiSharp/Entities/User/User.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index c1c51d3..bfa0ba1 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -240,8 +240,8 @@ public class Service : ObjectBase, IObjectBaseCrud, IPowerable [JsonProperty("Notes")] public string Notes { get; set; } - public User.User User => ServicesController.TcaClient.UsersController.GetUser(this.UserId); - public Server.Server Server => ServicesController.TcaClient.ServersController.GetServer(this.ServerId); + [JsonIgnore] public User.User User => ServicesController.TcaClient.UsersController.GetUser(this.UserId); + [JsonIgnore] public Server.Server Server => ServicesController.TcaClient.ServersController.GetServer(this.ServerId); public void Update(Action action) { diff --git a/TCAdminApiSharp/Entities/User/User.cs b/TCAdminApiSharp/Entities/User/User.cs index dbc4c37..7b53955 100644 --- a/TCAdminApiSharp/Entities/User/User.cs +++ b/TCAdminApiSharp/Entities/User/User.cs @@ -87,7 +87,7 @@ public class User : ObjectBase, IObjectBaseCrud [JsonProperty("UserType")] public UserType UserType { get; set; } - public IList Services => + [JsonIgnore] public IList Services => UsersController.TcaClient.ServicesController.GetServicesByUserId(this.UserId).Result; public void SetPassword(string password) From a67ca9ac59759ac7e3f538780f6d5921fb4309f3 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 15:42:27 +0000 Subject: [PATCH 12/31] Implemented service suspend/unsuspend --- TCAdminApiSharp/Entities/Service/Service.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index bfa0ba1..9c18875 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -304,5 +304,21 @@ public void Configure() request.Method = Method.POST; ServicesController.ExecuteBaseResponseRequest(request); } + + public bool Suspend() + { + var request = ServicesController.GenerateDefaultRequest(); + request.Resource += $"suspend/{this.ServiceId}"; + request.Method = Method.POST; + return ServicesController.ExecuteBaseResponseRequest(request).Success; + } + + public bool Unsuspend() + { + var request = ServicesController.GenerateDefaultRequest(); + request.Resource += $"unsuspend/{this.ServiceId}"; + request.Method = Method.POST; + return ServicesController.ExecuteBaseResponseRequest(request).Success; + } } } \ No newline at end of file From eb6e4c91bee6dd2f7948045e3dfce249c56ca122 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 15:45:27 +0000 Subject: [PATCH 13/31] Remove supression --- TCAdminApiSharp/Entities/Service/Service.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index 9c18875..969238b 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using RestSharp; From c585669f57266a61d2595f1523113e1339825ee3 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 16:55:56 +0000 Subject: [PATCH 14/31] Implemented settings --- TCAdminApiSharp.Tests/ServiceTests.cs | 2 +- TCAdminApiSharp/Controllers/BaseController.cs | 34 ++++++++++++------- TCAdminApiSharp/Entities/User/User.cs | 30 +++++++++++++++- TCAdminApiSharp/Helpers/Constants.cs | 5 +++ TCAdminApiSharp/TcaClient.cs | 11 +++--- TCAdminApiSharp/TcaClientSettings.cs | 21 ++++++++++++ 6 files changed, 85 insertions(+), 18 deletions(-) create mode 100644 TCAdminApiSharp/TcaClientSettings.cs diff --git a/TCAdminApiSharp.Tests/ServiceTests.cs b/TCAdminApiSharp.Tests/ServiceTests.cs index ccd143f..d5235ae 100644 --- a/TCAdminApiSharp.Tests/ServiceTests.cs +++ b/TCAdminApiSharp.Tests/ServiceTests.cs @@ -16,7 +16,7 @@ public class ServiceTests [SetUp] public void Setup() { - _tcaClient = new TcaClient("https://4a815e4e-aaa8-4351-a948-5ca3f92e5c8b.mock.pstmn.io", "-", LogEventLevel.Debug); + _tcaClient = new TcaClient("https://4a815e4e-aaa8-4351-a948-5ca3f92e5c8b.mock.pstmn.io", "-", TcaClientSettings.Debug); } [Test] diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index 5e5c217..93d27a6 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -8,6 +8,7 @@ using Serilog; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Exceptions.API; +using TCAdminApiSharp.Helpers; namespace TCAdminApiSharp.Controllers { @@ -34,61 +35,66 @@ public RestRequest GenerateDefaultRequest() return new(BaseResource); } - internal BaseResponse ExecuteBaseResponseRequest(RestRequest request) + public BaseResponse ExecuteBaseResponseRequest(RestRequest request) { var response = ExecuteRequest(request, out var restResponse); response.RestResponse = restResponse; return response; } - internal BaseResponse ExecuteBaseResponseRequest(RestRequest request) + public BaseResponse ExecuteBaseResponseRequest(RestRequest request) { var response = ExecuteRequest>(request, out var restResponse); response.RestResponse = restResponse; return response; } - internal ListResponse ExecuteListResponseRequest(RestRequest request) + public ListResponse ExecuteListResponseRequest(RestRequest request) { var response = ExecuteRequest>(request, out var restResponse); response.RestResponse = restResponse; return response; } - internal T ExecuteRequest(RestRequest request) + public T ExecuteRequest(RestRequest request) { return ExecuteRequest(request, out _); } - internal T ExecuteRequest(RestRequest request, out IRestResponse restResponse) + public T ExecuteRequest(RestRequest request, out IRestResponse restResponse) { var (t, restResponse2) = ExecuteRequestAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); restResponse = restResponse2; return t; } - internal async Task> ExecuteRequestAsync(RestRequest request) + public async Task> ExecuteRequestAsync(RestRequest request) { - Logger.Verbose(JsonConvert.SerializeObject(request, new JsonSerializerSettings() - { - ReferenceLoopHandling = ReferenceLoopHandling.Ignore - })); + Logger.Verbose(JsonConvert.SerializeObject(request, Constants.IgnoreReferenceLoop)); Logger.Debug($"Request URL [{request.Method}]: {TcaClient.RestClient.BuildUri(request)}"); var restResponse = await TcaClient.RestClient.ExecuteAsync(request); - Logger.Debug(restResponse.Content); + Logger.Verbose(JsonConvert.SerializeObject(restResponse, Constants.IgnoreReferenceLoop)); Logger.Debug("Response Status: " + restResponse.ResponseStatus); Logger.Debug("Status Code: " + restResponse.StatusCode); if (restResponse.ResponseStatus != ResponseStatus.Completed) { + if (!TcaClient.Settings.ThrowOnApiResponseStatusNonComplete) + { + return new Tuple(default!, restResponse); + } throw new ApiResponseException(restResponse, "Response Status is: " + restResponse.ResponseStatus); } if (restResponse.StatusCode != HttpStatusCode.OK) { + if (!TcaClient.Settings.ThrowOnApiStatusCodeNonOk) + { + return new Tuple(default!, restResponse); + } throw new ApiResponseException(restResponse, "Status code is: " + restResponse.StatusCode); } - var baseResponse = JsonConvert.DeserializeObject>(restResponse.Content); + var baseResponse = JsonConvert.DeserializeObject>(restResponse.Content); // First deserialize to the base response baseResponse.RestResponse = restResponse; if (!baseResponse.Success) { @@ -98,6 +104,10 @@ internal async Task> ExecuteRequestAsync(RestRequest return new Tuple(JsonConvert.DeserializeObject(restResponse.Content), restResponse); } + if (!TcaClient.Settings.ThrowOnApiSuccessFailure) + { + return new Tuple(default!, restResponse); + } throw new ApiResponseException(restResponse, "API returned an error"); } diff --git a/TCAdminApiSharp/Entities/User/User.cs b/TCAdminApiSharp/Entities/User/User.cs index 7b53955..dc9e4ff 100644 --- a/TCAdminApiSharp/Entities/User/User.cs +++ b/TCAdminApiSharp/Entities/User/User.cs @@ -5,6 +5,7 @@ using TCAdminApiSharp.Entities.Generic; using Microsoft.Extensions.DependencyInjection; using RestSharp; +using TCAdminApiSharp.Helpers; namespace TCAdminApiSharp.Entities.User { @@ -101,12 +102,39 @@ public void SetPassword(string password) public void Update(Action action) { - throw new NotImplementedException(); + var service = new User(); + action(service); + var putJson = JsonConvert.SerializeObject(service, Constants.IgnoreDefaultValues); + var request = UsersController.GenerateDefaultRequest(); + request.Resource += this.UserId; + request.Method = Method.PUT; + request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); + UsersController.ExecuteBaseResponseRequest(request); } public void Delete() { throw new NotImplementedException(); } + + public bool Suspend(bool recursive = true, bool suspendServices = true) + { + var request = UsersController.GenerateDefaultRequest(); + request.Resource += $"suspend/{this.UserId}"; + request.Method = Method.POST; + request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); + request.AddParameter(nameof(suspendServices), suspendServices, ParameterType.GetOrPost); + return UsersController.ExecuteBaseResponseRequest(request).Success; + } + + public bool Unsuspend(bool recursive = true, bool enableServices = true) + { + var request = UsersController.GenerateDefaultRequest(); + request.Resource += $"unsuspend/{this.UserId}"; + request.Method = Method.POST; + request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); + request.AddParameter(nameof(enableServices), enableServices, ParameterType.GetOrPost); + return UsersController.ExecuteBaseResponseRequest(request).Success; + } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Helpers/Constants.cs b/TCAdminApiSharp/Helpers/Constants.cs index 6fa42e9..348ad40 100644 --- a/TCAdminApiSharp/Helpers/Constants.cs +++ b/TCAdminApiSharp/Helpers/Constants.cs @@ -11,5 +11,10 @@ internal static class Constants NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; + + public static readonly JsonSerializerSettings IgnoreReferenceLoop = new() + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }; } } \ No newline at end of file diff --git a/TCAdminApiSharp/TcaClient.cs b/TCAdminApiSharp/TcaClient.cs index 4e4ebbf..fef330f 100644 --- a/TCAdminApiSharp/TcaClient.cs +++ b/TCAdminApiSharp/TcaClient.cs @@ -12,16 +12,18 @@ public class TcaClient { public readonly string Host; private readonly string _apiKey; - internal static ServiceProvider ServiceProvider; + internal static ServiceProvider ServiceProvider = new ServiceCollection().BuildServiceProvider(); internal readonly RestClient RestClient; public readonly ServicesController ServicesController; public readonly ServersController ServersController; public readonly UsersController UsersController; public readonly TasksController TasksController; + public readonly TcaClientSettings Settings; - public TcaClient(string host, string apiKey, LogEventLevel minimumLogLevel = LogEventLevel.Information) + public TcaClient(string host, string apiKey, TcaClientSettings? clientSettings = null) { - SetupDefaultLogger(minimumLogLevel); + clientSettings ??= TcaClientSettings.Default; + SetupDefaultLogger(clientSettings.MinimumLogLevel); CreateHostBuilder(); if (string.IsNullOrEmpty(host)) { @@ -31,7 +33,8 @@ public TcaClient(string host, string apiKey, LogEventLevel minimumLogLevel = Log { throw new ArgumentException("Parameter is null/empty", nameof(apiKey)); } - + + Settings = clientSettings; Host = host; _apiKey = apiKey; diff --git a/TCAdminApiSharp/TcaClientSettings.cs b/TCAdminApiSharp/TcaClientSettings.cs new file mode 100644 index 0000000..fbaa2df --- /dev/null +++ b/TCAdminApiSharp/TcaClientSettings.cs @@ -0,0 +1,21 @@ +using Serilog.Events; + +namespace TCAdminApiSharp +{ + public class TcaClientSettings + { + public LogEventLevel MinimumLogLevel { get; set; } = LogEventLevel.Information; + public bool ThrowOnApiSuccessFailure { get; set; } = true; + + public bool ThrowOnApiResponseStatusNonComplete { get; set; } = true; + public bool ThrowOnApiStatusCodeNonOk { get; set; } = true; + + public static TcaClientSettings Default => new(); + + public static TcaClientSettings Debug => new() + { + MinimumLogLevel = LogEventLevel.Debug, + ThrowOnApiSuccessFailure = true + }; + } +} \ No newline at end of file From 89db08eac52258ffeabcfe69c20c1c9b941422fd Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 17:58:21 +0000 Subject: [PATCH 15/31] Workflows update --- .../{publish.yml => Publish - Dev.yml} | 15 ++-------- .github/workflows/Publish - Release.yml | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 12 deletions(-) rename .github/workflows/{publish.yml => Publish - Dev.yml} (63%) create mode 100644 .github/workflows/Publish - Release.yml diff --git a/.github/workflows/publish.yml b/.github/workflows/Publish - Dev.yml similarity index 63% rename from .github/workflows/publish.yml rename to .github/workflows/Publish - Dev.yml index 50a5aea..1ed150b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/Publish - Dev.yml @@ -1,8 +1,8 @@ -name: Deploy to Nuget +name: Dev - Build + Deploy on: push: - branches: [ master, dev-* ] + branches: [ dev-*, dev/** ] jobs: build: @@ -19,23 +19,14 @@ jobs: run: dotnet build --no-restore - name: Test run: dotnet test --no-build --verbosity normal - - name: Deploy - Release - uses: alexr03/publish-nuget@master - if: github.ref == 'refs/heads/master' - with: - PROJECT_FILE_PATH: TCAdminApiSharp/TCAdminApiSharp.csproj - NUGET_KEY: ${{secrets.ALEX_NUGET_API_KEY}} - VERSION_REGEX: ^\s*(.*)<\/AssemblyVersion>\s*$ - name: Get DateTime - if: github.ref != 'refs/heads/master' id: datetime run: echo "::set-output name=date::$(date +'%Y%m%d')" - name: Deploy - Dev uses: alexr03/publish-nuget@master - if: github.ref != 'refs/heads/master' with: PROJECT_FILE_PATH: TCAdminApiSharp/TCAdminApiSharp.csproj NUGET_KEY: ${{secrets.ALEX_NUGET_API_KEY}} VERSION_REGEX: ^\s*(.*)<\/AssemblyVersion>\s*$ VERSION_SUFFIX: -dev-${{steps.datetime.outputs.date}}-${{github.run_number}} - TAG_COMMIT: false + TAG_FORMAT: dev-v*-${{steps.datetime.outputs.date}}-${{github.run_number}} \ No newline at end of file diff --git a/.github/workflows/Publish - Release.yml b/.github/workflows/Publish - Release.yml new file mode 100644 index 0000000..aa103ba --- /dev/null +++ b/.github/workflows/Publish - Release.yml @@ -0,0 +1,28 @@ +name: Deploy to Nuget + +on: + push: + branches: [ master ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 5.0.100 + - name: Restore dependencies + run: dotnet restore + - name: Build + run: dotnet build --no-restore + - name: Test + run: dotnet test --no-build --verbosity normal + - name: Deploy - Release + uses: alexr03/publish-nuget@master + with: + PROJECT_FILE_PATH: TCAdminApiSharp/TCAdminApiSharp.csproj + NUGET_KEY: ${{secrets.ALEX_NUGET_API_KEY}} + VERSION_REGEX: ^\s*(.*)<\/AssemblyVersion>\s*$ + TAG_VERSION: release-v*-${{steps.datetime.outputs.date}}-${{github.run_number}} \ No newline at end of file From 6d999a30a6a7ffda979801ff1217185a8270adb0 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 23 Jan 2021 18:06:15 +0000 Subject: [PATCH 16/31] Update release --- .github/workflows/Publish - Release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Publish - Release.yml b/.github/workflows/Publish - Release.yml index aa103ba..cecee1a 100644 --- a/.github/workflows/Publish - Release.yml +++ b/.github/workflows/Publish - Release.yml @@ -1,4 +1,4 @@ -name: Deploy to Nuget +name: Release - Build + Deploy on: push: From 2fe65c3302992e9c9aa5e20b93a46a16afdc2cbb Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Fri, 5 Feb 2021 12:54:50 +0000 Subject: [PATCH 17/31] Asynchronous based. --- TCAdminApiSharp.Tests/ServiceTests.cs | 30 ++++++---------- TCAdminApiSharp/Controllers/BaseController.cs | 20 +++++------ .../Controllers/ServersController.cs | 7 ++-- .../Controllers/ServicesController.cs | 22 ++++++------ .../Controllers/TasksController.cs | 10 +++--- .../Controllers/UsersController.cs | 23 ++++++------ .../Entities/Generic/IPowerable.cs | 6 ++-- .../Entities/Generic/ObjectBase.cs | 5 +-- TCAdminApiSharp/Entities/Server/Server.cs | 7 ++-- TCAdminApiSharp/Entities/Service/Service.cs | 35 ++++++++++--------- TCAdminApiSharp/Entities/Task/Task.cs | 2 +- TCAdminApiSharp/Entities/User/User.cs | 21 +++++------ 12 files changed, 96 insertions(+), 92 deletions(-) diff --git a/TCAdminApiSharp.Tests/ServiceTests.cs b/TCAdminApiSharp.Tests/ServiceTests.cs index d5235ae..6d0fa29 100644 --- a/TCAdminApiSharp.Tests/ServiceTests.cs +++ b/TCAdminApiSharp.Tests/ServiceTests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NUnit.Framework; using Serilog.Events; @@ -20,25 +21,16 @@ public void Setup() } [Test] - public void GetServiceTest() + public async Task GetServiceTest() { - var service = _tcaClient.ServicesController.GetService(2); + var service = await _tcaClient.ServicesController.GetService(2); Assert.AreEqual(2, service.ServiceId); } - - [Test] - public void GetNonExistentServiceTest() - { - Assert.Catch(() => - { - var _ = _tcaClient.ServicesController.GetService(0); - }); - } [Test] - public void GetServicesListTest() + public async Task GetServicesListTest() { - var services = _tcaClient.ServicesController.GetServices(); + var services = await _tcaClient.ServicesController.GetServices(); Assert.AreEqual(2, services.VirtualCount); } @@ -56,10 +48,10 @@ public void GetServiceExceptionTest() } [Test] - public void UpdateServiceTest() + public async Task UpdateServiceTest() { - var service = _tcaClient.ServicesController.GetService(1); - service.Update(x => + var service = await _tcaClient.ServicesController.GetService(1); + await service.Update(x => { x.Slots = 12; x.Executable = "changed.exe"; @@ -69,12 +61,12 @@ public void UpdateServiceTest() } [Test] - public void UpdateServiceExceptionTest() + public async Task UpdateServiceExceptionTest() { - var service = _tcaClient.ServicesController.GetService(2); + var service = await _tcaClient.ServicesController.GetService(2); try { - service.Update(x => + await service.Update(x => { x.Slots = 12; x.Executable = "changed.exe"; diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index 93d27a6..dd0c9df 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -35,37 +35,37 @@ public RestRequest GenerateDefaultRequest() return new(BaseResource); } - public BaseResponse ExecuteBaseResponseRequest(RestRequest request) + public async Task ExecuteBaseResponseRequest(RestRequest request) { - var response = ExecuteRequest(request, out var restResponse); + var response = await ExecuteRequest(request, out var restResponse); response.RestResponse = restResponse; return response; } - public BaseResponse ExecuteBaseResponseRequest(RestRequest request) + public async Task> ExecuteBaseResponseRequest(RestRequest request) { - var response = ExecuteRequest>(request, out var restResponse); + var response = await ExecuteRequest>(request, out var restResponse); response.RestResponse = restResponse; return response; } - public ListResponse ExecuteListResponseRequest(RestRequest request) + public async Task> ExecuteListResponseRequest(RestRequest request) { - var response = ExecuteRequest>(request, out var restResponse); + var response = await ExecuteRequest>(request, out var restResponse); response.RestResponse = restResponse; return response; } - public T ExecuteRequest(RestRequest request) + public async Task ExecuteRequest(RestRequest request) { - return ExecuteRequest(request, out _); + return await ExecuteRequest(request, out _); } - public T ExecuteRequest(RestRequest request, out IRestResponse restResponse) + public Task ExecuteRequest(RestRequest request, out IRestResponse restResponse) { var (t, restResponse2) = ExecuteRequestAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); restResponse = restResponse2; - return t; + return Task.FromResult(t); } public async Task> ExecuteRequestAsync(RestRequest request) diff --git a/TCAdminApiSharp/Controllers/ServersController.cs b/TCAdminApiSharp/Controllers/ServersController.cs index 42d82bd..ed2d14d 100644 --- a/TCAdminApiSharp/Controllers/ServersController.cs +++ b/TCAdminApiSharp/Controllers/ServersController.cs @@ -1,5 +1,6 @@ using System; using System.Net; +using System.Threading.Tasks; using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Server; @@ -25,13 +26,13 @@ public ServersController() : base("api/server") // return ExecuteBaseResponseRequest(request).Result; // } - public Server GetServer(int serverId) + public async Task GetServer(int serverId) { try { var request = GenerateDefaultRequest(); request.Resource += serverId; - return ExecuteBaseResponseRequest(request).Result; + return (await ExecuteBaseResponseRequest(request)).Result; } catch (ApiResponseException e) { @@ -44,7 +45,7 @@ public Server GetServer(int serverId) } } - public ListResponse GetServices() + public Task> GetServices() { var request = GenerateDefaultRequest(); request.Resource += "servers"; diff --git a/TCAdminApiSharp/Controllers/ServicesController.cs b/TCAdminApiSharp/Controllers/ServicesController.cs index 7348543..d5da1d7 100644 --- a/TCAdminApiSharp/Controllers/ServicesController.cs +++ b/TCAdminApiSharp/Controllers/ServicesController.cs @@ -1,5 +1,6 @@ using System; using System.Net; +using System.Threading.Tasks; using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Service; @@ -18,33 +19,34 @@ public ServicesController() : base("api/service") { } - public int CreateService(ServiceBuilder builder) + public async Task CreateService(ServiceBuilder builder) { var body = builder.GenerateRequestBody(); var request = GenerateDefaultRequest(); request.Resource += "create"; request.Method = Method.POST; request.AddParameter("createinfo", body, ParameterType.GetOrPost); - return ExecuteBaseResponseRequest(request).Result; + var response = await ExecuteBaseResponseRequest(request); + return response.Result; } - public ListResponse FindServices(QueryableInfo query) + public async Task> FindServices(QueryableInfo query) { var request = GenerateDefaultRequest(); Logger.Debug(query.BuildQuery()); request.Method = Method.POST; request.Resource += "gameservices"; request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); - return ExecuteListResponseRequest(request); + return await ExecuteListResponseRequest(request); } - public Service GetService(int serviceId) + public async Task GetService(int serviceId) { try { var request = GenerateDefaultRequest(); request.Resource += serviceId; - return ExecuteBaseResponseRequest(request).Result; + return (await ExecuteBaseResponseRequest(request)).Result; } catch (ApiResponseException e) { @@ -57,19 +59,19 @@ public Service GetService(int serviceId) } } - public ListResponse GetServices() + public async Task> GetServices() { var request = GenerateDefaultRequest(); request.Resource += "gameservices"; - return ExecuteListResponseRequest(request); + return await ExecuteListResponseRequest(request); } - public ListResponse GetServicesByBillingId(string billingId) + public Task> GetServicesByBillingId(string billingId) { return FindServices(new QueryableInfo(new WhereList("BillingId", ColumnOperator.Equal, billingId))); } - public ListResponse GetServicesByUserId(int userId) + public Task> GetServicesByUserId(int userId) { return FindServices(new QueryableInfo(new WhereList("UserId", ColumnOperator.Equal, userId))); } diff --git a/TCAdminApiSharp/Controllers/TasksController.cs b/TCAdminApiSharp/Controllers/TasksController.cs index 0fdff4e..ab5eab2 100644 --- a/TCAdminApiSharp/Controllers/TasksController.cs +++ b/TCAdminApiSharp/Controllers/TasksController.cs @@ -1,10 +1,12 @@ using System.Net; +using System.Threading.Tasks; using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Task; using TCAdminApiSharp.Entities.User; using TCAdminApiSharp.Exceptions; using TCAdminApiSharp.Exceptions.API; +using Task = TCAdminApiSharp.Entities.Task.Task; namespace TCAdminApiSharp.Controllers { @@ -14,13 +16,13 @@ public TasksController() : base("api/task") { } - public Task GetTask(int taskId) + public async Task GetTask(int taskId) { try { var request = GenerateDefaultRequest(); request.Resource += taskId; - return ExecuteBaseResponseRequest(request).Result; + return (await ExecuteBaseResponseRequest(request)).Result; } catch (ApiResponseException e) { @@ -33,7 +35,7 @@ public Task GetTask(int taskId) } } - public ListResponse GetPendingTasks(int serverId) + public Task> GetPendingTasks(int serverId) { var request = GenerateDefaultRequest(); request.Resource += "getpendingtasks"; @@ -41,7 +43,7 @@ public ListResponse GetPendingTasks(int serverId) return ExecuteListResponseRequest(request); } - public ListResponse GetTaskSteps(int taskId) + public Task> GetTaskSteps(int taskId) { var request = GenerateDefaultRequest(); request.Resource = "api/taskstep/getsteps"; diff --git a/TCAdminApiSharp/Controllers/UsersController.cs b/TCAdminApiSharp/Controllers/UsersController.cs index 5394878..97c01a3 100644 --- a/TCAdminApiSharp/Controllers/UsersController.cs +++ b/TCAdminApiSharp/Controllers/UsersController.cs @@ -1,4 +1,5 @@ using System.Net; +using System.Threading.Tasks; using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.User; @@ -14,13 +15,14 @@ public UsersController() : base("api/user") { } - public User GetUser(int userId) + public async Task GetUser(int userId) { try { var request = GenerateDefaultRequest(); request.Resource += userId; - return ExecuteBaseResponseRequest(request).Result; + var response = await ExecuteBaseResponseRequest(request); + return response.Result; } catch (ApiResponseException e) { @@ -32,13 +34,14 @@ public User GetUser(int userId) } } - public User GetMe() + public async Task GetMe() { try { var request = GenerateDefaultRequest(); request.Resource += "me"; - return ExecuteBaseResponseRequest(request).Result; + var response = await ExecuteBaseResponseRequest(request); + return response.Result; } catch (ApiResponseException e) { @@ -50,28 +53,28 @@ public User GetMe() } } - public ListResponse FindUsers(QueryableInfo query) + public async Task> FindUsers(QueryableInfo query) { var request = GenerateDefaultRequest(); Logger.Debug(query.BuildQuery()); request.Method = Method.POST; request.Resource += $"users/{TcaClient.GetTokenUserId()}"; request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); - return ExecuteListResponseRequest(request); + return await ExecuteListResponseRequest(request); } - public ListResponse GetMyUsers() + public async Task> GetMyUsers() { var request = GenerateDefaultRequest(); request.Resource += "myusers"; - return ExecuteListResponseRequest(request); + return await ExecuteListResponseRequest(request); } - public ListResponse GetUsers() + public async Task> GetUsers() { var request = GenerateDefaultRequest(); request.Resource += $"users/{TcaClient.GetTokenUserId()}"; - return ExecuteListResponseRequest(request); + return await ExecuteListResponseRequest(request); } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Generic/IPowerable.cs b/TCAdminApiSharp/Entities/Generic/IPowerable.cs index 79eef94..e7e0961 100644 --- a/TCAdminApiSharp/Entities/Generic/IPowerable.cs +++ b/TCAdminApiSharp/Entities/Generic/IPowerable.cs @@ -4,8 +4,8 @@ namespace TCAdminApiSharp.Entities.Generic { public interface IPowerable { - public void Start(string reason = ""); - public void Restart(string reason = ""); - public void Stop(string reason = ""); + public Task Start(string reason = ""); + public Task Restart(string reason = ""); + public Task Stop(string reason = ""); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Generic/ObjectBase.cs b/TCAdminApiSharp/Entities/Generic/ObjectBase.cs index cc9a736..0a319ec 100644 --- a/TCAdminApiSharp/Entities/Generic/ObjectBase.cs +++ b/TCAdminApiSharp/Entities/Generic/ObjectBase.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Newtonsoft.Json; namespace TCAdminApiSharp.Entities.Generic @@ -18,8 +19,8 @@ public class ObjectBase public interface IObjectBaseCrud { - public void Update(Action action); + public Task Update(Action action); - public void Delete(); + public Task Delete(); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Server/Server.cs b/TCAdminApiSharp/Entities/Server/Server.cs index cb02735..b31bd42 100644 --- a/TCAdminApiSharp/Entities/Server/Server.cs +++ b/TCAdminApiSharp/Entities/Server/Server.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Newtonsoft.Json; using RestSharp; using Microsoft.Extensions.DependencyInjection; @@ -241,7 +242,7 @@ public class Server : ObjectBase, IObjectBaseCrud [JsonProperty("DCDownloadPassword")] public string DCDownloadPassword { get; set; } - public void Update(Action action) + public async Task Update(Action action) { var server = new Server(); action(server); @@ -250,10 +251,10 @@ public void Update(Action action) request.Resource += this.ServerId; request.Method = Method.PUT; request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); - ServersController.ExecuteBaseResponseRequest(request); + return (await ServersController.ExecuteBaseResponseRequest(request)).Success; } - public void Delete() + public Task Delete() { throw new NotImplementedException(); } diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index 969238b..7f23c64 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using RestSharp; @@ -241,10 +242,10 @@ public class Service : ObjectBase, IObjectBaseCrud, IPowerable [JsonProperty("Notes")] public string Notes { get; set; } - [JsonIgnore] public User.User User => ServicesController.TcaClient.UsersController.GetUser(this.UserId); - [JsonIgnore] public Server.Server Server => ServicesController.TcaClient.ServersController.GetServer(this.ServerId); + [JsonIgnore] public User.User User => ServicesController.TcaClient.UsersController.GetUser(this.UserId).GetAwaiter().GetResult(); + [JsonIgnore] public Server.Server Server => ServicesController.TcaClient.ServersController.GetServer(this.ServerId).GetAwaiter().GetResult(); - public void Update(Action action) + public async Task Update(Action action) { var service = new Service(); action(service); @@ -253,16 +254,16 @@ public void Update(Action action) request.Resource += this.ServiceId; request.Method = Method.PUT; request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); - ServicesController.ExecuteBaseResponseRequest(request); + return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; } - public void Delete() + public Task Delete() { // todo: Luis hurry up implement pls throw new NotImplementedException(); } - public void Start(string reason = "") + public async Task Start(string reason = "") { var request = ServicesController.GenerateDefaultRequest(); request.Resource += $"start/{this.ServiceId}"; @@ -271,10 +272,10 @@ public void Start(string reason = "") { request.AddParameter("reason", reason); } - ServicesController.ExecuteBaseResponseRequest(request); + return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; } - public void Restart(string reason = "") + public async Task Restart(string reason = "") { var request = ServicesController.GenerateDefaultRequest(); request.Resource += $"restart/{this.ServiceId}"; @@ -283,10 +284,10 @@ public void Restart(string reason = "") { request.AddParameter("reason", reason); } - ServicesController.ExecuteBaseResponseRequest(request); + return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; } - public void Stop(string reason = "") + public async Task Stop(string reason = "") { var request = ServicesController.GenerateDefaultRequest(); request.Resource += $"stop/{this.ServiceId}"; @@ -295,31 +296,31 @@ public void Stop(string reason = "") { request.AddParameter("reason", reason); } - ServicesController.ExecuteBaseResponseRequest(request); + return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; } - public void Configure() + public async Task Configure() { var request = ServicesController.GenerateDefaultRequest(); request.Resource += $"configure/{this.ServiceId}"; request.Method = Method.POST; - ServicesController.ExecuteBaseResponseRequest(request); + return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; } - public bool Suspend() + public async Task Suspend() { var request = ServicesController.GenerateDefaultRequest(); request.Resource += $"suspend/{this.ServiceId}"; request.Method = Method.POST; - return ServicesController.ExecuteBaseResponseRequest(request).Success; + return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; } - public bool Unsuspend() + public async Task Unsuspend() { var request = ServicesController.GenerateDefaultRequest(); request.Resource += $"unsuspend/{this.ServiceId}"; request.Method = Method.POST; - return ServicesController.ExecuteBaseResponseRequest(request).Success; + return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Task/Task.cs b/TCAdminApiSharp/Entities/Task/Task.cs index 905c712..e251d7e 100644 --- a/TCAdminApiSharp/Entities/Task/Task.cs +++ b/TCAdminApiSharp/Entities/Task/Task.cs @@ -54,7 +54,7 @@ public class Task : ObjectBase [JsonProperty("RedirectUrl")] public string RedirectUrl { get; set; } - [JsonIgnore] public IEnumerable Steps => (List) TasksController.GetTaskSteps(this.TaskId).Result; + [JsonIgnore] public IEnumerable Steps => (List) TasksController.GetTaskSteps(this.TaskId).GetAwaiter().GetResult().Result; [JsonIgnore] public TaskStep CurrentStep diff --git a/TCAdminApiSharp/Entities/User/User.cs b/TCAdminApiSharp/Entities/User/User.cs index dc9e4ff..c9143a0 100644 --- a/TCAdminApiSharp/Entities/User/User.cs +++ b/TCAdminApiSharp/Entities/User/User.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using Newtonsoft.Json; using TCAdminApiSharp.Controllers; using TCAdminApiSharp.Entities.Generic; @@ -89,18 +90,18 @@ public class User : ObjectBase, IObjectBaseCrud [JsonProperty("UserType")] public UserType UserType { get; set; } [JsonIgnore] public IList Services => - UsersController.TcaClient.ServicesController.GetServicesByUserId(this.UserId).Result; + UsersController.TcaClient.ServicesController.GetServicesByUserId(this.UserId).GetAwaiter().GetResult().Result; - public void SetPassword(string password) + public async Task SetPassword(string password) { var request = UsersController.GenerateDefaultRequest(); request.Resource += $"setpassword/{UserId}"; request.Method = Method.POST; request.AddParameter("password", password, ParameterType.GetOrPost); - UsersController.ExecuteBaseResponseRequest(request); + return (await UsersController.ExecuteBaseResponseRequest(request)).Success; } - public void Update(Action action) + public async Task Update(Action action) { var service = new User(); action(service); @@ -109,32 +110,32 @@ public void Update(Action action) request.Resource += this.UserId; request.Method = Method.PUT; request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); - UsersController.ExecuteBaseResponseRequest(request); + return (await UsersController.ExecuteBaseResponseRequest(request)).Success; } - public void Delete() + public Task Delete() { throw new NotImplementedException(); } - public bool Suspend(bool recursive = true, bool suspendServices = true) + public async Task Suspend(bool recursive = true, bool suspendServices = true) { var request = UsersController.GenerateDefaultRequest(); request.Resource += $"suspend/{this.UserId}"; request.Method = Method.POST; request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); request.AddParameter(nameof(suspendServices), suspendServices, ParameterType.GetOrPost); - return UsersController.ExecuteBaseResponseRequest(request).Success; + return (await UsersController.ExecuteBaseResponseRequest(request)).Success; } - public bool Unsuspend(bool recursive = true, bool enableServices = true) + public async Task Unsuspend(bool recursive = true, bool enableServices = true) { var request = UsersController.GenerateDefaultRequest(); request.Resource += $"unsuspend/{this.UserId}"; request.Method = Method.POST; request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); request.AddParameter(nameof(enableServices), enableServices, ParameterType.GetOrPost); - return UsersController.ExecuteBaseResponseRequest(request).Success; + return (await UsersController.ExecuteBaseResponseRequest(request)).Success; } } } \ No newline at end of file From a38cf1ba92b9a5f04d168b657269a31e9ba5a586 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Fri, 5 Feb 2021 13:29:01 +0000 Subject: [PATCH 18/31] Remove blocker --- TCAdminApiSharp/Controllers/BaseController.cs | 32 ++++++------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index dd0c9df..1005f35 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -37,43 +37,29 @@ public RestRequest GenerateDefaultRequest() public async Task ExecuteBaseResponseRequest(RestRequest request) { - var response = await ExecuteRequest(request, out var restResponse); - response.RestResponse = restResponse; - return response; + var (baseResponse, restResponse) = await ExecuteRequestAsync(request); + baseResponse.RestResponse = restResponse; + return baseResponse; } public async Task> ExecuteBaseResponseRequest(RestRequest request) { - var response = await ExecuteRequest>(request, out var restResponse); - response.RestResponse = restResponse; - return response; + var (item1, item2) = await ExecuteRequestAsync>(request); + item1.RestResponse = item2; + return item1; } public async Task> ExecuteListResponseRequest(RestRequest request) { - var response = await ExecuteRequest>(request, out var restResponse); - response.RestResponse = restResponse; - return response; - } - - public async Task ExecuteRequest(RestRequest request) - { - return await ExecuteRequest(request, out _); - } - - public Task ExecuteRequest(RestRequest request, out IRestResponse restResponse) - { - var (t, restResponse2) = ExecuteRequestAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); - restResponse = restResponse2; - return Task.FromResult(t); + var (baseResponse, restResponse) = await ExecuteRequestAsync>(request); + baseResponse.RestResponse = restResponse; + return baseResponse; } public async Task> ExecuteRequestAsync(RestRequest request) { - Logger.Verbose(JsonConvert.SerializeObject(request, Constants.IgnoreReferenceLoop)); Logger.Debug($"Request URL [{request.Method}]: {TcaClient.RestClient.BuildUri(request)}"); var restResponse = await TcaClient.RestClient.ExecuteAsync(request); - Logger.Verbose(JsonConvert.SerializeObject(restResponse, Constants.IgnoreReferenceLoop)); Logger.Debug("Response Status: " + restResponse.ResponseStatus); Logger.Debug("Status Code: " + restResponse.StatusCode); if (restResponse.ResponseStatus != ResponseStatus.Completed) From b666f98617a9ea111a2f5643cf2cc8f50fdd34f6 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Fri, 5 Feb 2021 13:37:48 +0000 Subject: [PATCH 19/31] Update Publish - Dev.yml --- .github/workflows/Publish - Dev.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Publish - Dev.yml b/.github/workflows/Publish - Dev.yml index 1ed150b..d4136d7 100644 --- a/.github/workflows/Publish - Dev.yml +++ b/.github/workflows/Publish - Dev.yml @@ -29,4 +29,4 @@ jobs: NUGET_KEY: ${{secrets.ALEX_NUGET_API_KEY}} VERSION_REGEX: ^\s*(.*)<\/AssemblyVersion>\s*$ VERSION_SUFFIX: -dev-${{steps.datetime.outputs.date}}-${{github.run_number}} - TAG_FORMAT: dev-v*-${{steps.datetime.outputs.date}}-${{github.run_number}} \ No newline at end of file + TAG_FORMAT: dev-v* From 478861a41050e0a96162273801a8d935f49183f3 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 20 Feb 2021 02:17:38 +0000 Subject: [PATCH 20/31] Allow controller access statically --- .../Controllers/UsersController.cs | 2 +- TCAdminApiSharp/Entities/Server/Server.cs | 6 ++-- TCAdminApiSharp/Entities/Service/Service.cs | 34 +++++++++---------- TCAdminApiSharp/Entities/Task/Task.cs | 16 ++++----- TCAdminApiSharp/Entities/Task/TaskStep.cs | 8 ++++- TCAdminApiSharp/Entities/User/User.cs | 20 +++++------ 6 files changed, 46 insertions(+), 40 deletions(-) diff --git a/TCAdminApiSharp/Controllers/UsersController.cs b/TCAdminApiSharp/Controllers/UsersController.cs index 97c01a3..36f4062 100644 --- a/TCAdminApiSharp/Controllers/UsersController.cs +++ b/TCAdminApiSharp/Controllers/UsersController.cs @@ -62,7 +62,7 @@ public async Task> FindUsers(QueryableInfo query) request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); return await ExecuteListResponseRequest(request); } - + public async Task> GetMyUsers() { var request = GenerateDefaultRequest(); diff --git a/TCAdminApiSharp/Entities/Server/Server.cs b/TCAdminApiSharp/Entities/Server/Server.cs index b31bd42..e3db825 100644 --- a/TCAdminApiSharp/Entities/Server/Server.cs +++ b/TCAdminApiSharp/Entities/Server/Server.cs @@ -11,7 +11,7 @@ namespace TCAdminApiSharp.Entities.Server { public class Server : ObjectBase, IObjectBaseCrud { - [JsonIgnore] public readonly ServersController ServersController = + [JsonIgnore] public static readonly ServersController Controller = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); [JsonProperty("DisableNewServices")] public bool DisableNewServices { get; set; } @@ -247,11 +247,11 @@ public async Task Update(Action action) var server = new Server(); action(server); var putJson = JsonConvert.SerializeObject(server, Constants.IgnoreDefaultValues); - var request = ServersController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += this.ServerId; request.Method = Method.PUT; request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); - return (await ServersController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public Task Delete() diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index 7f23c64..1746625 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -15,7 +15,7 @@ namespace TCAdminApiSharp.Entities.Service public class Service : ObjectBase, IObjectBaseCrud, IPowerable { [JsonIgnore] - public readonly ServicesController ServicesController = + public static readonly ServicesController Controller = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); [JsonProperty("EnableGameSwitching")] public bool EnableGameSwitching { get; set; } @@ -242,19 +242,19 @@ public class Service : ObjectBase, IObjectBaseCrud, IPowerable [JsonProperty("Notes")] public string Notes { get; set; } - [JsonIgnore] public User.User User => ServicesController.TcaClient.UsersController.GetUser(this.UserId).GetAwaiter().GetResult(); - [JsonIgnore] public Server.Server Server => ServicesController.TcaClient.ServersController.GetServer(this.ServerId).GetAwaiter().GetResult(); + [JsonIgnore] public User.User User => Controller.TcaClient.UsersController.GetUser(this.UserId).GetAwaiter().GetResult(); + [JsonIgnore] public Server.Server Server => Controller.TcaClient.ServersController.GetServer(this.ServerId).GetAwaiter().GetResult(); public async Task Update(Action action) { var service = new Service(); action(service); var putJson = JsonConvert.SerializeObject(service, Constants.IgnoreDefaultValues); - var request = ServicesController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += this.ServiceId; request.Method = Method.PUT; request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); - return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public Task Delete() @@ -265,62 +265,62 @@ public Task Delete() public async Task Start(string reason = "") { - var request = ServicesController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"start/{this.ServiceId}"; request.Method = Method.POST; if (!string.IsNullOrEmpty(reason)) { request.AddParameter("reason", reason); } - return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public async Task Restart(string reason = "") { - var request = ServicesController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"restart/{this.ServiceId}"; request.Method = Method.POST; if (!string.IsNullOrEmpty(reason)) { request.AddParameter("reason", reason); } - return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public async Task Stop(string reason = "") { - var request = ServicesController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"stop/{this.ServiceId}"; request.Method = Method.POST; if (!string.IsNullOrEmpty(reason)) { request.AddParameter("reason", reason); } - return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public async Task Configure() { - var request = ServicesController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"configure/{this.ServiceId}"; request.Method = Method.POST; - return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public async Task Suspend() { - var request = ServicesController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"suspend/{this.ServiceId}"; request.Method = Method.POST; - return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public async Task Unsuspend() { - var request = ServicesController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"unsuspend/{this.ServiceId}"; request.Method = Method.POST; - return (await ServicesController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Task/Task.cs b/TCAdminApiSharp/Entities/Task/Task.cs index e251d7e..205f9b0 100644 --- a/TCAdminApiSharp/Entities/Task/Task.cs +++ b/TCAdminApiSharp/Entities/Task/Task.cs @@ -11,7 +11,7 @@ namespace TCAdminApiSharp.Entities.Task { public class Task : ObjectBase { - [JsonIgnore] public readonly TasksController TasksController = + [JsonIgnore] public static readonly TasksController Controller = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); [JsonProperty("TaskId")] public int TaskId { get; set; } @@ -54,7 +54,7 @@ public class Task : ObjectBase [JsonProperty("RedirectUrl")] public string RedirectUrl { get; set; } - [JsonIgnore] public IEnumerable Steps => (List) TasksController.GetTaskSteps(this.TaskId).GetAwaiter().GetResult().Result; + [JsonIgnore] public IEnumerable Steps => (List) Controller.GetTaskSteps(this.TaskId).GetAwaiter().GetResult().Result; [JsonIgnore] public TaskStep CurrentStep @@ -62,20 +62,20 @@ public TaskStep CurrentStep get { return Steps.FirstOrDefault(x => x.StepId == this.CurrentStepId) ?? throw new InvalidOperationException(); } } - public void Start() + public async System.Threading.Tasks.Task Start() { - var request = TasksController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"start/{this.TaskId}"; request.Method = Method.POST; - TasksController.ExecuteBaseResponseRequest(request); + await Controller.ExecuteBaseResponseRequest(request); } - public void Cancel() + public async System.Threading.Tasks.Task Cancel() { - var request = TasksController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"cancel/{this.TaskId}"; request.Method = Method.POST; - TasksController.ExecuteBaseResponseRequest(request); + await Controller.ExecuteBaseResponseRequest(request); } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Task/TaskStep.cs b/TCAdminApiSharp/Entities/Task/TaskStep.cs index 83d04ee..af67ce7 100644 --- a/TCAdminApiSharp/Entities/Task/TaskStep.cs +++ b/TCAdminApiSharp/Entities/Task/TaskStep.cs @@ -1,11 +1,17 @@ using System; using System.Collections.Generic; using Newtonsoft.Json; +using TCAdminApiSharp.Controllers; +using TCAdminApiSharp.Entities.Generic; +using Microsoft.Extensions.DependencyInjection; namespace TCAdminApiSharp.Entities.Task { - public class TaskStep + public class TaskStep : ObjectBase { + [JsonIgnore] public static readonly TasksController Controller = + TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); + [JsonProperty("ModuleId")] public string ModuleId { get; set; } diff --git a/TCAdminApiSharp/Entities/User/User.cs b/TCAdminApiSharp/Entities/User/User.cs index c9143a0..ba4cead 100644 --- a/TCAdminApiSharp/Entities/User/User.cs +++ b/TCAdminApiSharp/Entities/User/User.cs @@ -12,7 +12,7 @@ namespace TCAdminApiSharp.Entities.User { public class User : ObjectBase, IObjectBaseCrud { - [JsonIgnore] public readonly UsersController UsersController = + [JsonIgnore] public static readonly UsersController Controller = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); [JsonProperty("UserId")] public int UserId { get; set; } @@ -90,15 +90,15 @@ public class User : ObjectBase, IObjectBaseCrud [JsonProperty("UserType")] public UserType UserType { get; set; } [JsonIgnore] public IList Services => - UsersController.TcaClient.ServicesController.GetServicesByUserId(this.UserId).GetAwaiter().GetResult().Result; + Controller.TcaClient.ServicesController.GetServicesByUserId(this.UserId).GetAwaiter().GetResult().Result; public async Task SetPassword(string password) { - var request = UsersController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"setpassword/{UserId}"; request.Method = Method.POST; request.AddParameter("password", password, ParameterType.GetOrPost); - return (await UsersController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public async Task Update(Action action) @@ -106,11 +106,11 @@ public async Task Update(Action action) var service = new User(); action(service); var putJson = JsonConvert.SerializeObject(service, Constants.IgnoreDefaultValues); - var request = UsersController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += this.UserId; request.Method = Method.PUT; request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); - return (await UsersController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public Task Delete() @@ -120,22 +120,22 @@ public Task Delete() public async Task Suspend(bool recursive = true, bool suspendServices = true) { - var request = UsersController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"suspend/{this.UserId}"; request.Method = Method.POST; request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); request.AddParameter(nameof(suspendServices), suspendServices, ParameterType.GetOrPost); - return (await UsersController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public async Task Unsuspend(bool recursive = true, bool enableServices = true) { - var request = UsersController.GenerateDefaultRequest(); + var request = Controller.GenerateDefaultRequest(); request.Resource += $"unsuspend/{this.UserId}"; request.Method = Method.POST; request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); request.AddParameter(nameof(enableServices), enableServices, ParameterType.GetOrPost); - return (await UsersController.ExecuteBaseResponseRequest(request)).Success; + return (await Controller.ExecuteBaseResponseRequest(request)).Success; } } } \ No newline at end of file From e3c7d427b1a1aa19453dca66a0f728a0f14dd684 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sat, 20 Feb 2021 02:22:48 +0000 Subject: [PATCH 21/31] Internal Logger --- TCAdminApiSharp/Controllers/BaseController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index 1005f35..48e6e46 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -17,7 +17,7 @@ public class BaseController public readonly TcaClient TcaClient = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); public readonly string BaseResource; - public readonly ILogger Logger; + internal readonly ILogger Logger; protected BaseController(string baseResource) { From 0237670a357d7a510d55a3135e76b70ffb8db07c Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Mon, 1 Mar 2021 17:52:29 +0000 Subject: [PATCH 22/31] Improvements --- TCAdminApiSharp/Controllers/BaseController.cs | 52 ++++++++++----- .../Controllers/ServersController.cs | 14 ++--- .../Controllers/ServicesController.cs | 8 +-- .../Controllers/TasksController.cs | 4 +- .../Controllers/UsersController.cs | 19 +++--- .../Converters/QueryOperationJsonConverter.cs | 33 ---------- TCAdminApiSharp/Entities/API/BaseResponse.cs | 6 +- TCAdminApiSharp/Entities/API/ErrorResponse.cs | 3 +- TCAdminApiSharp/Entities/API/ListResponse.cs | 3 +- .../Entities/Billing/BillingStatus.cs | 2 +- .../Entities/Generic/ObjectBase.cs | 2 +- TCAdminApiSharp/Entities/Server/Server.cs | 4 +- TCAdminApiSharp/Entities/Service/Service.cs | 51 +++++++-------- .../Entities/Service/ServiceBuilder.cs | 12 ++-- .../Entities/Service/ServiceStartup.cs | 2 +- .../Entities/Service/ServiceStatus.cs | 2 +- TCAdminApiSharp/Entities/Task/Task.cs | 17 +++-- TCAdminApiSharp/Entities/Task/TaskStatus.cs | 2 +- TCAdminApiSharp/Entities/Task/TaskStep.cs | 46 +++++--------- TCAdminApiSharp/Entities/User/User.cs | 17 ++--- TCAdminApiSharp/Entities/User/UserType.cs | 2 +- .../Exceptions/API/ApiRequestException.cs | 15 ++--- .../Exceptions/API/ApiResponseException.cs | 1 - .../Exceptions/NotFoundException.cs | 12 ++-- TCAdminApiSharp/Helpers/Constants.cs | 4 +- TCAdminApiSharp/Querying/IQueryOperation.cs | 6 +- .../Querying/Operations/FilterList.cs | 62 ++++++++++++++++++ .../Querying/Operations/OrderList.cs | 28 +++++++-- .../Querying/Operations/WhereList.cs | 63 ++++++++++++------- TCAdminApiSharp/Querying/QueryableInfo.cs | 15 ++--- .../Querying/Structs/FilterInfo.cs | 12 ++++ TCAdminApiSharp/Querying/Structs/OrderInfo.cs | 8 +-- TCAdminApiSharp/Querying/Structs/WhereInfo.cs | 2 +- TCAdminApiSharp/TCAdminApiSharp.csproj | 4 ++ TCAdminApiSharp/TcaClient.cs | 27 ++++---- TCAdminApiSharp/TcaClientSettings.cs | 2 +- 36 files changed, 320 insertions(+), 242 deletions(-) delete mode 100644 TCAdminApiSharp/Converters/QueryOperationJsonConverter.cs create mode 100644 TCAdminApiSharp/Querying/Operations/FilterList.cs create mode 100644 TCAdminApiSharp/Querying/Structs/FilterInfo.cs diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index 48e6e46..51d6678 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -4,11 +4,13 @@ using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using RestSharp; using Serilog; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Exceptions.API; using TCAdminApiSharp.Helpers; +using TCAdminApiSharp.Querying; namespace TCAdminApiSharp.Controllers { @@ -16,6 +18,7 @@ public class BaseController { public readonly TcaClient TcaClient = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); + public readonly string BaseResource; internal readonly ILogger Logger; @@ -24,10 +27,7 @@ protected BaseController(string baseResource) Logger = Log.ForContext(GetType()); BaseResource = baseResource; - if (!baseResource.EndsWith("/")) - { - BaseResource = baseResource + "/"; - } + if (!baseResource.EndsWith("/")) BaseResource = baseResource + "/"; } public RestRequest GenerateDefaultRequest() @@ -35,6 +35,28 @@ public RestRequest GenerateDefaultRequest() return new(BaseResource); } + public async Task> AdvancedRequest(string resource, QueryableInfo query, Method method = Method.POST) + { + var request = GenerateDefaultRequest(); + // Logger.Debug(query.BuildQuery()); + request.Method = method; + request.Resource += resource; + // request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); + query.BuildQuery(request); + return await ExecuteBaseResponseRequest(request); + } + + public async Task> AdvancedListRequest(string resource, QueryableInfo query, Method method = Method.POST) + { + var request = GenerateDefaultRequest(); + // Logger.Debug(query.BuildQuery()); + request.Method = method; + request.Resource += resource; + // request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); + query.BuildQuery(request); + return await ExecuteListResponseRequest(request); + } + public async Task ExecuteBaseResponseRequest(RestRequest request) { var (baseResponse, restResponse) = await ExecuteRequestAsync(request); @@ -48,7 +70,7 @@ public async Task> ExecuteBaseResponseRequest(RestRequest req item1.RestResponse = item2; return item1; } - + public async Task> ExecuteListResponseRequest(RestRequest request) { var (baseResponse, restResponse) = await ExecuteRequestAsync>(request); @@ -62,38 +84,38 @@ public async Task> ExecuteRequestAsync(RestRequest re var restResponse = await TcaClient.RestClient.ExecuteAsync(request); Logger.Debug("Response Status: " + restResponse.ResponseStatus); Logger.Debug("Status Code: " + restResponse.StatusCode); + Logger.Debug("Parameters:"); + foreach (var requestParameter in request.Parameters) + { + Logger.Debug(requestParameter.ToString()); + } if (restResponse.ResponseStatus != ResponseStatus.Completed) { if (!TcaClient.Settings.ThrowOnApiResponseStatusNonComplete) - { return new Tuple(default!, restResponse); - } throw new ApiResponseException(restResponse, "Response Status is: " + restResponse.ResponseStatus); } if (restResponse.StatusCode != HttpStatusCode.OK) { if (!TcaClient.Settings.ThrowOnApiStatusCodeNonOk) - { return new Tuple(default!, restResponse); - } throw new ApiResponseException(restResponse, "Status code is: " + restResponse.StatusCode); } - var baseResponse = JsonConvert.DeserializeObject>(restResponse.Content); // First deserialize to the base response + var baseResponse = + JsonConvert.DeserializeObject>(restResponse + .Content); // First deserialize to the base response baseResponse.RestResponse = restResponse; if (!baseResponse.Success) { var tType = typeof(T); if (tType.GenericTypeArguments.Contains(baseResponse.Result.GetType())) - { - return new Tuple(JsonConvert.DeserializeObject(restResponse.Content), restResponse); - } + return new Tuple(JsonConvert.DeserializeObject(restResponse.Content), + restResponse); if (!TcaClient.Settings.ThrowOnApiSuccessFailure) - { return new Tuple(default!, restResponse); - } throw new ApiResponseException(restResponse, "API returned an error"); } diff --git a/TCAdminApiSharp/Controllers/ServersController.cs b/TCAdminApiSharp/Controllers/ServersController.cs index ed2d14d..b36684a 100644 --- a/TCAdminApiSharp/Controllers/ServersController.cs +++ b/TCAdminApiSharp/Controllers/ServersController.cs @@ -1,7 +1,5 @@ -using System; -using System.Net; +using System.Net; using System.Threading.Tasks; -using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Server; using TCAdminApiSharp.Entities.Service; @@ -25,7 +23,7 @@ public ServersController() : base("api/server") // request.AddParameter("createinfo", body, ParameterType.GetOrPost); // return ExecuteBaseResponseRequest(request).Result; // } - + public async Task GetServer(int serverId) { try @@ -37,15 +35,13 @@ public async Task GetServer(int serverId) catch (ApiResponseException e) { if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - { - throw new NotFoundException(typeof(Service), e, new []{serverId}); - } + throw new NotFoundException(typeof(Service), e, new[] {serverId}); throw; } } - - public Task> GetServices() + + public Task> GetServers() { var request = GenerateDefaultRequest(); request.Resource += "servers"; diff --git a/TCAdminApiSharp/Controllers/ServicesController.cs b/TCAdminApiSharp/Controllers/ServicesController.cs index d5da1d7..b3fc861 100644 --- a/TCAdminApiSharp/Controllers/ServicesController.cs +++ b/TCAdminApiSharp/Controllers/ServicesController.cs @@ -1,6 +1,7 @@ using System; using System.Net; using System.Threading.Tasks; +using Newtonsoft.Json.Linq; using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Service; @@ -33,10 +34,11 @@ public async Task CreateService(ServiceBuilder builder) public async Task> FindServices(QueryableInfo query) { var request = GenerateDefaultRequest(); - Logger.Debug(query.BuildQuery()); + // Logger.Debug(query.BuildQuery()); request.Method = Method.POST; request.Resource += "gameservices"; - request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); + // request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); + query.BuildQuery(request); return await ExecuteListResponseRequest(request); } @@ -51,9 +53,7 @@ public async Task GetService(int serviceId) catch (ApiResponseException e) { if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - { throw new NotFoundException(typeof(Service), e, new[] {serviceId}); - } throw; } diff --git a/TCAdminApiSharp/Controllers/TasksController.cs b/TCAdminApiSharp/Controllers/TasksController.cs index ab5eab2..eb3a512 100644 --- a/TCAdminApiSharp/Controllers/TasksController.cs +++ b/TCAdminApiSharp/Controllers/TasksController.cs @@ -27,9 +27,7 @@ public async Task GetTask(int taskId) catch (ApiResponseException e) { if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - { throw new NotFoundException(typeof(Task), e, new[] {taskId}); - } throw; } @@ -42,7 +40,7 @@ public Task> GetPendingTasks(int serverId) request.AddParameter("serverId", serverId, ParameterType.QueryString); return ExecuteListResponseRequest(request); } - + public Task> GetTaskSteps(int taskId) { var request = GenerateDefaultRequest(); diff --git a/TCAdminApiSharp/Controllers/UsersController.cs b/TCAdminApiSharp/Controllers/UsersController.cs index 36f4062..add77d1 100644 --- a/TCAdminApiSharp/Controllers/UsersController.cs +++ b/TCAdminApiSharp/Controllers/UsersController.cs @@ -14,7 +14,7 @@ public class UsersController : BaseController public UsersController() : base("api/user") { } - + public async Task GetUser(int userId) { try @@ -27,13 +27,11 @@ public async Task GetUser(int userId) catch (ApiResponseException e) { if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - { - throw new NotFoundException(typeof(User), e, new []{userId}); - } + throw new NotFoundException(typeof(User), e, new[] {userId}); throw; } } - + public async Task GetMe() { try @@ -46,9 +44,7 @@ public async Task GetMe() catch (ApiResponseException e) { if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - { - throw new NotFoundException(typeof(User), e, new []{TcaClient.GetTokenUserId()}); - } + throw new NotFoundException(typeof(User), e, new[] {TcaClient.GetTokenUserId()}); throw; } } @@ -56,10 +52,11 @@ public async Task GetMe() public async Task> FindUsers(QueryableInfo query) { var request = GenerateDefaultRequest(); - Logger.Debug(query.BuildQuery()); + // Logger.Debug(query.BuildQuery(request)); request.Method = Method.POST; request.Resource += $"users/{TcaClient.GetTokenUserId()}"; - request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); + // request.AddParameter("queryInfo", query.BuildQuery(request), ParameterType.GetOrPost); + query.BuildQuery(request); return await ExecuteListResponseRequest(request); } @@ -69,7 +66,7 @@ public async Task> GetMyUsers() request.Resource += "myusers"; return await ExecuteListResponseRequest(request); } - + public async Task> GetUsers() { var request = GenerateDefaultRequest(); diff --git a/TCAdminApiSharp/Converters/QueryOperationJsonConverter.cs b/TCAdminApiSharp/Converters/QueryOperationJsonConverter.cs deleted file mode 100644 index 39e399a..0000000 --- a/TCAdminApiSharp/Converters/QueryOperationJsonConverter.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using Newtonsoft.Json; -using TCAdminApiSharp.Querying; - -namespace TCAdminApiSharp.Converters -{ - public class QueryOperationJsonConverter : JsonConverter - { - public override bool CanConvert(Type objectType) - { - return true; - } - - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) - { - if (value != null && value.GetType().IsAssignableTo(typeof(IQueryOperation))) - { - writer.WriteValue(((IQueryOperation)value).GenerateQuery()); - } - else - { - throw new Exception($"Cannot convert {value?.GetType()} to {typeof(IQueryOperation)}"); - } - } - - public override bool CanRead => false; - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/API/BaseResponse.cs b/TCAdminApiSharp/Entities/API/BaseResponse.cs index 34596a8..a306650 100644 --- a/TCAdminApiSharp/Entities/API/BaseResponse.cs +++ b/TCAdminApiSharp/Entities/API/BaseResponse.cs @@ -9,18 +9,18 @@ public class BaseResponse [JsonProperty("Success")] public bool Success { get; private set; } = true; [JsonProperty("Message")] public string? Message { get; private set; } - + public IRestResponse RestResponse { get; internal set; } internal BaseResponse() { } } - + public class BaseResponse : BaseResponse { [JsonProperty("Result")] public T Result { get; private set; } - + internal BaseResponse() { } diff --git a/TCAdminApiSharp/Entities/API/ErrorResponse.cs b/TCAdminApiSharp/Entities/API/ErrorResponse.cs index 5c4422e..ed3ce77 100644 --- a/TCAdminApiSharp/Entities/API/ErrorResponse.cs +++ b/TCAdminApiSharp/Entities/API/ErrorResponse.cs @@ -16,7 +16,8 @@ internal ErrorResponse(IRestResponse restResponse) { throw new Exception("Couldn't parse API error to object!", e); } - this.RestResponse = restResponse; + + RestResponse = restResponse; } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/API/ListResponse.cs b/TCAdminApiSharp/Entities/API/ListResponse.cs index d7ecf3c..508857a 100644 --- a/TCAdminApiSharp/Entities/API/ListResponse.cs +++ b/TCAdminApiSharp/Entities/API/ListResponse.cs @@ -8,6 +8,7 @@ public class ListResponse : BaseResponse> /// /// Only returns when "RowCount" was specified in the request. /// - [JsonProperty("VirtualCount")] public int VirtualCount { get; internal set; } + [JsonProperty("VirtualCount")] + public int VirtualCount { get; internal set; } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Billing/BillingStatus.cs b/TCAdminApiSharp/Entities/Billing/BillingStatus.cs index 9cf3823..3b8734a 100644 --- a/TCAdminApiSharp/Entities/Billing/BillingStatus.cs +++ b/TCAdminApiSharp/Entities/Billing/BillingStatus.cs @@ -3,6 +3,6 @@ public enum BillingStatus { Active = 1, - Suspended = 2, + Suspended = 2 } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Generic/ObjectBase.cs b/TCAdminApiSharp/Entities/Generic/ObjectBase.cs index 0a319ec..7b2e700 100644 --- a/TCAdminApiSharp/Entities/Generic/ObjectBase.cs +++ b/TCAdminApiSharp/Entities/Generic/ObjectBase.cs @@ -7,7 +7,7 @@ namespace TCAdminApiSharp.Entities.Generic public class ObjectBase { [JsonProperty("AppData")] public TcaXmlField AppData { get; set; } - + [JsonProperty("CreatedOn")] public DateTime CreatedOn { get; set; } [JsonProperty("CreatedBy")] public int CreatedBy { get; set; } diff --git a/TCAdminApiSharp/Entities/Server/Server.cs b/TCAdminApiSharp/Entities/Server/Server.cs index e3db825..7178113 100644 --- a/TCAdminApiSharp/Entities/Server/Server.cs +++ b/TCAdminApiSharp/Entities/Server/Server.cs @@ -11,7 +11,7 @@ namespace TCAdminApiSharp.Entities.Server { public class Server : ObjectBase, IObjectBaseCrud { - [JsonIgnore] public static readonly ServersController Controller = + [JsonIgnore] private static readonly ServersController Controller = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); [JsonProperty("DisableNewServices")] public bool DisableNewServices { get; set; } @@ -248,7 +248,7 @@ public async Task Update(Action action) action(server); var putJson = JsonConvert.SerializeObject(server, Constants.IgnoreDefaultValues); var request = Controller.GenerateDefaultRequest(); - request.Resource += this.ServerId; + request.Resource += ServerId; request.Method = Method.PUT; request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); return (await Controller.ExecuteBaseResponseRequest(request)).Success; diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index 1746625..8c030de 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; @@ -9,15 +8,15 @@ using TCAdminApiSharp.Entities.Billing; using TCAdminApiSharp.Entities.Generic; using TCAdminApiSharp.Helpers; +// ReSharper disable UnusedMember.Global namespace TCAdminApiSharp.Entities.Service { public class Service : ObjectBase, IObjectBaseCrud, IPowerable { - [JsonIgnore] - public static readonly ServicesController Controller = + [JsonIgnore] private static readonly ServicesController Controller = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); - + [JsonProperty("EnableGameSwitching")] public bool EnableGameSwitching { get; set; } [JsonProperty("DisableQueryMonitoring")] @@ -242,8 +241,13 @@ public class Service : ObjectBase, IObjectBaseCrud, IPowerable [JsonProperty("Notes")] public string Notes { get; set; } - [JsonIgnore] public User.User User => Controller.TcaClient.UsersController.GetUser(this.UserId).GetAwaiter().GetResult(); - [JsonIgnore] public Server.Server Server => Controller.TcaClient.ServersController.GetServer(this.ServerId).GetAwaiter().GetResult(); + [JsonIgnore] + public User.User User => Controller.TcaClient.UsersController.GetUser(UserId).ConfigureAwait(false).GetAwaiter() + .GetResult(); + + [JsonIgnore] + public Server.Server Server => + Controller.TcaClient.ServersController.GetServer(ServerId).ConfigureAwait(false).GetAwaiter().GetResult(); public async Task Update(Action action) { @@ -251,7 +255,7 @@ public async Task Update(Action action) action(service); var putJson = JsonConvert.SerializeObject(service, Constants.IgnoreDefaultValues); var request = Controller.GenerateDefaultRequest(); - request.Resource += this.ServiceId; + request.Resource += ServiceId; request.Method = Method.PUT; request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); return (await Controller.ExecuteBaseResponseRequest(request)).Success; @@ -266,59 +270,50 @@ public Task Delete() public async Task Start(string reason = "") { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"start/{this.ServiceId}"; + request.Resource += $"start/{ServiceId}"; request.Method = Method.POST; - if (!string.IsNullOrEmpty(reason)) - { - request.AddParameter("reason", reason); - } + if (!string.IsNullOrEmpty(reason)) request.AddParameter("reason", reason); return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public async Task Restart(string reason = "") { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"restart/{this.ServiceId}"; + request.Resource += $"restart/{ServiceId}"; request.Method = Method.POST; - if (!string.IsNullOrEmpty(reason)) - { - request.AddParameter("reason", reason); - } + if (!string.IsNullOrEmpty(reason)) request.AddParameter("reason", reason); return (await Controller.ExecuteBaseResponseRequest(request)).Success; } public async Task Stop(string reason = "") { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"stop/{this.ServiceId}"; + request.Resource += $"stop/{ServiceId}"; request.Method = Method.POST; - if (!string.IsNullOrEmpty(reason)) - { - request.AddParameter("reason", reason); - } + if (!string.IsNullOrEmpty(reason)) request.AddParameter("reason", reason); return (await Controller.ExecuteBaseResponseRequest(request)).Success; } - + public async Task Configure() { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"configure/{this.ServiceId}"; + request.Resource += $"configure/{ServiceId}"; request.Method = Method.POST; return (await Controller.ExecuteBaseResponseRequest(request)).Success; } - + public async Task Suspend() { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"suspend/{this.ServiceId}"; + request.Resource += $"suspend/{ServiceId}"; request.Method = Method.POST; return (await Controller.ExecuteBaseResponseRequest(request)).Success; } - + public async Task Unsuspend() { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"unsuspend/{this.ServiceId}"; + request.Resource += $"unsuspend/{ServiceId}"; request.Method = Method.POST; return (await Controller.ExecuteBaseResponseRequest(request)).Success; } diff --git a/TCAdminApiSharp/Entities/Service/ServiceBuilder.cs b/TCAdminApiSharp/Entities/Service/ServiceBuilder.cs index ec7e053..7fcee89 100644 --- a/TCAdminApiSharp/Entities/Service/ServiceBuilder.cs +++ b/TCAdminApiSharp/Entities/Service/ServiceBuilder.cs @@ -6,6 +6,7 @@ using Serilog; using TCAdminApiSharp.Entities.Generic; using TCAdminApiSharp.Helpers; + // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMethodReturnValue.Global @@ -41,7 +42,7 @@ public ServiceBuilder WithUserId(int id) _service.UserId = id; return this; } - + public ServiceBuilder WithUser(User.User user) { _service.UserId = user.UserId; @@ -92,7 +93,7 @@ public ServiceBuilder WithStartup(ServiceStartup startup) public ServiceBuilder WithPriority(ProcessPriorityClass priority) { - _service.Priority = (int)priority; + _service.Priority = (int) priority; return this; } @@ -176,11 +177,8 @@ public ServiceBuilder WithMemoryLimitMb(int mb) internal string GenerateRequestBody() { - var jo = JObject.FromObject(this._service, JsonSerializer.Create(Constants.IgnoreDefaultValues)); - foreach (var keyValuePair in _extraData) - { - jo.Add(keyValuePair.Key, new JValue(keyValuePair.Value)); - } + var jo = JObject.FromObject(_service, JsonSerializer.Create(Constants.IgnoreDefaultValues)); + foreach (var keyValuePair in _extraData) jo.Add(keyValuePair.Key, new JValue(keyValuePair.Value)); _logger.Debug(jo.ToString()); return jo.ToString(); diff --git a/TCAdminApiSharp/Entities/Service/ServiceStartup.cs b/TCAdminApiSharp/Entities/Service/ServiceStartup.cs index db9e4d5..16ec273 100644 --- a/TCAdminApiSharp/Entities/Service/ServiceStartup.cs +++ b/TCAdminApiSharp/Entities/Service/ServiceStartup.cs @@ -4,6 +4,6 @@ public enum ServiceStartup { Automatic = 2, Manual = 3, - Disabled = 4, + Disabled = 4 } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/ServiceStatus.cs b/TCAdminApiSharp/Entities/Service/ServiceStatus.cs index 8530687..a11306a 100644 --- a/TCAdminApiSharp/Entities/Service/ServiceStatus.cs +++ b/TCAdminApiSharp/Entities/Service/ServiceStatus.cs @@ -12,6 +12,6 @@ public enum ServiceStatus Running = 4, Resuming = 5, Pausing = 6, - Paused = 7, + Paused = 7 } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Task/Task.cs b/TCAdminApiSharp/Entities/Task/Task.cs index 205f9b0..cfe80e9 100644 --- a/TCAdminApiSharp/Entities/Task/Task.cs +++ b/TCAdminApiSharp/Entities/Task/Task.cs @@ -11,7 +11,7 @@ namespace TCAdminApiSharp.Entities.Task { public class Task : ObjectBase { - [JsonIgnore] public static readonly TasksController Controller = + [JsonIgnore] private static readonly TasksController Controller = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); [JsonProperty("TaskId")] public int TaskId { get; set; } @@ -54,26 +54,31 @@ public class Task : ObjectBase [JsonProperty("RedirectUrl")] public string RedirectUrl { get; set; } - [JsonIgnore] public IEnumerable Steps => (List) Controller.GetTaskSteps(this.TaskId).GetAwaiter().GetResult().Result; + [JsonIgnore] + public IEnumerable Steps => + (List) Controller.GetTaskSteps(TaskId).GetAwaiter().GetResult().Result; [JsonIgnore] public TaskStep CurrentStep { - get { return Steps.FirstOrDefault(x => x.StepId == this.CurrentStepId) ?? throw new InvalidOperationException(); } + get + { + return Steps.FirstOrDefault(x => x.StepId == CurrentStepId) ?? throw new InvalidOperationException(); + } } public async System.Threading.Tasks.Task Start() { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"start/{this.TaskId}"; + request.Resource += $"start/{TaskId}"; request.Method = Method.POST; await Controller.ExecuteBaseResponseRequest(request); } - + public async System.Threading.Tasks.Task Cancel() { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"cancel/{this.TaskId}"; + request.Resource += $"cancel/{TaskId}"; request.Method = Method.POST; await Controller.ExecuteBaseResponseRequest(request); } diff --git a/TCAdminApiSharp/Entities/Task/TaskStatus.cs b/TCAdminApiSharp/Entities/Task/TaskStatus.cs index c348d98..3af5edf 100644 --- a/TCAdminApiSharp/Entities/Task/TaskStatus.cs +++ b/TCAdminApiSharp/Entities/Task/TaskStatus.cs @@ -7,6 +7,6 @@ public enum TaskStatus Scheduled, Completed, Canceled, - TaskError, + TaskError } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Task/TaskStep.cs b/TCAdminApiSharp/Entities/Task/TaskStep.cs index af67ce7..eb9a1c9 100644 --- a/TCAdminApiSharp/Entities/Task/TaskStep.cs +++ b/TCAdminApiSharp/Entities/Task/TaskStep.cs @@ -9,49 +9,35 @@ namespace TCAdminApiSharp.Entities.Task { public class TaskStep : ObjectBase { - [JsonIgnore] public static readonly TasksController Controller = + [JsonIgnore] private static readonly TasksController Controller = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); - - [JsonProperty("ModuleId")] - public string ModuleId { get; set; } - [JsonProperty("ProcessId")] - public int ProcessId { get; set; } + [JsonProperty("ModuleId")] public string ModuleId { get; set; } - [JsonProperty("TaskId")] - public int TaskId { get; set; } + [JsonProperty("ProcessId")] public int ProcessId { get; set; } - [JsonProperty("StepId")] - public int StepId { get; set; } + [JsonProperty("TaskId")] public int TaskId { get; set; } - [JsonProperty("ServerId")] - public int ServerId { get; set; } + [JsonProperty("StepId")] public int StepId { get; set; } - [JsonProperty("Log")] - public Dictionary Log { get; set; } + [JsonProperty("ServerId")] public int ServerId { get; set; } - [JsonProperty("DebugLog")] - public Dictionary DebugLog { get; set; } + [JsonProperty("Log")] public Dictionary Log { get; set; } - [JsonProperty("LastDebugLogKey")] - public DateTime LastDebugLogKey { get; set; } + [JsonProperty("DebugLog")] public Dictionary DebugLog { get; set; } - [JsonProperty("LastLogKey")] - public DateTime LastLogKey { get; set; } + [JsonProperty("LastDebugLogKey")] public DateTime LastDebugLogKey { get; set; } - [JsonProperty("Name")] - public string Name { get; set; } + [JsonProperty("LastLogKey")] public DateTime LastLogKey { get; set; } - [JsonProperty("LastLogItem")] - public string LastLogItem { get; set; } + [JsonProperty("Name")] public string Name { get; set; } - [JsonProperty("Arguments")] - public string Arguments { get; set; } + [JsonProperty("LastLogItem")] public string LastLogItem { get; set; } - [JsonProperty("ReturnValue")] - public string ReturnValue { get; set; } + [JsonProperty("Arguments")] public string Arguments { get; set; } - [JsonProperty("Progress")] - public int Progress { get; set; } + [JsonProperty("ReturnValue")] public string ReturnValue { get; set; } + + [JsonProperty("Progress")] public int Progress { get; set; } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/User/User.cs b/TCAdminApiSharp/Entities/User/User.cs index ba4cead..b1d1ca4 100644 --- a/TCAdminApiSharp/Entities/User/User.cs +++ b/TCAdminApiSharp/Entities/User/User.cs @@ -12,7 +12,7 @@ namespace TCAdminApiSharp.Entities.User { public class User : ObjectBase, IObjectBaseCrud { - [JsonIgnore] public static readonly UsersController Controller = + [JsonIgnore] private static readonly UsersController Controller = TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); [JsonProperty("UserId")] public int UserId { get; set; } @@ -89,8 +89,9 @@ public class User : ObjectBase, IObjectBaseCrud [JsonProperty("UserType")] public UserType UserType { get; set; } - [JsonIgnore] public IList Services => - Controller.TcaClient.ServicesController.GetServicesByUserId(this.UserId).GetAwaiter().GetResult().Result; + [JsonIgnore] + public IList Services => + Controller.TcaClient.ServicesController.GetServicesByUserId(UserId).GetAwaiter().GetResult().Result; public async Task SetPassword(string password) { @@ -107,7 +108,7 @@ public async Task Update(Action action) action(service); var putJson = JsonConvert.SerializeObject(service, Constants.IgnoreDefaultValues); var request = Controller.GenerateDefaultRequest(); - request.Resource += this.UserId; + request.Resource += UserId; request.Method = Method.PUT; request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); return (await Controller.ExecuteBaseResponseRequest(request)).Success; @@ -117,21 +118,21 @@ public Task Delete() { throw new NotImplementedException(); } - + public async Task Suspend(bool recursive = true, bool suspendServices = true) { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"suspend/{this.UserId}"; + request.Resource += $"suspend/{UserId}"; request.Method = Method.POST; request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); request.AddParameter(nameof(suspendServices), suspendServices, ParameterType.GetOrPost); return (await Controller.ExecuteBaseResponseRequest(request)).Success; } - + public async Task Unsuspend(bool recursive = true, bool enableServices = true) { var request = Controller.GenerateDefaultRequest(); - request.Resource += $"unsuspend/{this.UserId}"; + request.Resource += $"unsuspend/{UserId}"; request.Method = Method.POST; request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); request.AddParameter(nameof(enableServices), enableServices, ParameterType.GetOrPost); diff --git a/TCAdminApiSharp/Entities/User/UserType.cs b/TCAdminApiSharp/Entities/User/UserType.cs index 2e043d0..9294939 100644 --- a/TCAdminApiSharp/Entities/User/UserType.cs +++ b/TCAdminApiSharp/Entities/User/UserType.cs @@ -4,6 +4,6 @@ public enum UserType { User = 1, SubAdmin = 2, - Admin = 3, + Admin = 3 } } \ No newline at end of file diff --git a/TCAdminApiSharp/Exceptions/API/ApiRequestException.cs b/TCAdminApiSharp/Exceptions/API/ApiRequestException.cs index 6344c8f..f31abd5 100644 --- a/TCAdminApiSharp/Exceptions/API/ApiRequestException.cs +++ b/TCAdminApiSharp/Exceptions/API/ApiRequestException.cs @@ -6,25 +6,26 @@ namespace TCAdminApiSharp.Exceptions.API public class ApiRequestException : Exception { public readonly RestRequest RestRequest; - + internal ApiRequestException(RestRequest restRequest) { - this.RestRequest = restRequest; + RestRequest = restRequest; } internal ApiRequestException(RestRequest restRequest, string? message) : base(message) { - this.RestRequest = restRequest; + RestRequest = restRequest; } - internal ApiRequestException(RestRequest restRequest, string? message, Exception? innerException) : base(message, innerException) + internal ApiRequestException(RestRequest restRequest, string? message, Exception? innerException) : base( + message, innerException) { - this.RestRequest = restRequest; + RestRequest = restRequest; } - + internal ApiRequestException(RestRequest restRequest, Exception? innerException) : base(null, innerException) { - this.RestRequest = restRequest; + RestRequest = restRequest; } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Exceptions/API/ApiResponseException.cs b/TCAdminApiSharp/Exceptions/API/ApiResponseException.cs index 60762b1..521ad85 100644 --- a/TCAdminApiSharp/Exceptions/API/ApiResponseException.cs +++ b/TCAdminApiSharp/Exceptions/API/ApiResponseException.cs @@ -12,7 +12,6 @@ public class ApiResponseException : Exception internal ApiResponseException() { - } internal ApiResponseException(IRestResponse restResponse) : this() diff --git a/TCAdminApiSharp/Exceptions/NotFoundException.cs b/TCAdminApiSharp/Exceptions/NotFoundException.cs index 13450bc..1c02ff1 100644 --- a/TCAdminApiSharp/Exceptions/NotFoundException.cs +++ b/TCAdminApiSharp/Exceptions/NotFoundException.cs @@ -6,16 +6,18 @@ public class NotFoundException : Exception { public readonly Type Type; public readonly int[] Ids; - - public NotFoundException(Type type, params int[] ids) : base($"The {type.FullName} could not be found with ids: [{string.Join(", ", ids)}]") + + public NotFoundException(Type type, params int[] ids) : base( + $"The {type.FullName} could not be found with ids: [{string.Join(", ", ids)}]") { - this.Type = type; + Type = type; Ids = ids; } - public NotFoundException(Type type, Exception innerException, int[] ids) : base($"The {type.FullName} could not be found", innerException) + public NotFoundException(Type type, Exception innerException, int[] ids) : base( + $"The {type.FullName} could not be found", innerException) { - this.Type = type; + Type = type; Ids = ids; } } diff --git a/TCAdminApiSharp/Helpers/Constants.cs b/TCAdminApiSharp/Helpers/Constants.cs index 348ad40..cbf59de 100644 --- a/TCAdminApiSharp/Helpers/Constants.cs +++ b/TCAdminApiSharp/Helpers/Constants.cs @@ -5,13 +5,13 @@ namespace TCAdminApiSharp.Helpers internal static class Constants { public const string JsonContentType = "application/json"; - + public static readonly JsonSerializerSettings IgnoreDefaultValues = new() { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; - + public static readonly JsonSerializerSettings IgnoreReferenceLoop = new() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore diff --git a/TCAdminApiSharp/Querying/IQueryOperation.cs b/TCAdminApiSharp/Querying/IQueryOperation.cs index 7c5fdf2..a5c7a46 100644 --- a/TCAdminApiSharp/Querying/IQueryOperation.cs +++ b/TCAdminApiSharp/Querying/IQueryOperation.cs @@ -1,11 +1,15 @@ using Newtonsoft.Json.Linq; +using RestSharp; namespace TCAdminApiSharp.Querying { public interface IQueryOperation { string JsonKey { get; set; } + + void ModifyRequest(IRestRequest request) + { - JToken GenerateQuery(); + } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operations/FilterList.cs b/TCAdminApiSharp/Querying/Operations/FilterList.cs new file mode 100644 index 0000000..31748b9 --- /dev/null +++ b/TCAdminApiSharp/Querying/Operations/FilterList.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RestSharp; +using TCAdminApiSharp.Querying.Structs; + +namespace TCAdminApiSharp.Querying.Operations +{ + public class FilterList : List, IQueryOperation + { + [JsonIgnore] + public string JsonKey { get; set; } = "Fields"; + + public FilterList() + { + } + + public FilterList(params string[] where) + { + foreach (var filterInfo in where) + { + Add(filterInfo); + } + } + + public FilterList(FilterInfo where) + { + Add(where); + } + + public FilterList(params FilterInfo[] where) + { + foreach (var filterInfo in @where) + { + Add(filterInfo); + } + } + + public void Add(string column) + { + Add(new FilterInfo() + { + Column = column + }); + } + + public JToken GenerateQuery() + { + var temp = this.Aggregate("(", (current, info) => current + $"[{info.Column}]"); + + temp += ")"; + return new JValue(temp); + } + + public void ModifyRequest(IRestRequest request) + { + request.AddQueryParameter("fields", string.Join(",", this.Select(x => x.Column.ToLower()))); + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operations/OrderList.cs b/TCAdminApiSharp/Querying/Operations/OrderList.cs index 8878bb2..898c387 100644 --- a/TCAdminApiSharp/Querying/Operations/OrderList.cs +++ b/TCAdminApiSharp/Querying/Operations/OrderList.cs @@ -3,6 +3,7 @@ using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using RestSharp; using TCAdminApiSharp.Querying.Operators; using TCAdminApiSharp.Querying.Structs; @@ -18,18 +19,35 @@ public OrderList() public OrderList(string field, OrderOperator @operator) { - this.Add(field, @operator); + Add(field, @operator); } - public void Add(string column, OrderOperator @operator) => this.Add(new OrderInfo + public void Add(string column, OrderOperator @operator) { - Column = column, - Operator = @operator - }); + Add(new OrderInfo + { + Column = column, + Operator = @operator + }); + } public JToken GenerateQuery() { return JToken.FromObject(this); } + + public void ModifyRequest(IRestRequest request) + { + JObject jObject = new(); + var queryInfoExists = request.Parameters.Any(x => x.Name == "queryInfo"); + if (queryInfoExists) + { + jObject = JsonConvert.DeserializeObject(request.Parameters.Find(x => x.Name == "queryInfo")!.Value!.ToString()!); + } + + jObject[JsonKey] = JToken.FromObject(this); + + request.AddOrUpdateParameter("queryInfo", jObject, ParameterType.GetOrPost); + } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operations/WhereList.cs b/TCAdminApiSharp/Querying/Operations/WhereList.cs index 577b4f9..1b21ee8 100644 --- a/TCAdminApiSharp/Querying/Operations/WhereList.cs +++ b/TCAdminApiSharp/Querying/Operations/WhereList.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; -using System.Text.Json.Serialization; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using RestSharp; using TCAdminApiSharp.Querying.Operators; using TCAdminApiSharp.Querying.Structs; @@ -11,27 +12,30 @@ namespace TCAdminApiSharp.Querying.Operations { public class WhereList : List, IQueryOperation { - [JsonIgnore] public string JsonKey { get; set; } = "Where"; - [JsonIgnore] public WhereOperator WhereOperator { get; set; } + [System.Text.Json.Serialization.JsonIgnore] public string JsonKey { get; set; } = "Where"; + [System.Text.Json.Serialization.JsonIgnore] public WhereOperator WhereOperator { get; set; } - public WhereList() => this.WhereOperator = WhereOperator.And; + public WhereList() + { + WhereOperator = WhereOperator.And; + } public WhereList(WhereInfo where) { - this.WhereOperator = WhereOperator.And; - this.Add(where); + WhereOperator = WhereOperator.And; + Add(where); } public WhereList(string column, object value) { - this.WhereOperator = WhereOperator.And; - this.Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); + WhereOperator = WhereOperator.And; + Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); } public WhereList(string column, ColumnOperator @operator, object value) { - this.WhereOperator = WhereOperator.And; - this.Add(new WhereInfo + WhereOperator = WhereOperator.And; + Add(new WhereInfo { Column = column, ColumnOperator = @operator, @@ -39,15 +43,20 @@ public WhereList(string column, ColumnOperator @operator, object value) }); } - public void Add(string column, object value) => - this.Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); + public void Add(string column, object value) + { + Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); + } - public void Add(string column, ColumnOperator @operator, object value) => this.Add(new WhereInfo + public void Add(string column, ColumnOperator @operator, object value) { - Column = column, - ColumnOperator = @operator, - ColumnValue = value - }); + Add(new WhereInfo + { + Column = column, + ColumnOperator = @operator, + ColumnValue = value + }); + } public JToken GenerateQuery() { @@ -56,17 +65,29 @@ public JToken GenerateQuery() { temp += $"[{info.Column}] {ConvertColumnOperator(info.ColumnOperator)} '{info.ColumnValue}'"; if (!this.Last().Equals(info)) - { // Add where operator - temp += $" {this.WhereOperator.ToString().ToUpper()} "; - } + temp += $" {WhereOperator.ToString().ToUpper()} "; } temp += ")"; return new JValue(temp); } - public string ConvertColumnOperator(ColumnOperator columnOperator) + public void ModifyRequest(IRestRequest request) + { + JObject jObject = new(); + var queryInfoExists = request.Parameters.Any(x => x.Name == "queryInfo"); + if (queryInfoExists) + { + jObject = JsonConvert.DeserializeObject(request.Parameters.Find(x => x.Name == "queryInfo")!.Value!.ToString()!); + } + + jObject[JsonKey] = GenerateQuery(); + + request.AddOrUpdateParameter("queryInfo", jObject, ParameterType.GetOrPost); + } + + public static string ConvertColumnOperator(ColumnOperator columnOperator) { return columnOperator switch { diff --git a/TCAdminApiSharp/Querying/QueryableInfo.cs b/TCAdminApiSharp/Querying/QueryableInfo.cs index 48ef72e..7134908 100644 --- a/TCAdminApiSharp/Querying/QueryableInfo.cs +++ b/TCAdminApiSharp/Querying/QueryableInfo.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using RestSharp; namespace TCAdminApiSharp.Querying { @@ -25,23 +26,15 @@ public QueryableInfo(int rowCount, int offset, IQueryOperation queryOperation) public QueryableInfo(params IQueryOperation[] queryOperations) { - foreach (var queryOperation in queryOperations) - { - QueryOperations.Add(queryOperation); - } + foreach (var queryOperation in queryOperations) QueryOperations.Add(queryOperation); } - public string BuildQuery() + public void BuildQuery(IRestRequest request) { - var jObject = JObject.FromObject(this); foreach (var queryOperation in QueryOperations) { - jObject.Add(queryOperation.JsonKey, queryOperation.GenerateQuery()); + queryOperation.ModifyRequest(request); } - return JsonConvert.SerializeObject(jObject, new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore, - }); } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Structs/FilterInfo.cs b/TCAdminApiSharp/Querying/Structs/FilterInfo.cs new file mode 100644 index 0000000..ce70ce4 --- /dev/null +++ b/TCAdminApiSharp/Querying/Structs/FilterInfo.cs @@ -0,0 +1,12 @@ +namespace TCAdminApiSharp.Querying.Structs +{ + public struct FilterInfo + { + public string Column; + + public FilterInfo(string column) + { + Column = column; + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Structs/OrderInfo.cs b/TCAdminApiSharp/Querying/Structs/OrderInfo.cs index 4dc4f3d..bd874ab 100644 --- a/TCAdminApiSharp/Querying/Structs/OrderInfo.cs +++ b/TCAdminApiSharp/Querying/Structs/OrderInfo.cs @@ -6,11 +6,9 @@ namespace TCAdminApiSharp.Querying.Structs { public struct OrderInfo { - [JsonProperty("Field")] - public string Column; - - [JsonProperty("Direction")] - [JsonConverter(typeof(StringEnumConverter))] + [JsonProperty("Field")] public string Column; + + [JsonProperty("Direction")] [JsonConverter(typeof(StringEnumConverter))] public OrderOperator Operator; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Structs/WhereInfo.cs b/TCAdminApiSharp/Querying/Structs/WhereInfo.cs index ca1ef96..ee71a30 100644 --- a/TCAdminApiSharp/Querying/Structs/WhereInfo.cs +++ b/TCAdminApiSharp/Querying/Structs/WhereInfo.cs @@ -8,7 +8,7 @@ public struct WhereInfo { public string Column; public object ColumnValue; - + [JsonConverter(typeof(StringEnumConverter))] public ColumnOperator ColumnOperator; } diff --git a/TCAdminApiSharp/TCAdminApiSharp.csproj b/TCAdminApiSharp/TCAdminApiSharp.csproj index 45bc24c..5f4a3cb 100644 --- a/TCAdminApiSharp/TCAdminApiSharp.csproj +++ b/TCAdminApiSharp/TCAdminApiSharp.csproj @@ -25,4 +25,8 @@ + + + + diff --git a/TCAdminApiSharp/TcaClient.cs b/TCAdminApiSharp/TcaClient.cs index fef330f..40a06a4 100644 --- a/TCAdminApiSharp/TcaClient.cs +++ b/TCAdminApiSharp/TcaClient.cs @@ -4,6 +4,7 @@ using Serilog; using Serilog.Events; using TCAdminApiSharp.Controllers; + // ReSharper disable NotAccessedField.Global namespace TCAdminApiSharp @@ -24,35 +25,31 @@ public TcaClient(string host, string apiKey, TcaClientSettings? clientSettings = { clientSettings ??= TcaClientSettings.Default; SetupDefaultLogger(clientSettings.MinimumLogLevel); - CreateHostBuilder(); - if (string.IsNullOrEmpty(host)) - { - throw new ArgumentException("Parameter is null/empty", nameof(host)); - } - if (string.IsNullOrEmpty(apiKey)) - { - throw new ArgumentException("Parameter is null/empty", nameof(apiKey)); - } - + InitializeDI(); + if (string.IsNullOrEmpty(host)) throw new ArgumentException("Parameter is null/empty", nameof(host)); + if (string.IsNullOrEmpty(apiKey)) throw new ArgumentException("Parameter is null/empty", nameof(apiKey)); + Settings = clientSettings; Host = host; _apiKey = apiKey; RestClient = new RestClient(Host); RestClient.AddDefaultHeader("api_key", apiKey); - - ServicesController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); - ServersController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); + + ServicesController = ServiceProvider.GetService() ?? + throw new InvalidOperationException(); + ServersController = + ServiceProvider.GetService() ?? throw new InvalidOperationException(); UsersController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); TasksController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); } internal int GetTokenUserId() { - return int.Parse(this._apiKey.Split('#')[0]); + return int.Parse(_apiKey.Split('#')[0]); } - private void CreateHostBuilder() + private void InitializeDI() { ServiceProvider = new ServiceCollection() .AddTransient(_ => this) diff --git a/TCAdminApiSharp/TcaClientSettings.cs b/TCAdminApiSharp/TcaClientSettings.cs index fbaa2df..2313769 100644 --- a/TCAdminApiSharp/TcaClientSettings.cs +++ b/TCAdminApiSharp/TcaClientSettings.cs @@ -6,7 +6,7 @@ public class TcaClientSettings { public LogEventLevel MinimumLogLevel { get; set; } = LogEventLevel.Information; public bool ThrowOnApiSuccessFailure { get; set; } = true; - + public bool ThrowOnApiResponseStatusNonComplete { get; set; } = true; public bool ThrowOnApiStatusCodeNonOk { get; set; } = true; From f0df70b40c4df74c3fb8556257ff3fa6e40159fd Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Tue, 2 Mar 2021 17:27:44 +0000 Subject: [PATCH 23/31] Improvements --- TCAdminApiSharp/Controllers/BaseController.cs | 6 ------ TCAdminApiSharp/Controllers/ServicesController.cs | 2 -- 2 files changed, 8 deletions(-) diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index 51d6678..622d712 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -4,12 +4,10 @@ using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using RestSharp; using Serilog; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Exceptions.API; -using TCAdminApiSharp.Helpers; using TCAdminApiSharp.Querying; namespace TCAdminApiSharp.Controllers @@ -38,10 +36,8 @@ public RestRequest GenerateDefaultRequest() public async Task> AdvancedRequest(string resource, QueryableInfo query, Method method = Method.POST) { var request = GenerateDefaultRequest(); - // Logger.Debug(query.BuildQuery()); request.Method = method; request.Resource += resource; - // request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); query.BuildQuery(request); return await ExecuteBaseResponseRequest(request); } @@ -49,10 +45,8 @@ public async Task> AdvancedRequest(string resource, Queryable public async Task> AdvancedListRequest(string resource, QueryableInfo query, Method method = Method.POST) { var request = GenerateDefaultRequest(); - // Logger.Debug(query.BuildQuery()); request.Method = method; request.Resource += resource; - // request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); query.BuildQuery(request); return await ExecuteListResponseRequest(request); } diff --git a/TCAdminApiSharp/Controllers/ServicesController.cs b/TCAdminApiSharp/Controllers/ServicesController.cs index b3fc861..ec8344c 100644 --- a/TCAdminApiSharp/Controllers/ServicesController.cs +++ b/TCAdminApiSharp/Controllers/ServicesController.cs @@ -34,10 +34,8 @@ public async Task CreateService(ServiceBuilder builder) public async Task> FindServices(QueryableInfo query) { var request = GenerateDefaultRequest(); - // Logger.Debug(query.BuildQuery()); request.Method = Method.POST; request.Resource += "gameservices"; - // request.AddParameter("queryInfo", query.BuildQuery(), ParameterType.GetOrPost); query.BuildQuery(request); return await ExecuteListResponseRequest(request); } From 1da74e03241c7b8d447e7e77efc2b72c2f976301 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sun, 19 Sep 2021 17:45:32 +0100 Subject: [PATCH 24/31] Custom field support --- .idea/.idea.TCAdminApiSharp/.idea/indexLayout.xml | 2 +- .idea/.idea.TCAdminApiSharp/.idea/riderModule.iml | 14 -------------- TCAdminApiSharp/Entities/API/BaseResponse.cs | 2 +- TCAdminApiSharp/Querying/Operations/WhereList.cs | 8 +++++++- 4 files changed, 9 insertions(+), 17 deletions(-) delete mode 100644 .idea/.idea.TCAdminApiSharp/.idea/riderModule.iml diff --git a/.idea/.idea.TCAdminApiSharp/.idea/indexLayout.xml b/.idea/.idea.TCAdminApiSharp/.idea/indexLayout.xml index 27ba142..7b08163 100644 --- a/.idea/.idea.TCAdminApiSharp/.idea/indexLayout.xml +++ b/.idea/.idea.TCAdminApiSharp/.idea/indexLayout.xml @@ -1,6 +1,6 @@ - + diff --git a/.idea/.idea.TCAdminApiSharp/.idea/riderModule.iml b/.idea/.idea.TCAdminApiSharp/.idea/riderModule.iml deleted file mode 100644 index 024158d..0000000 --- a/.idea/.idea.TCAdminApiSharp/.idea/riderModule.iml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/API/BaseResponse.cs b/TCAdminApiSharp/Entities/API/BaseResponse.cs index a306650..503a0e5 100644 --- a/TCAdminApiSharp/Entities/API/BaseResponse.cs +++ b/TCAdminApiSharp/Entities/API/BaseResponse.cs @@ -10,7 +10,7 @@ public class BaseResponse [JsonProperty("Message")] public string? Message { get; private set; } - public IRestResponse RestResponse { get; internal set; } + [JsonIgnore] public IRestResponse RestResponse { get; internal set; } internal BaseResponse() { diff --git a/TCAdminApiSharp/Querying/Operations/WhereList.cs b/TCAdminApiSharp/Querying/Operations/WhereList.cs index 1b21ee8..ebaefc5 100644 --- a/TCAdminApiSharp/Querying/Operations/WhereList.cs +++ b/TCAdminApiSharp/Querying/Operations/WhereList.cs @@ -63,7 +63,13 @@ public JToken GenerateQuery() var temp = "("; foreach (var info in this) { - temp += $"[{info.Column}] {ConvertColumnOperator(info.ColumnOperator)} '{info.ColumnValue}'"; + var tempColumnName = info.Column; + if (!tempColumnName.StartsWith("[") && !tempColumnName.EndsWith("]")) + { + tempColumnName = $"[{info.Column}]"; + } + + temp += $"{tempColumnName} {ConvertColumnOperator(info.ColumnOperator)} '{info.ColumnValue}'"; if (!this.Last().Equals(info)) // Add where operator temp += $" {WhereOperator.ToString().ToUpper()} "; From 7e7a3e69cbce162cd53be66eebd2f53438a35538 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sun, 19 Sep 2021 21:25:14 +0100 Subject: [PATCH 25/31] Fix get by user id --- TCAdminApiSharp/Controllers/BaseController.cs | 2 +- TCAdminApiSharp/Controllers/ServicesController.cs | 5 ++++- TCAdminApiSharp/TcaClientSettings.cs | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index 622d712..883524c 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -94,7 +94,7 @@ public async Task> ExecuteRequestAsync(RestRequest re { if (!TcaClient.Settings.ThrowOnApiStatusCodeNonOk) return new Tuple(default!, restResponse); - throw new ApiResponseException(restResponse, "Status code is: " + restResponse.StatusCode); + throw new ApiResponseException(restResponse, $"Status code is: {restResponse.StatusCode}\n{restResponse.Content}"); } var baseResponse = diff --git a/TCAdminApiSharp/Controllers/ServicesController.cs b/TCAdminApiSharp/Controllers/ServicesController.cs index ec8344c..1f4cab8 100644 --- a/TCAdminApiSharp/Controllers/ServicesController.cs +++ b/TCAdminApiSharp/Controllers/ServicesController.cs @@ -71,7 +71,10 @@ public Task> GetServicesByBillingId(string billingId) public Task> GetServicesByUserId(int userId) { - return FindServices(new QueryableInfo(new WhereList("UserId", ColumnOperator.Equal, userId))); + var request = GenerateDefaultRequest(); + request.Method = Method.GET; + request.Resource += $"gameservices?{nameof(userId)}={userId}"; + return ExecuteListResponseRequest(request); } } } \ No newline at end of file diff --git a/TCAdminApiSharp/TcaClientSettings.cs b/TCAdminApiSharp/TcaClientSettings.cs index 2313769..618fd50 100644 --- a/TCAdminApiSharp/TcaClientSettings.cs +++ b/TCAdminApiSharp/TcaClientSettings.cs @@ -4,7 +4,7 @@ namespace TCAdminApiSharp { public class TcaClientSettings { - public LogEventLevel MinimumLogLevel { get; set; } = LogEventLevel.Information; + public LogEventLevel MinimumLogLevel { get; set; } = LogEventLevel.Error; public bool ThrowOnApiSuccessFailure { get; set; } = true; public bool ThrowOnApiResponseStatusNonComplete { get; set; } = true; From 4198e6d4d7319051c703adfacfb1e09d47694b03 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Sun, 19 Sep 2021 23:33:50 +0100 Subject: [PATCH 26/31] Build update --- .github/workflows/Publish - Dev.yml | 3 ++- TCAdminApiSharp/Controllers/BaseController.cs | 2 +- TCAdminApiSharp/TCAdminApiSharp.csproj | 5 +++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/Publish - Dev.yml b/.github/workflows/Publish - Dev.yml index d4136d7..152984b 100644 --- a/.github/workflows/Publish - Dev.yml +++ b/.github/workflows/Publish - Dev.yml @@ -21,7 +21,7 @@ jobs: run: dotnet test --no-build --verbosity normal - name: Get DateTime id: datetime - run: echo "::set-output name=date::$(date +'%Y%m%d')" + run: echo "::set-output name=date::$(date +'%Y%m%d-%H%M%S')" - name: Deploy - Dev uses: alexr03/publish-nuget@master with: @@ -30,3 +30,4 @@ jobs: VERSION_REGEX: ^\s*(.*)<\/AssemblyVersion>\s*$ VERSION_SUFFIX: -dev-${{steps.datetime.outputs.date}}-${{github.run_number}} TAG_FORMAT: dev-v* + INCLUDE_SYMBOLS: true diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index 883524c..af07398 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -30,7 +30,7 @@ protected BaseController(string baseResource) public RestRequest GenerateDefaultRequest() { - return new(BaseResource); + return new RestRequest(BaseResource); } public async Task> AdvancedRequest(string resource, QueryableInfo query, Method method = Method.POST) diff --git a/TCAdminApiSharp/TCAdminApiSharp.csproj b/TCAdminApiSharp/TCAdminApiSharp.csproj index 5f4a3cb..3ab1d15 100644 --- a/TCAdminApiSharp/TCAdminApiSharp.csproj +++ b/TCAdminApiSharp/TCAdminApiSharp.csproj @@ -12,8 +12,9 @@ https://avatars3.githubusercontent.com/u/67070230?s=200&v=4 https://github.com/TotalControlAdmin/TCAdminApiSharp TCAdmin, Wrapper, Rest, Api - 1.0.1 - 1.0.1 + 1.0.2 + 1.0.2 + 1.0.2 From 92363c98438cb8cac2c2e27070dd8125f5a98ea4 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Thu, 30 Jun 2022 12:51:23 +0100 Subject: [PATCH 27/31] Initial dev 2.0.0 --- .github/workflows/Publish - Dev.yml | 32 +- TCAdminApiSharp.Tests/ClientTests.cs | 31 +- TCAdminApiSharp.Tests/ServerTests.cs | 39 ++ TCAdminApiSharp.Tests/ServiceTests.cs | 226 ++++++----- .../TCAdminApiSharp.Tests.csproj | 19 +- TCAdminApiSharp.Tests/appsettings.json | 11 + TCAdminApiSharp.Tests/appsettings.local.json | 11 + TCAdminApiSharp/Controllers/BaseController.cs | 210 ++++++---- .../Controllers/ServersController.cs | 58 +-- .../Controllers/ServicesController.cs | 109 +++-- .../Controllers/TasksController.cs | 62 ++- .../Controllers/UsersController.cs | 99 ++--- TCAdminApiSharp/Entities/API/BaseResponse.cs | 36 +- TCAdminApiSharp/Entities/API/ErrorResponse.cs | 27 +- TCAdminApiSharp/Entities/API/ListResponse.cs | 17 +- .../Entities/Billing/BillingStatus.cs | 11 +- .../Entities/Generic/IPowerable.cs | 13 +- .../Entities/Generic/ObjectBase.cs | 35 +- .../Entities/Generic/TcaXmlField.cs | 15 +- TCAdminApiSharp/Entities/Server/Server.cs | 290 +++++++------- .../Service/FileManager/CompressModel.cs | 9 + .../Service/FileManager/DirectoryListing.cs | 47 +++ .../Entities/Service/FileManager/FileInfo.cs | 61 +++ .../Service/FileManager/FileManagerService.cs | 136 +++++++ TCAdminApiSharp/Entities/Service/Service.cs | 373 +++++++++--------- .../Entities/Service/ServiceBuilder.cs | 343 ++++++++-------- .../Entities/Service/ServiceStartup.cs | 13 +- .../Entities/Service/ServiceStatus.cs | 29 +- TCAdminApiSharp/Entities/Task/Task.cs | 102 +++-- TCAdminApiSharp/Entities/Task/TaskStatus.cs | 19 +- TCAdminApiSharp/Entities/Task/TaskStep.cs | 40 +- TCAdminApiSharp/Entities/User/User.cs | 184 ++++----- TCAdminApiSharp/Entities/User/UserType.cs | 13 +- .../Exceptions/API/ApiRequestException.cs | 31 -- .../Exceptions/API/ApiResponseException.cs | 47 ++- .../Exceptions/NotFoundException.cs | 24 -- TCAdminApiSharp/Helpers/Constants.cs | 28 +- TCAdminApiSharp/Querying/IQueryOperation.cs | 18 +- .../Querying/Operations/FilterList.cs | 78 ++-- .../Querying/Operations/OrderList.cs | 68 ++-- .../Querying/Operations/WhereList.cs | 165 ++++---- .../Querying/Operators/ColumnOperator.cs | 23 +- .../Querying/Operators/OrderOperator.cs | 11 +- .../Querying/Operators/WhereOperator.cs | 11 +- TCAdminApiSharp/Querying/QueryableInfo.cs | 50 ++- .../Querying/Structs/FilterInfo.cs | 15 +- TCAdminApiSharp/Querying/Structs/OrderInfo.cs | 13 +- TCAdminApiSharp/Querying/Structs/WhereInfo.cs | 15 +- TCAdminApiSharp/TCAdminApiSharp.csproj | 20 +- TCAdminApiSharp/TcaClient.cs | 105 +++-- TCAdminApiSharp/TcaClientSettings.cs | 25 +- 51 files changed, 1841 insertions(+), 1626 deletions(-) create mode 100644 TCAdminApiSharp.Tests/ServerTests.cs create mode 100644 TCAdminApiSharp.Tests/appsettings.json create mode 100644 TCAdminApiSharp.Tests/appsettings.local.json create mode 100644 TCAdminApiSharp/Entities/Service/FileManager/CompressModel.cs create mode 100644 TCAdminApiSharp/Entities/Service/FileManager/DirectoryListing.cs create mode 100644 TCAdminApiSharp/Entities/Service/FileManager/FileInfo.cs create mode 100644 TCAdminApiSharp/Entities/Service/FileManager/FileManagerService.cs delete mode 100644 TCAdminApiSharp/Exceptions/API/ApiRequestException.cs delete mode 100644 TCAdminApiSharp/Exceptions/NotFoundException.cs diff --git a/.github/workflows/Publish - Dev.yml b/.github/workflows/Publish - Dev.yml index 152984b..17cf35b 100644 --- a/.github/workflows/Publish - Dev.yml +++ b/.github/workflows/Publish - Dev.yml @@ -2,7 +2,7 @@ name: Dev - Build + Deploy on: push: - branches: [ dev-*, dev/** ] + branches: [ dev-*, dev/**, develop, develop/* ] jobs: build: @@ -12,22 +12,16 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: 5.0.100 - - name: Restore dependencies - run: dotnet restore - - name: Build - run: dotnet build --no-restore - - name: Test - run: dotnet test --no-build --verbosity normal - - name: Get DateTime - id: datetime - run: echo "::set-output name=date::$(date +'%Y%m%d-%H%M%S')" - - name: Deploy - Dev - uses: alexr03/publish-nuget@master + dotnet-version: 6.0.x + + - name: Build Nuget Packages + run: "mkdir build && dotnet pack -p:IncludeSymbols=true -p:SymbolPackageFormat=snupkg --include-source -o build -p:VersionSuffix='nightly' -p:BuildNumber=0$((${{ github.run_number }} ))" + + - name: Publish Nuget Packages + run: "dotnet nuget push \"build/*\" -k ${{ secrets.ALEX_NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json" + + - name: "Upload Nuget Packages To Github Actions" + uses: actions/upload-artifact@v3 with: - PROJECT_FILE_PATH: TCAdminApiSharp/TCAdminApiSharp.csproj - NUGET_KEY: ${{secrets.ALEX_NUGET_API_KEY}} - VERSION_REGEX: ^\s*(.*)<\/AssemblyVersion>\s*$ - VERSION_SUFFIX: -dev-${{steps.datetime.outputs.date}}-${{github.run_number}} - TAG_FORMAT: dev-v* - INCLUDE_SYMBOLS: true + name: PR Nuget Packages + path: build/* \ No newline at end of file diff --git a/TCAdminApiSharp.Tests/ClientTests.cs b/TCAdminApiSharp.Tests/ClientTests.cs index 19e8a06..9b08ed8 100644 --- a/TCAdminApiSharp.Tests/ClientTests.cs +++ b/TCAdminApiSharp.Tests/ClientTests.cs @@ -1,26 +1,25 @@ using System; using NUnit.Framework; -namespace TCAdminApiSharp.Tests +namespace TCAdminApiSharp.Tests; + +public class ClientTests { - public class ClientTests + [Test] + public void CreateClientWithoutHost() { - [Test] - public void CreateClientWithoutHost() + Assert.Catch(() => { - Assert.Catch(() => - { - var _ = new TcaClient("", "-"); - }); - } + var _ = new TcaClient("", "-"); + }); + } - [Test] - public void CreateClientWithoutToken() + [Test] + public void CreateClientWithoutToken() + { + Assert.Catch(() => { - Assert.Catch(() => - { - var _ = new TcaClient("https://4a815e4e-aaa8-4351-a948-5ca3f92e5c8b.mock.pstmn.io", ""); - }); - } + var _ = new TcaClient("https://4a815e4e-aaa8-4351-a948-5ca3f92e5c8b.mock.pstmn.io", ""); + }); } } \ No newline at end of file diff --git a/TCAdminApiSharp.Tests/ServerTests.cs b/TCAdminApiSharp.Tests/ServerTests.cs new file mode 100644 index 0000000..5a6fcdd --- /dev/null +++ b/TCAdminApiSharp.Tests/ServerTests.cs @@ -0,0 +1,39 @@ +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using NUnit.Framework; + +namespace TCAdminApiSharp.Tests; + +public class ServerTests +{ + private TcaClient _tcaClient; + + [SetUp] + public void Setup() + { + var config = new ConfigurationBuilder().AddJsonFile("appsettings.json") + .AddJsonFile("appsettings.local.json", true) + .Build().GetSection("TCAdmin"); + var activeProfile = config["ActiveProfile"]; + var profileSection = config.GetSection("Profiles").GetSection(activeProfile); + var host = profileSection["Host"]; + var key = profileSection["Key"]; + _tcaClient = new TcaClient(host, key, TcaClientSettings.Debug); + } + + [Test] + public async Task GetServerTest() + { + var server = await _tcaClient.ServersController.GetServer(1); + Assert.AreEqual("Master", server.Name); + } + + // [Test] + // public async Task GetServersTest() + // { + // var server = await _tcaClient.ServersController.GetServers(); + // Assert.IsTrue(server.Success); + // Assert.AreEqual(1, server.Result.Count); + // Assert.AreEqual("Master", server.Result[0].Name); + // } +} \ No newline at end of file diff --git a/TCAdminApiSharp.Tests/ServiceTests.cs b/TCAdminApiSharp.Tests/ServiceTests.cs index 6d0fa29..d0c54c9 100644 --- a/TCAdminApiSharp.Tests/ServiceTests.cs +++ b/TCAdminApiSharp.Tests/ServiceTests.cs @@ -1,105 +1,155 @@ using System; -using System.Collections.Generic; using System.Threading.Tasks; -using Newtonsoft.Json.Linq; +using Microsoft.Extensions.Configuration; using NUnit.Framework; -using Serilog.Events; using TCAdminApiSharp.Entities.Service; -using TCAdminApiSharp.Exceptions; using TCAdminApiSharp.Exceptions.API; -namespace TCAdminApiSharp.Tests +namespace TCAdminApiSharp.Tests; + +public class ServiceTests { - public class ServiceTests - { - private TcaClient _tcaClient; + private TcaClient _tcaClient; - [SetUp] - public void Setup() - { - _tcaClient = new TcaClient("https://4a815e4e-aaa8-4351-a948-5ca3f92e5c8b.mock.pstmn.io", "-", TcaClientSettings.Debug); - } + [SetUp] + public void Setup() + { + var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").AddJsonFile("appsettings.local.json", true).Build().GetSection("TCAdmin"); + var activeProfile = config["ActiveProfile"]; + var profileSection = config.GetSection("Profiles").GetSection(activeProfile); + var host = profileSection["Host"]; + var key = profileSection["Key"]; + _tcaClient = new TcaClient(host, key, TcaClientSettings.Debug); + } - [Test] - public async Task GetServiceTest() - { - var service = await _tcaClient.ServicesController.GetService(2); - Assert.AreEqual(2, service.ServiceId); - } + [Test] + public async Task GetServiceTest() + { + var service = await _tcaClient.ServicesController.GetService(1); + Assert.AreEqual(1, service.ServiceId); + } + + [Test] + public async Task ServiceStart() + { + var service = await _tcaClient.ServicesController.GetService(1); + await service.Start(); + service = await _tcaClient.ServicesController.GetService(1); + Assert.AreEqual(ServiceStatus.Running, service.ServiceStatus); + } - [Test] - public async Task GetServicesListTest() - { - var services = await _tcaClient.ServicesController.GetServices(); - Assert.AreEqual(2, services.VirtualCount); - } + [Test] + public async Task GetServicesListTest() + { + var services = await _tcaClient.ServicesController.GetServices(); + Assert.AreEqual(2, services.Count); + } - [Test] - public void GetServiceExceptionTest() + [Test] + public async Task GetServiceExceptionTest() + { + Assert.ThrowsAsync(async () => { - try - { - var _ = _tcaClient.ServicesController.GetService(-1); - } - catch (ApiResponseException e) - { - Console.WriteLine(e.ErrorResponse); - } - } + var service = await _tcaClient.ServicesController.GetService(-1); + Console.WriteLine(service.ServiceId); + }); + } + + [Test] + public async Task GetServiceFileManagerService() + { + var service = await _tcaClient.ServicesController.GetService(3); + Assert.NotNull(service.FileManagerService); + } + + [Test] + public async Task FileManagerGetFileInfo() + { + var service = await _tcaClient.ServicesController.GetService(3); + var fileInfo = await service.FileManagerService.GetFileInfo("/cfg/server.cfg"); + Assert.AreEqual("server.cfg", fileInfo.Name); + Assert.AreEqual(".cfg", fileInfo.Extension); + } + + [Test] + public async Task FileManagerCopyFileInfo() + { + var service = await _tcaClient.ServicesController.GetService(3); + var fileInfo = await service.FileManagerService.GetFileInfo("/cfg/server.cfg"); + var copy = await fileInfo.Copy("/cfg2"); + Assert.IsTrue(copy); + } + + [Test] + public async Task FileManagerCompressDirectory() + { + var service = await _tcaClient.ServicesController.GetService(3); + var directoryListing = await service.FileManagerService.GetDirectoryListing("/cfg"); + var compressModel = await directoryListing.Compress("/cfg2"); + Assert.IsNotNull(compressModel.Zip); + } - [Test] - public async Task UpdateServiceTest() + [Test] + public async Task UpdateServiceTest() + { + var service = await _tcaClient.ServicesController.GetService(1); + Assert.AreEqual(1, service.ServiceId); + await service.Update(x => { - var service = await _tcaClient.ServicesController.GetService(1); - await service.Update(x => - { - x.Slots = 12; - x.Executable = "changed.exe"; - }); - - Assert.Pass("Service Updated"); - } + x.Slots = 5; + // x.Executable = "changed.exe"; + }); + } - [Test] - public async Task UpdateServiceExceptionTest() - { - var service = await _tcaClient.ServicesController.GetService(2); - try - { - await service.Update(x => - { - x.Slots = 12; - x.Executable = "changed.exe"; - }); - } - catch (ApiResponseException e) - { - var result = ((JObject) e.ErrorResponse.Result).ToObject(); - if (result?.Source == "TCAdmin.Web.MVC") //todo Update this to the specific Update Service exception type. - { - Assert.Pass("Correct exception returned"); - } - Console.WriteLine(result); - } - - Assert.Fail("No exception"); - } + // [Test] + // public async Task UpdateServiceExceptionTest() + // { + // var service = await _tcaClient.ServicesController.GetService(2); + // try + // { + // await service.Update(x => + // { + // x.Slots = 12; + // x.Executable = "changed.exe"; + // }); + // } + // catch (ApiResponseException e) + // { + // var result = (e.HttpResponseMessage).ToObject(); + // if (result?.Source == "TCAdmin.Web.MVC") //todo Update this to the specific Update Service exception type. + // { + // Assert.Pass("Correct exception returned"); + // } + // Console.WriteLine(result); + // } + // + // Assert.Fail("No exception"); + // } - // [Test] - // public void ServiceCreateJsonTest() - // { - // var serviceBuilder = new ServiceBuilder() - // .WithAutomaticPort(true) - // .WithGameId(12) - // .WithBranded(true) - // .WithDatacenterId(1) - // .WithVariables(new Dictionary() - // { - // {"test", 123} - // }) - // .WithSlots(100) - // .WithBillingId("100Not4Me"); - // _tcaClient.ServicesController.CreateService(serviceBuilder); - // } - } + // [Test] + // public async Task ServiceCreateJsonTest() + // { + // var serviceBuilder = new ServiceBuilder() + // .WithAutomaticPort(true) + // .WithGameId(67) + // .WithBranded(true) + // .WithDatacenterId(1) + // // .WithVariables(new TcaXmlField() + // // { + // // {"test", 123} + // // }) + // .WithSlots(100) + // .WithBillingId("100Not4Me"); + // try + // { + // var service = await _tcaClient.ServicesController.CreateService(serviceBuilder); + // Console.WriteLine("Sv: " + service); + // } + // catch (ApiResponseException e) + // { + // Console.WriteLine(e.ExceptionResponse.Success); + // Console.WriteLine(e.ExceptionResponse.Message); + // throw; + // } + // } } \ No newline at end of file diff --git a/TCAdminApiSharp.Tests/TCAdminApiSharp.Tests.csproj b/TCAdminApiSharp.Tests/TCAdminApiSharp.Tests.csproj index d8cfe75..05440cf 100644 --- a/TCAdminApiSharp.Tests/TCAdminApiSharp.Tests.csproj +++ b/TCAdminApiSharp.Tests/TCAdminApiSharp.Tests.csproj @@ -1,19 +1,30 @@ - net5.0 + net6.0 false - - - + + + + + + + + Always + + + Always + + + diff --git a/TCAdminApiSharp.Tests/appsettings.json b/TCAdminApiSharp.Tests/appsettings.json new file mode 100644 index 0000000..b758d66 --- /dev/null +++ b/TCAdminApiSharp.Tests/appsettings.json @@ -0,0 +1,11 @@ +{ + "TCAdmin": { + "ActiveProfile": "Mock", + "Profiles": { + "Mock": { + "Host": "https://dbc851a7-3a7a-4a85-8b02-8ad9fa519e3c.mock.pstmn.io", + "Key": "mock-key" + } + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp.Tests/appsettings.local.json b/TCAdminApiSharp.Tests/appsettings.local.json new file mode 100644 index 0000000..c793369 --- /dev/null +++ b/TCAdminApiSharp.Tests/appsettings.local.json @@ -0,0 +1,11 @@ +{ + "TCAdmin": { + "ActiveProfile": "Admin", + "Profiles": { + "Admin": { + "Host": "http://tcadmin-d01/api", + "Key": "oD50BKoFaOABml9Ax+o3wY3nk18FsI6FhOJwepc2TGFaWfu4lbfb5FfeSrh3/zBOVgJq/VwxKZRGBwwGEy352B/wQqP7Fh5gQ8lTEdWfMT/McK3F9Pcbuj94MJ1vgfzW9Od0Dat5JkZbziZRc7YQMzL9xYzLXC2zVlmE5o91Qfc030SPyBHifKq8d5KVRaKbO0lwO+1+lZrb4dDl8zRog5SoleZYiSXNhPE1Qj2z8d4=" + } + } + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index af07398..c83dd00 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -1,119 +1,155 @@ using System; +using System.Collections; +using System.Collections.Generic; using System.Linq; -using System.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; -using RestSharp; using Serilog; using TCAdminApiSharp.Entities.API; +using TCAdminApiSharp.Entities.Generic; using TCAdminApiSharp.Exceptions.API; +using TCAdminApiSharp.Helpers; using TCAdminApiSharp.Querying; -namespace TCAdminApiSharp.Controllers -{ - public class BaseController - { - public readonly TcaClient TcaClient = - TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); +namespace TCAdminApiSharp.Controllers; - public readonly string BaseResource; - internal readonly ILogger Logger; +public class BaseController +{ + public readonly TcaClient TcaClient; + public readonly string BaseResource; + internal readonly ILogger Logger; - protected BaseController(string baseResource) - { - Logger = Log.ForContext(GetType()); - BaseResource = baseResource; + protected BaseController(TcaClient tcaClient, string baseResource) + { + Logger = Log.ForContext(GetType()); + TcaClient = tcaClient; + BaseResource = baseResource; - if (!baseResource.EndsWith("/")) BaseResource = baseResource + "/"; - } + if (!baseResource.EndsWith("/")) BaseResource = baseResource + "/"; + } + + public HttpRequestMessage GenerateDefaultRequest() + { + var httpRequestMessage = new HttpRequestMessage(); + httpRequestMessage.RequestUri = Append(new Uri(BaseResource, UriKind.RelativeOrAbsolute)); + return httpRequestMessage; + } - public RestRequest GenerateDefaultRequest() - { - return new RestRequest(BaseResource); - } + public HttpRequestMessage GenerateDefaultRequest(params string[] paths) + { + var httpRequestMessage = new HttpRequestMessage(); + httpRequestMessage.RequestUri = Append(new Uri(BaseResource, UriKind.RelativeOrAbsolute), paths); + return httpRequestMessage; + } + + public HttpRequestMessage GenerateDefaultRequest(HttpMethod httpMethod, params string[] paths) + { + var httpRequestMessage = new HttpRequestMessage(); + httpRequestMessage.RequestUri = Append(new Uri(BaseResource, UriKind.RelativeOrAbsolute), paths); + httpRequestMessage.Method = httpMethod; + return httpRequestMessage; + } - public async Task> AdvancedRequest(string resource, QueryableInfo query, Method method = Method.POST) - { - var request = GenerateDefaultRequest(); - request.Method = method; - request.Resource += resource; - query.BuildQuery(request); - return await ExecuteBaseResponseRequest(request); - } + public async Task> AdvancedRequest(string resource, QueryableInfo query, HttpMethod method) + { + var request = GenerateDefaultRequest(resource); + request.Method = method; + query.BuildQuery(request); + return await ExecuteBaseResponseRequest(request); + } - public async Task> AdvancedListRequest(string resource, QueryableInfo query, Method method = Method.POST) - { - var request = GenerateDefaultRequest(); - request.Method = method; - request.Resource += resource; - query.BuildQuery(request); - return await ExecuteListResponseRequest(request); - } + public async Task> AdvancedListRequest(string resource, QueryableInfo query, HttpMethod method) + { + var request = GenerateDefaultRequest(resource); + request.Method = method; + query.BuildQuery(request); + return await ExecuteListResponseRequest(request); + } - public async Task ExecuteBaseResponseRequest(RestRequest request) - { - var (baseResponse, restResponse) = await ExecuteRequestAsync(request); - baseResponse.RestResponse = restResponse; - return baseResponse; - } + public async Task ExecuteBaseResponseRequest(HttpRequestMessage requestMessage) + { + var (baseResponse, httpResponse) = await ExecuteRequestAsync(requestMessage); + baseResponse.RequestMessage = requestMessage; + baseResponse.ResponseMessage = httpResponse; + return baseResponse; + } - public async Task> ExecuteBaseResponseRequest(RestRequest request) + public async Task> ExecuteBaseResponseRequest(HttpRequestMessage requestMessage) + { + var (baseResponse, httpResponse) = await ExecuteRequestAsync>(requestMessage); + baseResponse.RequestMessage = requestMessage; + baseResponse.ResponseMessage = httpResponse; + return baseResponse; + } + + public async Task> ExecuteListResponseRequest(HttpRequestMessage requestMessage) + { + var (baseResponse, restResponse) = await ExecuteRequestAsync>(requestMessage); + return baseResponse; + } + + public async Task> ExecuteRequestAsync(HttpRequestMessage request) + { + Logger.Debug("Request: {Request}", request.ToString()); + var httpResponseMessage = await TcaClient.HttpClient.SendAsync(request); + Logger.Debug("Response: {Response}", httpResponseMessage.ToString()); + var strResponse = await httpResponseMessage.Content.ReadAsStringAsync(); + if (!httpResponseMessage.IsSuccessStatusCode) { - var (item1, item2) = await ExecuteRequestAsync>(request); - item1.RestResponse = item2; - return item1; + if (!TcaClient.Settings.ThrowOnApiResponseStatusNonComplete) + return new Tuple(default!, httpResponseMessage); + + if (!string.IsNullOrEmpty(strResponse)) + { + var exceptionResponse = JsonConvert.DeserializeObject>(strResponse); + throw new ApiResponseException(httpResponseMessage, exceptionResponse); + } + + throw new ApiResponseException(httpResponseMessage, "Response Status Code is: " + httpResponseMessage.StatusCode); } - public async Task> ExecuteListResponseRequest(RestRequest request) + var response = + JsonConvert.DeserializeObject(strResponse, Constants.IgnoreDefaultValues); + if (response != null) ApplyObjectBaseTCAClient(response, true); + + return new Tuple(response, httpResponseMessage);; + } + + public void ApplyObjectBaseTCAClient(object obj, bool recursive) + { + var type = obj.GetType(); + // if (type.IsSubclassOf(typeof(ITCAdminClientCompatible))) + if (typeof(ITCAdminClientCompatible).IsAssignableFrom(type)) { - var (baseResponse, restResponse) = await ExecuteRequestAsync>(request); - baseResponse.RestResponse = restResponse; - return baseResponse; + type.GetProperty(nameof(ITCAdminClientCompatible.TcaClient))?.SetValue(obj, TcaClient); } - public async Task> ExecuteRequestAsync(RestRequest request) + if (recursive) { - Logger.Debug($"Request URL [{request.Method}]: {TcaClient.RestClient.BuildUri(request)}"); - var restResponse = await TcaClient.RestClient.ExecuteAsync(request); - Logger.Debug("Response Status: " + restResponse.ResponseStatus); - Logger.Debug("Status Code: " + restResponse.StatusCode); - Logger.Debug("Parameters:"); - foreach (var requestParameter in request.Parameters) + if (type.IsSubclassOf(typeof(BaseResponse))) { - Logger.Debug(requestParameter.ToString()); - } - if (restResponse.ResponseStatus != ResponseStatus.Completed) - { - if (!TcaClient.Settings.ThrowOnApiResponseStatusNonComplete) - return new Tuple(default!, restResponse); - throw new ApiResponseException(restResponse, "Response Status is: " + restResponse.ResponseStatus); + var value = type.GetProperty("Result")?.GetValue(obj); + if (value != null) + { + ApplyObjectBaseTCAClient(value, recursive); + } } - if (restResponse.StatusCode != HttpStatusCode.OK) + if (typeof(IEnumerable).IsAssignableFrom(type)) { - if (!TcaClient.Settings.ThrowOnApiStatusCodeNonOk) - return new Tuple(default!, restResponse); - throw new ApiResponseException(restResponse, $"Status code is: {restResponse.StatusCode}\n{restResponse.Content}"); + var enumerable = (IEnumerable)obj; + foreach (var o in enumerable) + { + ApplyObjectBaseTCAClient(o, recursive); + } } - - var baseResponse = - JsonConvert.DeserializeObject>(restResponse - .Content); // First deserialize to the base response - baseResponse.RestResponse = restResponse; - if (!baseResponse.Success) - { - var tType = typeof(T); - if (tType.GenericTypeArguments.Contains(baseResponse.Result.GetType())) - return new Tuple(JsonConvert.DeserializeObject(restResponse.Content), - restResponse); - - if (!TcaClient.Settings.ThrowOnApiSuccessFailure) - return new Tuple(default!, restResponse); - throw new ApiResponseException(restResponse, "API returned an error"); - } - - return new Tuple(JsonConvert.DeserializeObject(restResponse.Content), restResponse); } } + + public static Uri Append(Uri uri, params string[] paths) + { + return new Uri(paths.Aggregate(uri.ToString(), (current, path) => + $"{current.TrimEnd('/')}/{path.TrimStart('/')}"), UriKind.RelativeOrAbsolute); + } } \ No newline at end of file diff --git a/TCAdminApiSharp/Controllers/ServersController.cs b/TCAdminApiSharp/Controllers/ServersController.cs index b36684a..f6dab2d 100644 --- a/TCAdminApiSharp/Controllers/ServersController.cs +++ b/TCAdminApiSharp/Controllers/ServersController.cs @@ -1,51 +1,27 @@ -using System.Net; -using System.Threading.Tasks; +using System.Threading.Tasks; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Server; -using TCAdminApiSharp.Entities.Service; -using TCAdminApiSharp.Exceptions; -using TCAdminApiSharp.Exceptions.API; -namespace TCAdminApiSharp.Controllers +namespace TCAdminApiSharp.Controllers; + +public class ServersController : BaseController { - public class ServersController : BaseController + public ServersController(TcaClient tcaClient) : base(tcaClient, "api/server") { - public ServersController() : base("api/server") - { - } - - // public int CreateService(ServiceBuilder builder) - // { - // var body = builder.GenerateRequestBody(); - // var request = GenerateDefaultRequest(); - // request.Resource += "create"; - // request.Method = Method.POST; - // request.AddParameter("createinfo", body, ParameterType.GetOrPost); - // return ExecuteBaseResponseRequest(request).Result; - // } + } - public async Task GetServer(int serverId) - { - try - { - var request = GenerateDefaultRequest(); - request.Resource += serverId; - return (await ExecuteBaseResponseRequest(request)).Result; - } - catch (ApiResponseException e) - { - if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - throw new NotFoundException(typeof(Service), e, new[] {serverId}); + public async Task GetServer(int serverId) + { + var request = GenerateDefaultRequest(serverId.ToString()); + var result = (await ExecuteBaseResponseRequest(request)).Result; + return result; + } - throw; - } - } + public async Task> GetServers() + { + var request = GenerateDefaultRequest(); + var result = await ExecuteListResponseRequest(request); - public Task> GetServers() - { - var request = GenerateDefaultRequest(); - request.Resource += "servers"; - return ExecuteListResponseRequest(request); - } + return result; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Controllers/ServicesController.cs b/TCAdminApiSharp/Controllers/ServicesController.cs index 1f4cab8..b54cf39 100644 --- a/TCAdminApiSharp/Controllers/ServicesController.cs +++ b/TCAdminApiSharp/Controllers/ServicesController.cs @@ -1,80 +1,63 @@ -using System; -using System.Net; +using System.Collections.Generic; +using System.Net.Http; using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using RestSharp; +using Microsoft.AspNetCore.WebUtilities; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Service; -using TCAdminApiSharp.Entities.User; -using TCAdminApiSharp.Exceptions; -using TCAdminApiSharp.Exceptions.API; using TCAdminApiSharp.Querying; using TCAdminApiSharp.Querying.Operations; using TCAdminApiSharp.Querying.Operators; -namespace TCAdminApiSharp.Controllers +namespace TCAdminApiSharp.Controllers; + +public class ServicesController : BaseController { - public class ServicesController : BaseController + public ServicesController(TcaClient tcaClient) : base(tcaClient, "api/service") { - public ServicesController() : base("api/service") - { - } - - public async Task CreateService(ServiceBuilder builder) - { - var body = builder.GenerateRequestBody(); - var request = GenerateDefaultRequest(); - request.Resource += "create"; - request.Method = Method.POST; - request.AddParameter("createinfo", body, ParameterType.GetOrPost); - var response = await ExecuteBaseResponseRequest(request); - return response.Result; - } + } - public async Task> FindServices(QueryableInfo query) - { - var request = GenerateDefaultRequest(); - request.Method = Method.POST; - request.Resource += "gameservices"; - query.BuildQuery(request); - return await ExecuteListResponseRequest(request); - } + public async Task CreateService(ServiceBuilder builder) + { + var body = builder.GenerateRequestBody(); + var request = GenerateDefaultRequest("create"); + request.Method = HttpMethod.Post; + request.Content = new FormUrlEncodedContent(new []{new KeyValuePair("createinfo", body)}); + var response = await ExecuteBaseResponseRequest(request); + return response.Result; + } - public async Task GetService(int serviceId) - { - try - { - var request = GenerateDefaultRequest(); - request.Resource += serviceId; - return (await ExecuteBaseResponseRequest(request)).Result; - } - catch (ApiResponseException e) - { - if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - throw new NotFoundException(typeof(Service), e, new[] {serviceId}); + public async Task> FindServices(QueryableInfo query) + { + var request = GenerateDefaultRequest("gameservices"); + request.Method = HttpMethod.Post;; + query.BuildQuery(request); + var result = await ExecuteListResponseRequest(request); + return result; + } - throw; - } - } + public async Task GetService(int serviceId) + { + var request = GenerateDefaultRequest(serviceId.ToString()); + var result = (await ExecuteBaseResponseRequest(request)).Result; + return result; + } - public async Task> GetServices() - { - var request = GenerateDefaultRequest(); - request.Resource += "gameservices"; - return await ExecuteListResponseRequest(request); - } + public async Task> GetServices() + { + var request = GenerateDefaultRequest("gameservices"); + var result = await ExecuteListResponseRequest(request); + return result; + } - public Task> GetServicesByBillingId(string billingId) - { - return FindServices(new QueryableInfo(new WhereList("BillingId", ColumnOperator.Equal, billingId))); - } + public Task> GetServicesByBillingId(string billingId) + { + return FindServices(new QueryableInfo(new WhereList("BillingId", ColumnOperator.Equal, billingId))); + } - public Task> GetServicesByUserId(int userId) - { - var request = GenerateDefaultRequest(); - request.Method = Method.GET; - request.Resource += $"gameservices?{nameof(userId)}={userId}"; - return ExecuteListResponseRequest(request); - } + public async Task> GetServicesByUserId(int userId) + { + var request = GenerateDefaultRequest(QueryHelpers.AddQueryString("gameservices", nameof(userId), userId.ToString())); + var result = await ExecuteListResponseRequest(request); + return result; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Controllers/TasksController.cs b/TCAdminApiSharp/Controllers/TasksController.cs index eb3a512..ee36202 100644 --- a/TCAdminApiSharp/Controllers/TasksController.cs +++ b/TCAdminApiSharp/Controllers/TasksController.cs @@ -1,52 +1,34 @@ -using System.Net; +using System; using System.Threading.Tasks; -using RestSharp; +using Microsoft.AspNetCore.WebUtilities; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Task; -using TCAdminApiSharp.Entities.User; -using TCAdminApiSharp.Exceptions; -using TCAdminApiSharp.Exceptions.API; using Task = TCAdminApiSharp.Entities.Task.Task; -namespace TCAdminApiSharp.Controllers +namespace TCAdminApiSharp.Controllers; + +public class TasksController : BaseController { - public class TasksController : BaseController + public TasksController(TcaClient tcaClient) : base(tcaClient, "api/task") { - public TasksController() : base("api/task") - { - } - - public async Task GetTask(int taskId) - { - try - { - var request = GenerateDefaultRequest(); - request.Resource += taskId; - return (await ExecuteBaseResponseRequest(request)).Result; - } - catch (ApiResponseException e) - { - if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - throw new NotFoundException(typeof(Task), e, new[] {taskId}); + } - throw; - } - } + public async Task GetTask(int taskId) + { + var request = GenerateDefaultRequest(taskId.ToString()); + return (await ExecuteBaseResponseRequest(request)).Result; + } - public Task> GetPendingTasks(int serverId) - { - var request = GenerateDefaultRequest(); - request.Resource += "getpendingtasks"; - request.AddParameter("serverId", serverId, ParameterType.QueryString); - return ExecuteListResponseRequest(request); - } + public Task> GetPendingTasks(int serverId) + { + var request = GenerateDefaultRequest(QueryHelpers.AddQueryString("getpendingtasks", nameof(serverId), serverId.ToString())); + return ExecuteListResponseRequest(request); + } - public Task> GetTaskSteps(int taskId) - { - var request = GenerateDefaultRequest(); - request.Resource = "api/taskstep/getsteps"; - request.AddParameter("taskId", taskId, ParameterType.QueryString); - return ExecuteListResponseRequest(request); - } + public Task> GetTaskSteps(int taskId) + { + var request = GenerateDefaultRequest(); + request.RequestUri = new Uri(QueryHelpers.AddQueryString("api/taskstep/getsteps", nameof(taskId), taskId.ToString()), UriKind.RelativeOrAbsolute); + return ExecuteListResponseRequest(request); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Controllers/UsersController.cs b/TCAdminApiSharp/Controllers/UsersController.cs index add77d1..48c90c6 100644 --- a/TCAdminApiSharp/Controllers/UsersController.cs +++ b/TCAdminApiSharp/Controllers/UsersController.cs @@ -1,77 +1,50 @@ -using System.Net; +using System.Net.Http; using System.Threading.Tasks; -using RestSharp; using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.User; -using TCAdminApiSharp.Exceptions; -using TCAdminApiSharp.Exceptions.API; using TCAdminApiSharp.Querying; -namespace TCAdminApiSharp.Controllers +namespace TCAdminApiSharp.Controllers; + +public class UsersController : BaseController { - public class UsersController : BaseController + public UsersController(TcaClient tcaClient) : base(tcaClient, "api/user") { - public UsersController() : base("api/user") - { - } + } - public async Task GetUser(int userId) - { - try - { - var request = GenerateDefaultRequest(); - request.Resource += userId; - var response = await ExecuteBaseResponseRequest(request); - return response.Result; - } - catch (ApiResponseException e) - { - if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - throw new NotFoundException(typeof(User), e, new[] {userId}); - throw; - } - } + public async Task GetUser(int userId) + { + var request = GenerateDefaultRequest(userId.ToString()); + var response = await ExecuteBaseResponseRequest(request); + return response.Result; + } - public async Task GetMe() - { - try - { - var request = GenerateDefaultRequest(); - request.Resource += "me"; - var response = await ExecuteBaseResponseRequest(request); - return response.Result; - } - catch (ApiResponseException e) - { - if (e.ErrorResponse.RestResponse.StatusCode == HttpStatusCode.NotFound) - throw new NotFoundException(typeof(User), e, new[] {TcaClient.GetTokenUserId()}); - throw; - } - } + public async Task GetMe() + { + var request = GenerateDefaultRequest("me"); + var response = await ExecuteBaseResponseRequest(request); + return response.Result; + } - public async Task> FindUsers(QueryableInfo query) - { - var request = GenerateDefaultRequest(); - // Logger.Debug(query.BuildQuery(request)); - request.Method = Method.POST; - request.Resource += $"users/{TcaClient.GetTokenUserId()}"; - // request.AddParameter("queryInfo", query.BuildQuery(request), ParameterType.GetOrPost); - query.BuildQuery(request); - return await ExecuteListResponseRequest(request); - } + public async Task> FindUsers(QueryableInfo query) + { + var request = GenerateDefaultRequest("users", TcaClient.GetTokenUserId().ToString()); + // Logger.Debug(query.BuildQuery(request)); + request.Method = HttpMethod.Post; + // request.AddParameter("queryInfo", query.BuildQuery(request), ParameterType.GetOrPost); + query.BuildQuery(request); + return await ExecuteListResponseRequest(request); + } - public async Task> GetMyUsers() - { - var request = GenerateDefaultRequest(); - request.Resource += "myusers"; - return await ExecuteListResponseRequest(request); - } + public async Task> GetMyUsers() + { + var request = GenerateDefaultRequest("myusers"); + return await ExecuteListResponseRequest(request); + } - public async Task> GetUsers() - { - var request = GenerateDefaultRequest(); - request.Resource += $"users/{TcaClient.GetTokenUserId()}"; - return await ExecuteListResponseRequest(request); - } + public async Task> GetUsers() + { + var request = GenerateDefaultRequest("users", TcaClient.GetTokenUserId().ToString()); + return await ExecuteListResponseRequest(request); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/API/BaseResponse.cs b/TCAdminApiSharp/Entities/API/BaseResponse.cs index 503a0e5..beba987 100644 --- a/TCAdminApiSharp/Entities/API/BaseResponse.cs +++ b/TCAdminApiSharp/Entities/API/BaseResponse.cs @@ -1,28 +1,28 @@ -using Newtonsoft.Json; -using RestSharp; +using System.Net.Http; +using Newtonsoft.Json; -namespace TCAdminApiSharp.Entities.API +namespace TCAdminApiSharp.Entities.API; + +public class BaseResponse { - public class BaseResponse - { - // Default to true - [JsonProperty("Success")] public bool Success { get; private set; } = true; + // Default to true + [JsonProperty("Success")] public bool Success { get; private set; } = true; - [JsonProperty("Message")] public string? Message { get; private set; } + [JsonProperty("Message")] public string? Message { get; private set; } - [JsonIgnore] public IRestResponse RestResponse { get; internal set; } + [JsonIgnore] public HttpResponseMessage ResponseMessage { get; internal set; } + [JsonIgnore] public HttpRequestMessage RequestMessage { get; internal set; } - internal BaseResponse() - { - } + internal BaseResponse() + { } +} - public class BaseResponse : BaseResponse - { - [JsonProperty("Result")] public T Result { get; private set; } +public class BaseResponse : BaseResponse +{ + [JsonProperty("Result")] public T Result { get; private set; } - internal BaseResponse() - { - } + internal BaseResponse() + { } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/API/ErrorResponse.cs b/TCAdminApiSharp/Entities/API/ErrorResponse.cs index ed3ce77..de6d397 100644 --- a/TCAdminApiSharp/Entities/API/ErrorResponse.cs +++ b/TCAdminApiSharp/Entities/API/ErrorResponse.cs @@ -1,23 +1,22 @@ using System; +using System.Net.Http; using Newtonsoft.Json; -using RestSharp; -namespace TCAdminApiSharp.Entities.API +namespace TCAdminApiSharp.Entities.API; + +public class ErrorResponse : BaseResponse { - public class ErrorResponse : BaseResponse + internal ErrorResponse(HttpResponseMessage responseMessage) { - internal ErrorResponse(IRestResponse restResponse) + try { - try - { - JsonConvert.PopulateObject(restResponse.Content, this); - } - catch (Exception e) - { - throw new Exception("Couldn't parse API error to object!", e); - } - - RestResponse = restResponse; + JsonConvert.PopulateObject(responseMessage.Content.ReadAsStringAsync().Result, this); } + catch (Exception e) + { + throw new Exception("Couldn't parse API error to object!", e); + } + + ResponseMessage = responseMessage; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/API/ListResponse.cs b/TCAdminApiSharp/Entities/API/ListResponse.cs index 508857a..2b1e540 100644 --- a/TCAdminApiSharp/Entities/API/ListResponse.cs +++ b/TCAdminApiSharp/Entities/API/ListResponse.cs @@ -1,14 +1,13 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace TCAdminApiSharp.Entities.API +namespace TCAdminApiSharp.Entities.API; + +public class ListResponse : BaseResponse> { - public class ListResponse : BaseResponse> - { - /// - /// Only returns when "RowCount" was specified in the request. - /// - [JsonProperty("VirtualCount")] - public int VirtualCount { get; internal set; } - } + /// + /// Only returns when "RowCount" was specified in the request. + /// + [JsonProperty("Count")] + public int Count { get; internal set; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Billing/BillingStatus.cs b/TCAdminApiSharp/Entities/Billing/BillingStatus.cs index 3b8734a..0e1642e 100644 --- a/TCAdminApiSharp/Entities/Billing/BillingStatus.cs +++ b/TCAdminApiSharp/Entities/Billing/BillingStatus.cs @@ -1,8 +1,7 @@ -namespace TCAdminApiSharp.Entities.Billing +namespace TCAdminApiSharp.Entities.Billing; + +public enum BillingStatus { - public enum BillingStatus - { - Active = 1, - Suspended = 2 - } + Active = 1, + Suspended = 2 } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Generic/IPowerable.cs b/TCAdminApiSharp/Entities/Generic/IPowerable.cs index e7e0961..68a951d 100644 --- a/TCAdminApiSharp/Entities/Generic/IPowerable.cs +++ b/TCAdminApiSharp/Entities/Generic/IPowerable.cs @@ -1,11 +1,10 @@ using System.Threading.Tasks; -namespace TCAdminApiSharp.Entities.Generic +namespace TCAdminApiSharp.Entities.Generic; + +public interface IPowerable { - public interface IPowerable - { - public Task Start(string reason = ""); - public Task Restart(string reason = ""); - public Task Stop(string reason = ""); - } + public Task Start(string reason = ""); + public Task Restart(string reason = ""); + public Task Stop(string reason = ""); } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Generic/ObjectBase.cs b/TCAdminApiSharp/Entities/Generic/ObjectBase.cs index 7b2e700..741065e 100644 --- a/TCAdminApiSharp/Entities/Generic/ObjectBase.cs +++ b/TCAdminApiSharp/Entities/Generic/ObjectBase.cs @@ -2,25 +2,32 @@ using System.Threading.Tasks; using Newtonsoft.Json; -namespace TCAdminApiSharp.Entities.Generic +namespace TCAdminApiSharp.Entities.Generic; + +public class ObjectBase : ITCAdminClientCompatible { - public class ObjectBase - { - [JsonProperty("AppData")] public TcaXmlField AppData { get; set; } + [JsonProperty("AppData")] public TcaXmlField AppData { get; set; } + + [JsonProperty("CreatedOn")] public DateTime CreatedOn { get; set; } - [JsonProperty("CreatedOn")] public DateTime CreatedOn { get; set; } + [JsonProperty("CreatedBy")] public int CreatedBy { get; set; } - [JsonProperty("CreatedBy")] public int CreatedBy { get; set; } + [JsonProperty("ModifiedOn")] public DateTime ModifiedOn { get; set; } - [JsonProperty("ModifiedOn")] public DateTime ModifiedOn { get; set; } + [JsonProperty("ModifiedBy")] public int ModifiedBy { get; set; } + + // ReSharper disable once UnusedAutoPropertyAccessor.Global + [JsonIgnore] public TcaClient TcaClient { get; internal set; } +} - [JsonProperty("ModifiedBy")] public int ModifiedBy { get; set; } - } +public interface ITCAdminClientCompatible +{ + [JsonIgnore] public TcaClient TcaClient { get; } +} - public interface IObjectBaseCrud - { - public Task Update(Action action); +public interface IObjectBaseCrud +{ + public Task Update(Action action); - public Task Delete(); - } + public Task Delete(); } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Generic/TcaXmlField.cs b/TCAdminApiSharp/Entities/Generic/TcaXmlField.cs index d009119..0065840 100644 --- a/TCAdminApiSharp/Entities/Generic/TcaXmlField.cs +++ b/TCAdminApiSharp/Entities/Generic/TcaXmlField.cs @@ -1,15 +1,14 @@ using System.Collections.Generic; -namespace TCAdminApiSharp.Entities.Generic +namespace TCAdminApiSharp.Entities.Generic; + +public class TcaXmlField : Dictionary { - public class TcaXmlField : Dictionary + public TcaXmlField() { - public TcaXmlField() - { - } + } - public TcaXmlField(IDictionary dictionary) : base(dictionary) - { - } + public TcaXmlField(IDictionary dictionary) : base(dictionary) + { } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Server/Server.cs b/TCAdminApiSharp/Entities/Server/Server.cs index 7178113..789c833 100644 --- a/TCAdminApiSharp/Entities/Server/Server.cs +++ b/TCAdminApiSharp/Entities/Server/Server.cs @@ -1,262 +1,256 @@ using System; +using System.Net.Http; +using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; -using RestSharp; -using Microsoft.Extensions.DependencyInjection; -using TCAdminApiSharp.Controllers; using TCAdminApiSharp.Entities.Generic; using TCAdminApiSharp.Helpers; -namespace TCAdminApiSharp.Entities.Server -{ - public class Server : ObjectBase, IObjectBaseCrud - { - [JsonIgnore] private static readonly ServersController Controller = - TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); +namespace TCAdminApiSharp.Entities.Server; - [JsonProperty("DisableNewServices")] public bool DisableNewServices { get; set; } +public class Server : ObjectBase, IObjectBaseCrud +{ + [JsonProperty("DisableNewServices")] public bool DisableNewServices { get; set; } - [JsonProperty("GameFilesPath")] public string GameFilesPath { get; set; } + [JsonProperty("GameFilesPath")] public string GameFilesPath { get; set; } - [JsonProperty("VSUseCustomGameFiles")] public bool VSUseCustomGameFiles { get; set; } + [JsonProperty("VSUseCustomGameFiles")] public bool VsUseCustomGameFiles { get; set; } - [JsonProperty("ExtractSpeed")] public int ExtractSpeed { get; set; } + [JsonProperty("ExtractSpeed")] public int ExtractSpeed { get; set; } - [JsonProperty("UserFilesPath")] public string UserFilesPath { get; set; } + [JsonProperty("UserFilesPath")] public string UserFilesPath { get; set; } - [JsonProperty("FolderTemplate")] public string FolderTemplate { get; set; } + [JsonProperty("FolderTemplate")] public string FolderTemplate { get; set; } - [JsonProperty("KeepLocalCopy")] public bool KeepLocalCopy { get; set; } + [JsonProperty("KeepLocalCopy")] public bool KeepLocalCopy { get; set; } - [JsonProperty("LastServiceCreationUtc")] - public DateTime LastServiceCreationUtc { get; set; } + [JsonProperty("LastServiceCreationUtc")] + public DateTime LastServiceCreationUtc { get; set; } - [JsonProperty("EnableFileSharing")] public bool EnableFileSharing { get; set; } + [JsonProperty("EnableFileSharing")] public bool EnableFileSharing { get; set; } - [JsonProperty("EnableFastDownload")] public bool EnableFastDownload { get; set; } + [JsonProperty("EnableFastDownload")] public bool EnableFastDownload { get; set; } - [JsonProperty("ServerFileProviderModuleId")] - public string ServerFileProviderModuleId { get; set; } + [JsonProperty("ServerFileProviderModuleId")] + public string ServerFileProviderModuleId { get; set; } - [JsonProperty("ServerFileProviderId")] public int ServerFileProviderId { get; set; } + [JsonProperty("ServerFileProviderId")] public int ServerFileProviderId { get; set; } - [JsonProperty("ClientFileProviderModuleId")] - public string ClientFileProviderModuleId { get; set; } + [JsonProperty("ClientFileProviderModuleId")] + public string ClientFileProviderModuleId { get; set; } - [JsonProperty("ClientFileProviderId")] public int ClientFileProviderId { get; set; } + [JsonProperty("ClientFileProviderId")] public int ClientFileProviderId { get; set; } - [JsonProperty("ClientFileProviderSourceId")] - public int ClientFileProviderSourceId { get; set; } + [JsonProperty("ClientFileProviderSourceId")] + public int ClientFileProviderSourceId { get; set; } - [JsonProperty("FastDownloadFolderTemplate")] - public string FastDownloadFolderTemplate { get; set; } + [JsonProperty("FastDownloadFolderTemplate")] + public string FastDownloadFolderTemplate { get; set; } - [JsonProperty("FastDownloadSavePath")] public string FastDownloadSavePath { get; set; } + [JsonProperty("FastDownloadSavePath")] public string FastDownloadSavePath { get; set; } - [JsonProperty("FastDownloadUrl")] public string FastDownloadUrl { get; set; } + [JsonProperty("FastDownloadUrl")] public string FastDownloadUrl { get; set; } - [JsonProperty("ClientFastDownloadProviderModuleId")] - public string ClientFastDownloadProviderModuleId { get; set; } + [JsonProperty("ClientFastDownloadProviderModuleId")] + public string ClientFastDownloadProviderModuleId { get; set; } - [JsonProperty("ClientFastDownloadProviderId")] - public int ClientFastDownloadProviderId { get; set; } + [JsonProperty("ClientFastDownloadProviderId")] + public int ClientFastDownloadProviderId { get; set; } - [JsonProperty("ClientFastDownloadProviderSourceId")] - public int ClientFastDownloadProviderSourceId { get; set; } + [JsonProperty("ClientFastDownloadProviderSourceId")] + public int ClientFastDownloadProviderSourceId { get; set; } - [JsonProperty("NumberOfServices")] public int NumberOfServices { get; set; } + [JsonProperty("NumberOfServices")] public int NumberOfServices { get; set; } - [JsonProperty("NumberOfVoiceServices")] - public int NumberOfVoiceServices { get; set; } + [JsonProperty("NumberOfVoiceServices")] + public int NumberOfVoiceServices { get; set; } - [JsonProperty("NumberOfSlots")] public int NumberOfSlots { get; set; } + [JsonProperty("NumberOfSlots")] public int NumberOfSlots { get; set; } - [JsonProperty("NumberOfVoiceSlots")] public int NumberOfVoiceSlots { get; set; } + [JsonProperty("NumberOfVoiceSlots")] public int NumberOfVoiceSlots { get; set; } - [JsonProperty("MaxSlots")] public int MaxSlots { get; set; } + [JsonProperty("MaxSlots")] public int MaxSlots { get; set; } - [JsonProperty("SkipSuspendedServices")] - public bool SkipSuspendedServices { get; set; } + [JsonProperty("SkipSuspendedServices")] + public bool SkipSuspendedServices { get; set; } - [JsonProperty("SeparateVoiceSots")] public bool SeparateVoiceSots { get; set; } + [JsonProperty("SeparateVoiceSots")] public bool SeparateVoiceSots { get; set; } - [JsonProperty("MaxVoiceSlots")] public int MaxVoiceSlots { get; set; } + [JsonProperty("MaxVoiceSlots")] public int MaxVoiceSlots { get; set; } - [JsonProperty("MaxServices")] public int MaxServices { get; set; } + [JsonProperty("MaxServices")] public int MaxServices { get; set; } - [JsonProperty("SeparateVoiceServices")] - public bool SeparateVoiceServices { get; set; } + [JsonProperty("SeparateVoiceServices")] + public bool SeparateVoiceServices { get; set; } - [JsonProperty("MaxVoiceServices")] public int MaxVoiceServices { get; set; } + [JsonProperty("MaxVoiceServices")] public int MaxVoiceServices { get; set; } - [JsonProperty("ServerId")] public int ServerId { get; set; } + [JsonProperty("ServerId")] public int ServerId { get; set; } - [JsonProperty("PrivateNetworkId")] public int PrivateNetworkId { get; set; } + [JsonProperty("PrivateNetworkId")] public int PrivateNetworkId { get; set; } - [JsonProperty("PrivateNetworkIp")] public string PrivateNetworkIp { get; set; } + [JsonProperty("PrivateNetworkIp")] public string PrivateNetworkIp { get; set; } - [JsonProperty("DisableVirtualServerUser")] - public bool DisableVirtualServerUser { get; set; } + [JsonProperty("DisableVirtualServerUser")] + public bool DisableVirtualServerUser { get; set; } - [JsonProperty("UseCustomDatacenterId")] - public bool UseCustomDatacenterId { get; set; } + [JsonProperty("UseCustomDatacenterId")] + public bool UseCustomDatacenterId { get; set; } - [JsonProperty("DatacenterId")] public int DatacenterId { get; set; } + [JsonProperty("DatacenterId")] public int DatacenterId { get; set; } - [JsonProperty("OwnerId")] public int OwnerId { get; set; } + [JsonProperty("OwnerId")] public int OwnerId { get; set; } - [JsonProperty("OwnerIdFriendlyName")] public string OwnerIdFriendlyName { get; set; } + [JsonProperty("OwnerIdFriendlyName")] public string OwnerIdFriendlyName { get; set; } - [JsonProperty("IsMaster")] public bool IsMaster { get; set; } + [JsonProperty("IsMaster")] public bool IsMaster { get; set; } - [JsonProperty("OperatingSystem")] public int OperatingSystem { get; set; } + [JsonProperty("OperatingSystem")] public int OperatingSystem { get; set; } - [JsonProperty("PrimaryIp")] public string PrimaryIp { get; set; } + [JsonProperty("PrimaryIp")] public string PrimaryIp { get; set; } - [JsonProperty("SecurePort")] public int SecurePort { get; set; } + [JsonProperty("SecurePort")] public int SecurePort { get; set; } - [JsonProperty("StandardPort")] public int StandardPort { get; set; } + [JsonProperty("StandardPort")] public int StandardPort { get; set; } - [JsonProperty("BindAllIps")] public bool BindAllIps { get; set; } + [JsonProperty("BindAllIps")] public bool BindAllIps { get; set; } - [JsonProperty("FirewallIp")] public string FirewallIp { get; set; } + [JsonProperty("FirewallIp")] public string FirewallIp { get; set; } - [JsonProperty("Name")] public string Name { get; set; } + [JsonProperty("Name")] public string Name { get; set; } - [JsonProperty("Enabled")] public bool Enabled { get; set; } + [JsonProperty("Enabled")] public bool Enabled { get; set; } - [JsonProperty("DisableUpdates")] public bool DisableUpdates { get; set; } + [JsonProperty("DisableUpdates")] public bool DisableUpdates { get; set; } - [JsonProperty("MonitorVirtualDirectory")] - public string MonitorVirtualDirectory { get; set; } + [JsonProperty("MonitorVirtualDirectory")] + public string MonitorVirtualDirectory { get; set; } - [JsonProperty("PublicVirtualDirectory")] - public string PublicVirtualDirectory { get; set; } + [JsonProperty("PublicVirtualDirectory")] + public string PublicVirtualDirectory { get; set; } - [JsonProperty("ControlPanelEnableBasicAuth")] - public bool ControlPanelEnableBasicAuth { get; set; } + [JsonProperty("ControlPanelEnableBasicAuth")] + public bool ControlPanelEnableBasicAuth { get; set; } - [JsonProperty("ControlPanelRealm")] public string ControlPanelRealm { get; set; } + [JsonProperty("ControlPanelRealm")] public string ControlPanelRealm { get; set; } - [JsonProperty("ControlPanelLogOutUrl")] - public string ControlPanelLogOutUrl { get; set; } + [JsonProperty("ControlPanelLogOutUrl")] + public string ControlPanelLogOutUrl { get; set; } - [JsonProperty("WindowsFirewallEnabled")] - public bool WindowsFirewallEnabled { get; set; } + [JsonProperty("WindowsFirewallEnabled")] + public bool WindowsFirewallEnabled { get; set; } - [JsonProperty("uPnPPortForwardingEnabled")] - public bool UPnPPortForwardingEnabled { get; set; } + [JsonProperty("uPnPPortForwardingEnabled")] + public bool UPnPPortForwardingEnabled { get; set; } - [JsonProperty("MonitorLogin")] public string MonitorLogin { get; set; } + [JsonProperty("MonitorLogin")] public string MonitorLogin { get; set; } - [JsonProperty("MonitorPassword")] public string MonitorPassword { get; set; } + [JsonProperty("MonitorPassword")] public string MonitorPassword { get; set; } - [JsonProperty("MonitorVersion")] public string MonitorVersion { get; set; } + [JsonProperty("MonitorVersion")] public string MonitorVersion { get; set; } - [JsonProperty("FileSystemComparison")] public int FileSystemComparison { get; set; } + [JsonProperty("FileSystemComparison")] public int FileSystemComparison { get; set; } - [JsonProperty("FileSystemDirectorySeparator")] - public string FileSystemDirectorySeparator { get; set; } + [JsonProperty("FileSystemDirectorySeparator")] + public string FileSystemDirectorySeparator { get; set; } - [JsonProperty("DatacenterName")] public string DatacenterName { get; set; } + [JsonProperty("DatacenterName")] public string DatacenterName { get; set; } - [JsonProperty("IsVirtual")] public bool IsVirtual { get; set; } + [JsonProperty("IsVirtual")] public bool IsVirtual { get; set; } - [JsonProperty("RealServerId")] public int RealServerId { get; set; } + [JsonProperty("RealServerId")] public int RealServerId { get; set; } - [JsonProperty("RealServerName")] public string RealServerName { get; set; } + [JsonProperty("RealServerName")] public string RealServerName { get; set; } - [JsonProperty("KeepAlive")] public int KeepAlive { get; set; } + [JsonProperty("KeepAlive")] public int KeepAlive { get; set; } - [JsonProperty("NumberOfProcessors")] public int NumberOfProcessors { get; set; } + [JsonProperty("NumberOfProcessors")] public int NumberOfProcessors { get; set; } - [JsonProperty("MaxNumaNode")] public int MaxNumaNode { get; set; } + [JsonProperty("MaxNumaNode")] public int MaxNumaNode { get; set; } - [JsonProperty("MonitorAffinity")] public int MonitorAffinity { get; set; } + [JsonProperty("MonitorAffinity")] public int MonitorAffinity { get; set; } - [JsonProperty("MonitorNumaNode")] public int MonitorNumaNode { get; set; } + [JsonProperty("MonitorNumaNode")] public int MonitorNumaNode { get; set; } - [JsonProperty("MonitorPriority")] public int MonitorPriority { get; set; } + [JsonProperty("MonitorPriority")] public int MonitorPriority { get; set; } - [JsonProperty("Affinity")] public int Affinity { get; set; } + [JsonProperty("Affinity")] public int Affinity { get; set; } - [JsonProperty("NumaNode")] public int NumaNode { get; set; } + [JsonProperty("NumaNode")] public int NumaNode { get; set; } - [JsonProperty("Memory")] public long Memory { get; set; } + [JsonProperty("Memory")] public long Memory { get; set; } - [JsonProperty("MemoryMB")] public int MemoryMB { get; set; } + [JsonProperty("MemoryMB")] public int MemoryMb { get; set; } - [JsonProperty("MemoryString")] public string MemoryString { get; set; } + [JsonProperty("MemoryString")] public string MemoryString { get; set; } - [JsonProperty("DiskSpace")] public int DiskSpace { get; set; } + [JsonProperty("DiskSpace")] public int DiskSpace { get; set; } - [JsonProperty("DiskSpaceMB")] public int DiskSpaceMB { get; set; } + [JsonProperty("DiskSpaceMB")] public int DiskSpaceMb { get; set; } - [JsonProperty("DiskSpaceString")] public string DiskSpaceString { get; set; } + [JsonProperty("DiskSpaceString")] public string DiskSpaceString { get; set; } - [JsonProperty("DiskDrive")] public string DiskDrive { get; set; } + [JsonProperty("DiskDrive")] public string DiskDrive { get; set; } - [JsonProperty("CustomField1")] public string CustomField1 { get; set; } + [JsonProperty("CustomField1")] public string CustomField1 { get; set; } - [JsonProperty("CustomField2")] public string CustomField2 { get; set; } + [JsonProperty("CustomField2")] public string CustomField2 { get; set; } - [JsonProperty("CustomField3")] public string CustomField3 { get; set; } + [JsonProperty("CustomField3")] public string CustomField3 { get; set; } - [JsonProperty("CustomField4")] public string CustomField4 { get; set; } + [JsonProperty("CustomField4")] public string CustomField4 { get; set; } - [JsonProperty("CustomField5")] public string CustomField5 { get; set; } + [JsonProperty("CustomField5")] public string CustomField5 { get; set; } - [JsonProperty("CustomField6")] public string CustomField6 { get; set; } + [JsonProperty("CustomField6")] public string CustomField6 { get; set; } - [JsonProperty("CustomField7")] public string CustomField7 { get; set; } + [JsonProperty("CustomField7")] public string CustomField7 { get; set; } - [JsonProperty("CustomField8")] public string CustomField8 { get; set; } + [JsonProperty("CustomField8")] public string CustomField8 { get; set; } - [JsonProperty("CustomField9")] public string CustomField9 { get; set; } + [JsonProperty("CustomField9")] public string CustomField9 { get; set; } - [JsonProperty("CustomField10")] public string CustomField10 { get; set; } + [JsonProperty("CustomField10")] public string CustomField10 { get; set; } - [JsonProperty("CustomField11")] public string CustomField11 { get; set; } + [JsonProperty("CustomField11")] public string CustomField11 { get; set; } - [JsonProperty("CustomField12")] public string CustomField12 { get; set; } + [JsonProperty("CustomField12")] public string CustomField12 { get; set; } - [JsonProperty("CustomField13")] public string CustomField13 { get; set; } + [JsonProperty("CustomField13")] public string CustomField13 { get; set; } - [JsonProperty("CustomField14")] public string CustomField14 { get; set; } + [JsonProperty("CustomField14")] public string CustomField14 { get; set; } - [JsonProperty("CustomField15")] public string CustomField15 { get; set; } + [JsonProperty("CustomField15")] public string CustomField15 { get; set; } - [JsonProperty("BillingId")] public string BillingId { get; set; } + [JsonProperty("BillingId")] public string BillingId { get; set; } - [JsonProperty("BillingStatus")] public int BillingStatus { get; set; } + [JsonProperty("BillingStatus")] public int BillingStatus { get; set; } - [JsonProperty("PeakMemoryMB")] public double PeakMemoryMB { get; set; } + [JsonProperty("PeakMemoryMB")] public double PeakMemoryMb { get; set; } - [JsonProperty("PeakCPU")] public double PeakCPU { get; set; } + [JsonProperty("PeakCPU")] public double PeakCpu { get; set; } - [JsonProperty("DCSyncUrl")] public string DCSyncUrl { get; set; } + [JsonProperty("DCSyncUrl")] public string DcSyncUrl { get; set; } - [JsonProperty("DCDownloadServer")] public string DCDownloadServer { get; set; } + [JsonProperty("DCDownloadServer")] public string DcDownloadServer { get; set; } - [JsonProperty("DCDownloadUser")] public string DCDownloadUser { get; set; } + [JsonProperty("DCDownloadUser")] public string DcDownloadUser { get; set; } - [JsonProperty("DCDownloadPassword")] public string DCDownloadPassword { get; set; } + [JsonProperty("DCDownloadPassword")] public string DcDownloadPassword { get; set; } - public async Task Update(Action action) - { - var server = new Server(); - action(server); - var putJson = JsonConvert.SerializeObject(server, Constants.IgnoreDefaultValues); - var request = Controller.GenerateDefaultRequest(); - request.Resource += ServerId; - request.Method = Method.PUT; - request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); - return (await Controller.ExecuteBaseResponseRequest(request)).Success; - } + public async Task Update(Action action) + { + var server = new Server(); + action(server); + var putJson = JsonConvert.SerializeObject(server, Constants.IgnoreDefaultValues); + var request = TcaClient.ServersController.GenerateDefaultRequest(ServerId.ToString()); + request.Method = HttpMethod.Put; + request.Content = new StringContent(putJson, Encoding.UTF8, Constants.JsonContentType); + return (await TcaClient.ServersController.ExecuteBaseResponseRequest(request)).Success; + } - public Task Delete() - { - throw new NotImplementedException(); - } + public Task Delete() + { + throw new NotImplementedException(); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/FileManager/CompressModel.cs b/TCAdminApiSharp/Entities/Service/FileManager/CompressModel.cs new file mode 100644 index 0000000..40180f2 --- /dev/null +++ b/TCAdminApiSharp/Entities/Service/FileManager/CompressModel.cs @@ -0,0 +1,9 @@ +using Newtonsoft.Json; + +namespace TCAdminApiSharp.Entities.Service.FileManager; + +public class CompressModel +{ + [JsonProperty("Zip")] + public string Zip { get; set; } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/FileManager/DirectoryListing.cs b/TCAdminApiSharp/Entities/Service/FileManager/DirectoryListing.cs new file mode 100644 index 0000000..7fef326 --- /dev/null +++ b/TCAdminApiSharp/Entities/Service/FileManager/DirectoryListing.cs @@ -0,0 +1,47 @@ +using System; +using Newtonsoft.Json; + +namespace TCAdminApiSharp.Entities.Service.FileManager; + +public class DirectoryListing +{ + [JsonProperty("Name")] + public string Name { get; set; } + + [JsonProperty("Size")] + public long Size { get; set; } + + [JsonProperty("Path")] + public string Path { get; set; } + + [JsonProperty("Extension")] + public string Extension { get; set; } + + [JsonProperty("IsDirectory")] + public bool IsDirectory { get; set; } + + [JsonIgnore] public bool IsFile => !IsDirectory; + + [JsonProperty("HasDirectories")] + public bool HasDirectories { get; set; } + + [JsonProperty("Created")] + public DateTimeOffset Created { get; set; } + + [JsonProperty("CreatedUtc")] + public DateTimeOffset CreatedUtc { get; set; } + + [JsonProperty("Modified")] + public DateTimeOffset Modified { get; set; } + + [JsonProperty("ModifiedUtc")] + public DateTimeOffset ModifiedUtc { get; set; } + + [JsonIgnore] + public FileManagerService FileManagerService { get; internal set; } + + public System.Threading.Tasks.Task Rename(string newName) => FileManagerService.Rename(this.Path, newName); + public System.Threading.Tasks.Task Move(string target, bool overwrite = true) => FileManagerService.Move(new []{this.Path}, target, overwrite); + public System.Threading.Tasks.Task Copy(string target, bool overwrite = true) => FileManagerService.Copy(new []{this.Path}, target, overwrite); + public System.Threading.Tasks.Task Compress(string target) => FileManagerService.Compress(new []{this.Path}, target); +} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/FileManager/FileInfo.cs b/TCAdminApiSharp/Entities/Service/FileManager/FileInfo.cs new file mode 100644 index 0000000..fe3e7c0 --- /dev/null +++ b/TCAdminApiSharp/Entities/Service/FileManager/FileInfo.cs @@ -0,0 +1,61 @@ +using System; +using Newtonsoft.Json; + +namespace TCAdminApiSharp.Entities.Service.FileManager; + +public class FileInfo +{ + [JsonProperty("Attributes")] + public long Attributes { get; set; } + + [JsonProperty("CreationTime")] + public DateTimeOffset CreationTime { get; set; } + + [JsonProperty("CreationTimeUtc")] + public DateTimeOffset CreationTimeUtc { get; set; } + + [JsonProperty("Exists")] + public bool Exists { get; set; } + + [JsonProperty("Extension")] + public string Extension { get; set; } + + [JsonProperty("FullName")] + public string FullName { get; set; } + + [JsonProperty("LastAccessTime")] + public DateTimeOffset LastAccessTime { get; set; } + + [JsonProperty("LastAccessTimeUtc")] + public DateTimeOffset LastAccessTimeUtc { get; set; } + + [JsonProperty("LastWriteTime")] + public DateTimeOffset LastWriteTime { get; set; } + + [JsonProperty("LastWriteTimeUtc")] + public DateTimeOffset LastWriteTimeUtc { get; set; } + + [JsonProperty("Name")] + public string Name { get; set; } + + [JsonProperty("Directory")] + public string Directory { get; set; } + + [JsonProperty("IsReadOnly")] + public bool IsReadOnly { get; set; } + + [JsonProperty("Length")] + public long Length { get; set; } + + [JsonProperty("LinuxExecutable")] + public bool LinuxExecutable { get; set; } + + [JsonIgnore] + public FileManagerService FileManagerService { get; internal set; } + + public System.Threading.Tasks.Task Rename(string newName) => FileManagerService.Rename(this.FullName, newName); + public System.Threading.Tasks.Task Move(string target, bool overwrite = true) => FileManagerService.Move(new []{this.FullName}, target, overwrite); + public System.Threading.Tasks.Task Copy(string target, bool overwrite = true) => FileManagerService.Copy(new []{this.FullName}, target, overwrite); + public System.Threading.Tasks.Task Compress(string target) => FileManagerService.Compress(new []{this.FullName}, target); + public System.Threading.Tasks.Task Extract(string target) => FileManagerService.Extract(this.FullName, target); +} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/FileManager/FileManagerService.cs b/TCAdminApiSharp/Entities/Service/FileManager/FileManagerService.cs new file mode 100644 index 0000000..3542088 --- /dev/null +++ b/TCAdminApiSharp/Entities/Service/FileManager/FileManagerService.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using Microsoft.AspNetCore.WebUtilities; +using Newtonsoft.Json; +using TCAdminApiSharp.Entities.Generic; + +namespace TCAdminApiSharp.Entities.Service.FileManager; + +public class FileManagerService : ITCAdminClientCompatible +{ + public TcaClient TcaClient { get; set; } + private readonly Service _service; + private string FileManagerEndpoint => _service.ServiceId + "/FileManager"; + + public FileManagerService(TcaClient tcaClient, Service service) + { + _service = service; + TcaClient = tcaClient; + } + + public FileManagerService(Service service) : this(service.TcaClient, service) + { + } + + public async System.Threading.Tasks.Task GetDirectoryListing(string path = "/") + { + var realPath = path[(path.LastIndexOf("/", StringComparison.Ordinal) + 1)..]; + var parentPath = path[..(path.LastIndexOf("/", StringComparison.Ordinal) + 1)]; + var directoryListings = await GetDirectoryListings(parentPath); + var directoryListing = directoryListings.First(x => x.Path == realPath); + return directoryListing; + } + + public async System.Threading.Tasks.Task> GetDirectoryListings(string path = "/") + { + if (string.IsNullOrEmpty(path)) + { + path = "/"; + } + + path = path.Replace("\\", "/"); + + var endpoint = QueryHelpers.AddQueryString(FileManagerEndpoint, nameof(path), path); + var request = TcaClient.ServicesController.GenerateDefaultRequest(endpoint); + var executeBaseResponseRequest = await TcaClient.ServicesController.ExecuteBaseResponseRequest>(request); + foreach (var directoryListing in executeBaseResponseRequest.Result) + { + directoryListing.FileManagerService = this; + } + return executeBaseResponseRequest.Result; + } + + public async System.Threading.Tasks.Task GetFileInfo(string path) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + var endpoint = QueryHelpers.AddQueryString(FileManagerEndpoint, nameof(path), path); + var request = TcaClient.ServicesController.GenerateDefaultRequest(endpoint); + var executeBaseResponseRequest = await TcaClient.ServicesController.ExecuteBaseResponseRequest(request); + executeBaseResponseRequest.Result.FileManagerService = this; + return executeBaseResponseRequest.Result; + } + + public async System.Threading.Tasks.Task Rename(string path, string newName) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + if (newName == null) throw new ArgumentNullException(nameof(newName)); + var request = TcaClient.ServicesController.GenerateDefaultRequest(HttpMethod.Post, FileManagerEndpoint,nameof(Rename)); + request.Content = new FormUrlEncodedContent(new KeyValuePair[] + { + new(nameof(path), path), + new(nameof(newName), newName) + }); + var executeBaseResponseRequest = await TcaClient.ServicesController.ExecuteBaseResponseRequest(request); + return executeBaseResponseRequest.Success; + } + + public async System.Threading.Tasks.Task Move(string[] files, string target, bool overwrite = true) + { + if (files == null) throw new ArgumentNullException(nameof(files)); + if (target == null) throw new ArgumentNullException(nameof(target)); + var request = TcaClient.ServicesController.GenerateDefaultRequest(HttpMethod.Post, FileManagerEndpoint, nameof(Move)); + request.Content = new FormUrlEncodedContent(new KeyValuePair[] + { + new(nameof(files), JsonConvert.SerializeObject(files)), + new(nameof(target), target), + new(nameof(overwrite), overwrite.ToString()) + }); + var executeBaseResponseRequest = await TcaClient.ServicesController.ExecuteBaseResponseRequest(request); + return executeBaseResponseRequest.Success; + } + + public async System.Threading.Tasks.Task Copy(string[] files, string target, bool overwrite = true) + { + if (files == null) throw new ArgumentNullException(nameof(files)); + if (target == null) throw new ArgumentNullException(nameof(target)); + var request = TcaClient.ServicesController.GenerateDefaultRequest(HttpMethod.Post, FileManagerEndpoint, nameof(Copy)); + request.Content = new FormUrlEncodedContent(new KeyValuePair[] + { + new(nameof(files), JsonConvert.SerializeObject(files)), + new(nameof(target), target), + new(nameof(overwrite), overwrite.ToString()) + }); + var executeBaseResponseRequest = await TcaClient.ServicesController.ExecuteBaseResponseRequest(request); + return executeBaseResponseRequest.Success; + } + + public async System.Threading.Tasks.Task Compress(string[] files, string target) + { + if (files == null) throw new ArgumentNullException(nameof(files)); + if (target == null) throw new ArgumentNullException(nameof(target)); + var request = TcaClient.ServicesController.GenerateDefaultRequest(HttpMethod.Post, FileManagerEndpoint, nameof(Compress)); + request.Content = new FormUrlEncodedContent(new KeyValuePair[] + { + new(nameof(files), JsonConvert.SerializeObject(files)), + new(nameof(target), target), + }); + var executeBaseResponseRequest = await TcaClient.ServicesController.ExecuteBaseResponseRequest(request); + return executeBaseResponseRequest.Result; + } + + public async System.Threading.Tasks.Task Extract(string file, string extractPath) + { + if (file == null) throw new ArgumentNullException(nameof(file)); + if (extractPath == null) throw new ArgumentNullException(nameof(extractPath)); + var request = TcaClient.ServicesController.GenerateDefaultRequest(HttpMethod.Post, FileManagerEndpoint, nameof(Compress)); + request.Content = new FormUrlEncodedContent(new KeyValuePair[] + { + new(nameof(file), file), + new(nameof(extractPath), extractPath), + }); + var executeBaseResponseRequest = await TcaClient.ServicesController.ExecuteBaseResponseRequest(request); + return executeBaseResponseRequest.Success; + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index 8c030de..42092f4 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -1,321 +1,324 @@ using System; using System.Collections.Generic; +using System.Net.Http; +using System.Text; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; -using RestSharp; -using TCAdminApiSharp.Controllers; using TCAdminApiSharp.Entities.Billing; using TCAdminApiSharp.Entities.Generic; +using TCAdminApiSharp.Entities.Service.FileManager; using TCAdminApiSharp.Helpers; // ReSharper disable UnusedMember.Global -namespace TCAdminApiSharp.Entities.Service -{ - public class Service : ObjectBase, IObjectBaseCrud, IPowerable - { - [JsonIgnore] private static readonly ServicesController Controller = - TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); +namespace TCAdminApiSharp.Entities.Service; - [JsonProperty("EnableGameSwitching")] public bool EnableGameSwitching { get; set; } +public class Service : ObjectBase, IObjectBaseCrud, IPowerable +{ + [JsonProperty("EnableGameSwitching")] public bool EnableGameSwitching { get; set; } - [JsonProperty("DisableQueryMonitoring")] - public bool DisableQueryMonitoring { get; set; } + [JsonProperty("DisableQueryMonitoring")] + public bool DisableQueryMonitoring { get; set; } - [JsonProperty("DisableSlotMonitoring")] - public bool DisableSlotMonitoring { get; set; } + [JsonProperty("DisableSlotMonitoring")] + public bool DisableSlotMonitoring { get; set; } - [JsonProperty("DisablePrivateMonitoring")] - public bool DisablePrivateMonitoring { get; set; } + [JsonProperty("DisablePrivateMonitoring")] + public bool DisablePrivateMonitoring { get; set; } - [JsonProperty("DisableBrandedMonitoring")] - public bool DisableBrandedMonitoring { get; set; } + [JsonProperty("DisableBrandedMonitoring")] + public bool DisableBrandedMonitoring { get; set; } - [JsonProperty("GameSwitchingAllowedGames")] - public IList GameSwitchingAllowedGames { get; set; } + [JsonProperty("GameSwitchingAllowedGames")] + public IList GameSwitchingAllowedGames { get; set; } - [JsonProperty("FastDownloadUsage")] public int FastDownloadUsage { get; set; } + [JsonProperty("FastDownloadUsage")] public int FastDownloadUsage { get; set; } - [JsonProperty("FastDownloadFileCount")] - public int FastDownloadFileCount { get; set; } + [JsonProperty("FastDownloadFileCount")] + public int FastDownloadFileCount { get; set; } - [JsonProperty("ServiceId")] public int ServiceId { get; set; } + [JsonProperty("ServiceId")] public int ServiceId { get; set; } - [JsonProperty("MemoryLimitMB")] public int MemoryLimitMB { get; set; } + [JsonProperty("MemoryLimitMB")] public int MemoryLimitMB { get; set; } - [JsonProperty("CpuLimit")] public int CpuLimit { get; set; } + [JsonProperty("CpuLimit")] public int CpuLimit { get; set; } - [JsonProperty("ServerId")] public int ServerId { get; set; } + [JsonProperty("ServerId")] public int ServerId { get; set; } - [JsonProperty("BillingId")] public string BillingId { get; set; } + [JsonProperty("BillingId")] public string BillingId { get; set; } - [JsonProperty("BillingStatus")] public BillingStatus BillingStatus { get; set; } + [JsonProperty("BillingStatus")] public BillingStatus BillingStatus { get; set; } - [JsonProperty("GameId")] public int GameId { get; set; } + [JsonProperty("GameId")] public int GameId { get; set; } - [JsonProperty("UserPackageId")] public int UserPackageId { get; set; } + [JsonProperty("UserPackageId")] public int UserPackageId { get; set; } - [JsonProperty("UserId")] public int UserId { get; set; } + [JsonProperty("UserId")] public int UserId { get; set; } - [JsonProperty("Executable")] public string? Executable { get; set; } + [JsonProperty("Executable")] public string? Executable { get; set; } - [JsonProperty("UnparsedCommandLine")] public string UnparsedCommandLine { get; set; } + [JsonProperty("UnparsedCommandLine")] public string UnparsedCommandLine { get; set; } - [JsonProperty("WorkingDirectory")] public string WorkingDirectory { get; set; } + [JsonProperty("WorkingDirectory")] public string WorkingDirectory { get; set; } - [JsonProperty("RootDirectory")] public string RootDirectory { get; set; } + [JsonProperty("RootDirectory")] public string RootDirectory { get; set; } - [JsonProperty("Private")] public bool Private { get; set; } + [JsonProperty("Private")] public bool Private { get; set; } - [JsonProperty("Slots")] public int Slots { get; set; } + [JsonProperty("Slots")] public int Slots { get; set; } - [JsonProperty("CurrentOnline")] public bool CurrentOnline { get; set; } + [JsonProperty("CurrentOnline")] public bool CurrentOnline { get; set; } - [JsonProperty("CurrentPid")] public int CurrentPid { get; set; } + [JsonProperty("CurrentPid")] public int CurrentPid { get; set; } - [JsonProperty("CurrentPlayers")] public int CurrentPlayers { get; set; } + [JsonProperty("CurrentPlayers")] public int CurrentPlayers { get; set; } - [JsonProperty("CurrentMaxPlayers")] public int CurrentMaxPlayers { get; set; } + [JsonProperty("CurrentMaxPlayers")] public int CurrentMaxPlayers { get; set; } - [JsonProperty("CurrentCpu")] public double CurrentCpu { get; set; } + [JsonProperty("CurrentCpu")] public double CurrentCpu { get; set; } - [JsonProperty("CurrentMemory")] public double CurrentMemory { get; set; } + [JsonProperty("CurrentMemory")] public double CurrentMemory { get; set; } - [JsonProperty("CurrentMemoryLimit")] public double CurrentMemoryLimit { get; set; } + [JsonProperty("CurrentMemoryLimit")] public double CurrentMemoryLimit { get; set; } - [JsonProperty("CurrentMemoryPercent")] public double CurrentMemoryPercent { get; set; } + [JsonProperty("CurrentMemoryPercent")] public double CurrentMemoryPercent { get; set; } - [JsonProperty("CurrentBandwidth")] public double CurrentBandwidth { get; set; } + [JsonProperty("CurrentBandwidth")] public double CurrentBandwidth { get; set; } - [JsonProperty("CurrentMap")] public string CurrentMap { get; set; } + [JsonProperty("CurrentMap")] public string CurrentMap { get; set; } - [JsonProperty("CurrentGameType")] public string CurrentGameType { get; set; } + [JsonProperty("CurrentGameType")] public string CurrentGameType { get; set; } - [JsonProperty("CurrentName")] public string CurrentName { get; set; } + [JsonProperty("CurrentName")] public string CurrentName { get; set; } - [JsonProperty("ServiceStatus")] public ServiceStatus ServiceStatus { get; set; } + [JsonProperty("ServiceStatus")] public ServiceStatus ServiceStatus { get; set; } - [JsonProperty("StartTime")] public DateTime StartTime { get; set; } + [JsonProperty("StartTime")] public DateTime StartTime { get; set; } - [JsonProperty("JoinUrl")] public string JoinUrl { get; set; } + [JsonProperty("JoinUrl")] public string JoinUrl { get; set; } - [JsonProperty("Branded")] public bool Branded { get; set; } + [JsonProperty("Branded")] public bool Branded { get; set; } - [JsonProperty("ConnectionInfo")] public string ConnectionInfo { get; set; } + [JsonProperty("ConnectionInfo")] public string ConnectionInfo { get; set; } - [JsonProperty("QueryInfo")] public string QueryInfo { get; set; } + [JsonProperty("QueryInfo")] public string QueryInfo { get; set; } - [JsonProperty("RConInfo")] public string RConInfo { get; set; } + [JsonProperty("RConInfo")] public string RConInfo { get; set; } - [JsonProperty("FtpInfo")] public string FtpInfo { get; set; } + [JsonProperty("FtpInfo")] public string FtpInfo { get; set; } - [JsonProperty("IpAddress")] public string IpAddress { get; set; } + [JsonProperty("IpAddress")] public string IpAddress { get; set; } - [JsonProperty("IpHostname")] public string IpHostname { get; set; } + [JsonProperty("IpHostname")] public string IpHostname { get; set; } - [JsonProperty("PublicIpAddress")] public string PublicIpAddress { get; set; } + [JsonProperty("PublicIpAddress")] public string PublicIpAddress { get; set; } - [JsonProperty("GamePort")] public int GamePort { get; set; } + [JsonProperty("GamePort")] public int GamePort { get; set; } - [JsonProperty("QueryPort")] public int QueryPort { get; set; } + [JsonProperty("QueryPort")] public int QueryPort { get; set; } - [JsonProperty("RConPort")] public int RConPort { get; set; } + [JsonProperty("RConPort")] public int RConPort { get; set; } - [JsonProperty("CustomPort1")] public int CustomPort1 { get; set; } + [JsonProperty("CustomPort1")] public int CustomPort1 { get; set; } - [JsonProperty("CustomPort2")] public int CustomPort2 { get; set; } + [JsonProperty("CustomPort2")] public int CustomPort2 { get; set; } - [JsonProperty("CustomPort3")] public int CustomPort3 { get; set; } + [JsonProperty("CustomPort3")] public int CustomPort3 { get; set; } - [JsonProperty("CustomPort4")] public int CustomPort4 { get; set; } + [JsonProperty("CustomPort4")] public int CustomPort4 { get; set; } - [JsonProperty("CustomPort5")] public int CustomPort5 { get; set; } + [JsonProperty("CustomPort5")] public int CustomPort5 { get; set; } - [JsonProperty("CustomPort6")] public int CustomPort6 { get; set; } + [JsonProperty("CustomPort6")] public int CustomPort6 { get; set; } - [JsonProperty("CustomPort7")] public int CustomPort7 { get; set; } + [JsonProperty("CustomPort7")] public int CustomPort7 { get; set; } - [JsonProperty("CustomPort8")] public int CustomPort8 { get; set; } + [JsonProperty("CustomPort8")] public int CustomPort8 { get; set; } - [JsonProperty("CustomPort9")] public int CustomPort9 { get; set; } + [JsonProperty("CustomPort9")] public int CustomPort9 { get; set; } - [JsonProperty("CustomPort10")] public int CustomPort10 { get; set; } + [JsonProperty("CustomPort10")] public int CustomPort10 { get; set; } - [JsonProperty("CustomPort11")] public int CustomPort11 { get; set; } + [JsonProperty("CustomPort11")] public int CustomPort11 { get; set; } - [JsonProperty("CustomPort12")] public int CustomPort12 { get; set; } + [JsonProperty("CustomPort12")] public int CustomPort12 { get; set; } - [JsonProperty("CustomPort13")] public int CustomPort13 { get; set; } + [JsonProperty("CustomPort13")] public int CustomPort13 { get; set; } - [JsonProperty("CustomPort14")] public int CustomPort14 { get; set; } + [JsonProperty("CustomPort14")] public int CustomPort14 { get; set; } - [JsonProperty("CustomPort15")] public int CustomPort15 { get; set; } + [JsonProperty("CustomPort15")] public int CustomPort15 { get; set; } - [JsonProperty("CustomPort16")] public int CustomPort16 { get; set; } + [JsonProperty("CustomPort16")] public int CustomPort16 { get; set; } - [JsonProperty("CustomPort17")] public int CustomPort17 { get; set; } + [JsonProperty("CustomPort17")] public int CustomPort17 { get; set; } - [JsonProperty("CustomPort18")] public int CustomPort18 { get; set; } + [JsonProperty("CustomPort18")] public int CustomPort18 { get; set; } - [JsonProperty("CustomPort19")] public int CustomPort19 { get; set; } + [JsonProperty("CustomPort19")] public int CustomPort19 { get; set; } - [JsonProperty("CustomPort20")] public int CustomPort20 { get; set; } + [JsonProperty("CustomPort20")] public int CustomPort20 { get; set; } - [JsonProperty("CustomPort21")] public int CustomPort21 { get; set; } + [JsonProperty("CustomPort21")] public int CustomPort21 { get; set; } - [JsonProperty("CustomPort22")] public int CustomPort22 { get; set; } + [JsonProperty("CustomPort22")] public int CustomPort22 { get; set; } - [JsonProperty("CustomPort23")] public int CustomPort23 { get; set; } + [JsonProperty("CustomPort23")] public int CustomPort23 { get; set; } - [JsonProperty("CustomPort24")] public int CustomPort24 { get; set; } + [JsonProperty("CustomPort24")] public int CustomPort24 { get; set; } - [JsonProperty("CustomPort25")] public int CustomPort25 { get; set; } + [JsonProperty("CustomPort25")] public int CustomPort25 { get; set; } - [JsonProperty("CustomPort26")] public int CustomPort26 { get; set; } + [JsonProperty("CustomPort26")] public int CustomPort26 { get; set; } - [JsonProperty("CustomPort27")] public int CustomPort27 { get; set; } + [JsonProperty("CustomPort27")] public int CustomPort27 { get; set; } - [JsonProperty("CustomPort28")] public int CustomPort28 { get; set; } + [JsonProperty("CustomPort28")] public int CustomPort28 { get; set; } - [JsonProperty("CustomPort29")] public int CustomPort29 { get; set; } + [JsonProperty("CustomPort29")] public int CustomPort29 { get; set; } - [JsonProperty("CustomPort30")] public int CustomPort30 { get; set; } + [JsonProperty("CustomPort30")] public int CustomPort30 { get; set; } - [JsonProperty("CustomPort31")] public int CustomPort31 { get; set; } + [JsonProperty("CustomPort31")] public int CustomPort31 { get; set; } - [JsonProperty("CustomPort32")] public int CustomPort32 { get; set; } + [JsonProperty("CustomPort32")] public int CustomPort32 { get; set; } - [JsonProperty("CustomPort33")] public int CustomPort33 { get; set; } + [JsonProperty("CustomPort33")] public int CustomPort33 { get; set; } - [JsonProperty("CustomPort34")] public int CustomPort34 { get; set; } + [JsonProperty("CustomPort34")] public int CustomPort34 { get; set; } - [JsonProperty("CustomPort35")] public int CustomPort35 { get; set; } + [JsonProperty("CustomPort35")] public int CustomPort35 { get; set; } - [JsonProperty("CustomPort36")] public int CustomPort36 { get; set; } + [JsonProperty("CustomPort36")] public int CustomPort36 { get; set; } - [JsonProperty("CustomPort37")] public int CustomPort37 { get; set; } + [JsonProperty("CustomPort37")] public int CustomPort37 { get; set; } - [JsonProperty("CustomPort38")] public int CustomPort38 { get; set; } + [JsonProperty("CustomPort38")] public int CustomPort38 { get; set; } - [JsonProperty("CustomPort39")] public int CustomPort39 { get; set; } + [JsonProperty("CustomPort39")] public int CustomPort39 { get; set; } - [JsonProperty("CustomPort40")] public int CustomPort40 { get; set; } + [JsonProperty("CustomPort40")] public int CustomPort40 { get; set; } - [JsonProperty("CustomPort41")] public int CustomPort41 { get; set; } + [JsonProperty("CustomPort41")] public int CustomPort41 { get; set; } - [JsonProperty("CustomPort42")] public int CustomPort42 { get; set; } + [JsonProperty("CustomPort42")] public int CustomPort42 { get; set; } - [JsonProperty("CustomPort43")] public int CustomPort43 { get; set; } + [JsonProperty("CustomPort43")] public int CustomPort43 { get; set; } - [JsonProperty("CustomPort44")] public int CustomPort44 { get; set; } + [JsonProperty("CustomPort44")] public int CustomPort44 { get; set; } - [JsonProperty("CustomPort45")] public int CustomPort45 { get; set; } + [JsonProperty("CustomPort45")] public int CustomPort45 { get; set; } - [JsonProperty("CustomPort46")] public int CustomPort46 { get; set; } + [JsonProperty("CustomPort46")] public int CustomPort46 { get; set; } - [JsonProperty("CustomPort47")] public int CustomPort47 { get; set; } + [JsonProperty("CustomPort47")] public int CustomPort47 { get; set; } - [JsonProperty("CustomPort48")] public int CustomPort48 { get; set; } + [JsonProperty("CustomPort48")] public int CustomPort48 { get; set; } - [JsonProperty("CustomPort49")] public int CustomPort49 { get; set; } + [JsonProperty("CustomPort49")] public int CustomPort49 { get; set; } - [JsonProperty("CustomPort50")] public int CustomPort50 { get; set; } + [JsonProperty("CustomPort50")] public int CustomPort50 { get; set; } - [JsonProperty("Startup")] public ServiceStartup Startup { get; set; } + [JsonProperty("Startup")] public ServiceStartup Startup { get; set; } - [JsonProperty("Priority")] public int Priority { get; set; } + [JsonProperty("Priority")] public int Priority { get; set; } - [JsonProperty("Affinity")] public int Affinity { get; set; } + [JsonProperty("Affinity")] public int Affinity { get; set; } - [JsonProperty("NumaNode")] public int NumaNode { get; set; } + [JsonProperty("NumaNode")] public int NumaNode { get; set; } - [JsonProperty("GameKey")] public string GameKey { get; set; } + [JsonProperty("GameKey")] public string GameKey { get; set; } - [JsonProperty("Variables")] public TcaXmlField Variables { get; set; } + [JsonProperty("Variables")] public TcaXmlField Variables { get; set; } - [JsonProperty("InstalledMods")] public IList InstalledMods { get; set; } + [JsonProperty("InstalledMods")] public IList InstalledMods { get; set; } - [JsonProperty("InstalledUpdate")] public string InstalledUpdate { get; set; } + [JsonProperty("InstalledUpdate")] public string InstalledUpdate { get; set; } - [JsonProperty("OverrideCommandLine")] public bool OverrideCommandLine { get; set; } + [JsonProperty("OverrideCommandLine")] public bool OverrideCommandLine { get; set; } - [JsonProperty("Notes")] public string Notes { get; set; } + [JsonProperty("Notes")] public string Notes { get; set; } - [JsonIgnore] - public User.User User => Controller.TcaClient.UsersController.GetUser(UserId).ConfigureAwait(false).GetAwaiter() - .GetResult(); + [JsonIgnore] public FileManagerService FileManagerService => new(this); - [JsonIgnore] - public Server.Server Server => - Controller.TcaClient.ServersController.GetServer(ServerId).ConfigureAwait(false).GetAwaiter().GetResult(); + // [JsonIgnore] + // public User.User User => Controller.TcaClient.UsersController.GetUser(UserId).ConfigureAwait(false).GetAwaiter() + // .GetResult(); + // + // [JsonIgnore] + // public Server.Server Server => + // Controller.TcaClient.ServersController.GetServer(ServerId).ConfigureAwait(false).GetAwaiter().GetResult(); - public async Task Update(Action action) - { - var service = new Service(); - action(service); - var putJson = JsonConvert.SerializeObject(service, Constants.IgnoreDefaultValues); - var request = Controller.GenerateDefaultRequest(); - request.Resource += ServiceId; - request.Method = Method.PUT; - request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); - return (await Controller.ExecuteBaseResponseRequest(request)).Success; - } + public async Task Update(Action action) + { + var service = new Service(); + action(service); + var putJson = JsonConvert.SerializeObject(service, Constants.IgnoreDefaultValues); + var request = TcaClient.ServicesController.GenerateDefaultRequest(ServiceId.ToString()); + request.Method = HttpMethod.Put; + request.Content = new StringContent(putJson, Encoding.UTF8, Constants.JsonContentType); + return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Success; + } - public Task Delete() - { - // todo: Luis hurry up implement pls - throw new NotImplementedException(); - } + public Task Delete() + { + // todo: Luis hurry up implement pls + throw new NotImplementedException(); + } - public async Task Start(string reason = "") + public async Task Start(string reason = "") + { + var request = TcaClient.ServicesController.GenerateDefaultRequest( ServiceId.ToString(), nameof(Start)); + request.Method = HttpMethod.Post; + if (!string.IsNullOrEmpty(reason)) { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"start/{ServiceId}"; - request.Method = Method.POST; - if (!string.IsNullOrEmpty(reason)) request.AddParameter("reason", reason); - return (await Controller.ExecuteBaseResponseRequest(request)).Success; + request.Content = new FormUrlEncodedContent(new[] + { new KeyValuePair(nameof(reason), reason) }); } + return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Success; + } - public async Task Restart(string reason = "") + public async Task Restart(string reason = "") + { + var request = TcaClient.ServicesController.GenerateDefaultRequest( ServiceId.ToString(), nameof(Restart)); + request.Method = HttpMethod.Post; + if (!string.IsNullOrEmpty(reason)) { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"restart/{ServiceId}"; - request.Method = Method.POST; - if (!string.IsNullOrEmpty(reason)) request.AddParameter("reason", reason); - return (await Controller.ExecuteBaseResponseRequest(request)).Success; + request.Content = new FormUrlEncodedContent(new[] + { new KeyValuePair(nameof(reason), reason) }); } + return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Success; + } - public async Task Stop(string reason = "") + public async Task Stop(string reason = "") + { + var request = TcaClient.ServicesController.GenerateDefaultRequest( ServiceId.ToString(), nameof(Stop)); + request.Method = HttpMethod.Post; + if (!string.IsNullOrEmpty(reason)) { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"stop/{ServiceId}"; - request.Method = Method.POST; - if (!string.IsNullOrEmpty(reason)) request.AddParameter("reason", reason); - return (await Controller.ExecuteBaseResponseRequest(request)).Success; + request.Content = new FormUrlEncodedContent(new[] + { new KeyValuePair(nameof(reason), reason) }); } + return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Success; + } - public async Task Configure() - { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"configure/{ServiceId}"; - request.Method = Method.POST; - return (await Controller.ExecuteBaseResponseRequest(request)).Success; - } + public async Task Configure() + { + var request = TcaClient.ServicesController.GenerateDefaultRequest( ServiceId.ToString(), nameof(Configure)); + request.Method = HttpMethod.Post; + return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Success; + } - public async Task Suspend() - { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"suspend/{ServiceId}"; - request.Method = Method.POST; - return (await Controller.ExecuteBaseResponseRequest(request)).Success; - } + public async Task Suspend() + { + var request = TcaClient.ServicesController.GenerateDefaultRequest( ServiceId.ToString(), nameof(Suspend)); + request.Method = HttpMethod.Post; + return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Success; + } - public async Task Unsuspend() - { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"unsuspend/{ServiceId}"; - request.Method = Method.POST; - return (await Controller.ExecuteBaseResponseRequest(request)).Success; - } + public async Task Unsuspend() + { + var request = TcaClient.ServicesController.GenerateDefaultRequest( ServiceId.ToString(), nameof(Unsuspend)); + request.Method = HttpMethod.Post; + return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Success; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/ServiceBuilder.cs b/TCAdminApiSharp/Entities/Service/ServiceBuilder.cs index 7fcee89..35c757d 100644 --- a/TCAdminApiSharp/Entities/Service/ServiceBuilder.cs +++ b/TCAdminApiSharp/Entities/Service/ServiceBuilder.cs @@ -10,178 +10,177 @@ // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMethodReturnValue.Global -namespace TCAdminApiSharp.Entities.Service +namespace TCAdminApiSharp.Entities.Service; + +public class ServiceBuilder { - public class ServiceBuilder - { - private readonly ILogger _logger = Log.ForContext(); - private readonly Service _service; - private readonly Dictionary _extraData = new(); - - public ServiceBuilder() - { - _service = new Service(); - WithStartup(ServiceStartup.Automatic); - WithPriority(ProcessPriorityClass.Normal); - } - - public ServiceBuilder WithServerId(int id) - { - _service.ServerId = id; - return this; - } - - public ServiceBuilder WithDatacenterId(int id) - { - _extraData["DatacenterId"] = id; - return this; - } - - public ServiceBuilder WithUserId(int id) - { - _service.UserId = id; - return this; - } - - public ServiceBuilder WithUser(User.User user) - { - _service.UserId = user.UserId; - return this; - } - - public ServiceBuilder WithGameId(int id) - { - _service.GameId = id; - return this; - } - - public ServiceBuilder WithAutomaticPort(bool auto) - { - _extraData["AutomaticPort"] = auto; - return this; - } - - public ServiceBuilder WithPort(int port) - { - _service.GamePort = port; - return this; - } - - public ServiceBuilder WithSlots(int slots) - { - _service.Slots = slots; - return this; - } - - public ServiceBuilder WithPrivate(bool priv) - { - _service.Private = priv; - return this; - } - - public ServiceBuilder WithVariables(Dictionary variables) - { - _service.Variables = new TcaXmlField(variables); - return this; - } - - public ServiceBuilder WithStartup(ServiceStartup startup) - { - _service.Startup = startup; - return this; - } - - public ServiceBuilder WithPriority(ProcessPriorityClass priority) - { - _service.Priority = (int) priority; - return this; - } - - public ServiceBuilder WithAffinity(int affinity) - { - _service.Affinity = affinity; - return this; - } - - public ServiceBuilder WithNumaNode(int numaNode) - { - _service.NumaNode = numaNode; - return this; - } - - public ServiceBuilder WithBranded(bool branded) - { - _service.Branded = branded; - return this; - } - - public ServiceBuilder WithStartAfterCreated(bool startAfterCreation) - { - _extraData["StartAfterCreated"] = startAfterCreation; - return this; - } - - public ServiceBuilder WithScheduleDelete(bool scheduleDelete) - { - _extraData["ScheduleDelete"] = scheduleDelete; - return this; - } - - public ServiceBuilder WithDeleteTimeUtc(DateTime deletionTime) - { - _extraData["DeleteTimeUtc"] = deletionTime; - return this; - } - - public ServiceBuilder WithDeleteOwner(bool deleteOwner) - { - _extraData["DeleteOwner"] = deleteOwner; - return this; - } - - public ServiceBuilder WithUserPackageId(int userPackageId) - { - _service.UserPackageId = userPackageId; - return this; - } - - public ServiceBuilder WithGameSwitchingAllowedGames(string[] gameIds) - { - _service.GameSwitchingAllowedGames = gameIds; - return this; - } - - public ServiceBuilder WithBillingId(string billingId) - { - _service.BillingId = billingId; - return this; - } - - public ServiceBuilder WithCpuLimit(int cpuLimit) - { - _service.CpuLimit = cpuLimit; - return this; - } - - public ServiceBuilder WithVirtualMemoryLimitMb(int mb) - { - _extraData["VirtualMemoryLimitMB"] = mb; - return this; - } - - public ServiceBuilder WithMemoryLimitMb(int mb) - { - _service.MemoryLimitMB = mb; - return this; - } - - internal string GenerateRequestBody() - { - var jo = JObject.FromObject(_service, JsonSerializer.Create(Constants.IgnoreDefaultValues)); - foreach (var keyValuePair in _extraData) jo.Add(keyValuePair.Key, new JValue(keyValuePair.Value)); - _logger.Debug(jo.ToString()); - - return jo.ToString(); - } + private readonly ILogger _logger = Log.ForContext(); + private readonly Service _service; + private readonly Dictionary _extraData = new(); + + public ServiceBuilder() + { + _service = new Service(); + WithStartup(ServiceStartup.Automatic); + WithPriority(ProcessPriorityClass.Normal); + } + + public ServiceBuilder WithServerId(int id) + { + _service.ServerId = id; + return this; + } + + public ServiceBuilder WithDatacenterId(int id) + { + _extraData["DatacenterId"] = id; + return this; + } + + public ServiceBuilder WithUserId(int id) + { + _service.UserId = id; + return this; + } + + public ServiceBuilder WithUser(User.User user) + { + _service.UserId = user.UserId; + return this; + } + + public ServiceBuilder WithGameId(int id) + { + _service.GameId = id; + return this; + } + + public ServiceBuilder WithAutomaticPort(bool auto) + { + _extraData["AutomaticPort"] = auto; + return this; + } + + public ServiceBuilder WithPort(int port) + { + _service.GamePort = port; + return this; + } + + public ServiceBuilder WithSlots(int slots) + { + _service.Slots = slots; + return this; + } + + public ServiceBuilder WithPrivate(bool priv) + { + _service.Private = priv; + return this; + } + + public ServiceBuilder WithVariables(TcaXmlField variables) + { + _service.Variables = variables; + return this; + } + + public ServiceBuilder WithStartup(ServiceStartup startup) + { + _service.Startup = startup; + return this; + } + + public ServiceBuilder WithPriority(ProcessPriorityClass priority) + { + _service.Priority = (int) priority; + return this; + } + + public ServiceBuilder WithAffinity(int affinity) + { + _service.Affinity = affinity; + return this; + } + + public ServiceBuilder WithNumaNode(int numaNode) + { + _service.NumaNode = numaNode; + return this; + } + + public ServiceBuilder WithBranded(bool branded) + { + _service.Branded = branded; + return this; + } + + public ServiceBuilder WithStartAfterCreated(bool startAfterCreation) + { + _extraData["StartAfterCreated"] = startAfterCreation; + return this; + } + + public ServiceBuilder WithScheduleDelete(bool scheduleDelete) + { + _extraData["ScheduleDelete"] = scheduleDelete; + return this; + } + + public ServiceBuilder WithDeleteTimeUtc(DateTime deletionTime) + { + _extraData["DeleteTimeUtc"] = deletionTime; + return this; + } + + public ServiceBuilder WithDeleteOwner(bool deleteOwner) + { + _extraData["DeleteOwner"] = deleteOwner; + return this; + } + + public ServiceBuilder WithUserPackageId(int userPackageId) + { + _service.UserPackageId = userPackageId; + return this; + } + + public ServiceBuilder WithGameSwitchingAllowedGames(string[] gameIds) + { + _service.GameSwitchingAllowedGames = gameIds; + return this; + } + + public ServiceBuilder WithBillingId(string billingId) + { + _service.BillingId = billingId; + return this; + } + + public ServiceBuilder WithCpuLimit(int cpuLimit) + { + _service.CpuLimit = cpuLimit; + return this; + } + + public ServiceBuilder WithVirtualMemoryLimitMb(int mb) + { + _extraData["VirtualMemoryLimitMB"] = mb; + return this; + } + + public ServiceBuilder WithMemoryLimitMb(int mb) + { + _service.MemoryLimitMB = mb; + return this; + } + + internal string GenerateRequestBody() + { + var jo = JObject.FromObject(_service, JsonSerializer.Create(Constants.IgnoreDefaultValues)); + foreach (var keyValuePair in _extraData) jo.Add(keyValuePair.Key, new JValue(keyValuePair.Value)); + _logger.Debug(jo.ToString()); + + return jo.ToString(); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/ServiceStartup.cs b/TCAdminApiSharp/Entities/Service/ServiceStartup.cs index 16ec273..36f58e2 100644 --- a/TCAdminApiSharp/Entities/Service/ServiceStartup.cs +++ b/TCAdminApiSharp/Entities/Service/ServiceStartup.cs @@ -1,9 +1,8 @@ -namespace TCAdminApiSharp.Entities.Service +namespace TCAdminApiSharp.Entities.Service; + +public enum ServiceStartup { - public enum ServiceStartup - { - Automatic = 2, - Manual = 3, - Disabled = 4 - } + Automatic = 2, + Manual = 3, + Disabled = 4 } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/ServiceStatus.cs b/TCAdminApiSharp/Entities/Service/ServiceStatus.cs index a11306a..69030ff 100644 --- a/TCAdminApiSharp/Entities/Service/ServiceStatus.cs +++ b/TCAdminApiSharp/Entities/Service/ServiceStatus.cs @@ -1,17 +1,16 @@ -namespace TCAdminApiSharp.Entities.Service +namespace TCAdminApiSharp.Entities.Service; + +public enum ServiceStatus { - public enum ServiceStatus - { - Processing = -3, // 0xFFFFFFFD - StartError = -2, // 0xFFFFFFFE - Unknown = -1, // 0xFFFFFFFF - Disabled = 0, - Stopped = 1, - Starting = 2, - Stopping = 3, - Running = 4, - Resuming = 5, - Pausing = 6, - Paused = 7 - } + Processing = -3, // 0xFFFFFFFD + StartError = -2, // 0xFFFFFFFE + Unknown = -1, // 0xFFFFFFFF + Disabled = 0, + Stopped = 1, + Starting = 2, + Stopping = 3, + Running = 4, + Resuming = 5, + Pausing = 6, + Paused = 7 } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Task/Task.cs b/TCAdminApiSharp/Entities/Task/Task.cs index cfe80e9..4814be1 100644 --- a/TCAdminApiSharp/Entities/Task/Task.cs +++ b/TCAdminApiSharp/Entities/Task/Task.cs @@ -1,86 +1,76 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; using Newtonsoft.Json; -using TCAdminApiSharp.Controllers; using TCAdminApiSharp.Entities.Generic; -using Microsoft.Extensions.DependencyInjection; -using RestSharp; -namespace TCAdminApiSharp.Entities.Task -{ - public class Task : ObjectBase - { - [JsonIgnore] private static readonly TasksController Controller = - TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); - - [JsonProperty("TaskId")] public int TaskId { get; set; } +namespace TCAdminApiSharp.Entities.Task; - [JsonProperty("UserId")] public int UserId { get; set; } - - [JsonProperty("UserName")] public string UserName { get; set; } +public class Task : ObjectBase +{ + [JsonProperty("TaskId")] public int TaskId { get; set; } - [JsonProperty("ServerId")] public int ServerId { get; set; } + [JsonProperty("UserId")] public int UserId { get; set; } - [JsonProperty("Name")] public string Name { get; set; } + [JsonProperty("UserName")] public string UserName { get; set; } - [JsonProperty("Status")] public TaskStatus Status { get; set; } + [JsonProperty("ServerId")] public int ServerId { get; set; } - [JsonProperty("CurrentStepId")] public int CurrentStepId { get; set; } + [JsonProperty("Name")] public string Name { get; set; } - [JsonProperty("LastRunTime")] public DateTime LastRunTime { get; set; } + [JsonProperty("Status")] public TaskStatus Status { get; set; } - [JsonProperty("LastRunTimeUtc")] public DateTime LastRunTimeUtc { get; set; } + [JsonProperty("CurrentStepId")] public int CurrentStepId { get; set; } - [JsonProperty("ScheduledTime")] public DateTime ScheduledTime { get; set; } + [JsonProperty("LastRunTime")] public DateTime LastRunTime { get; set; } - [JsonProperty("ScheduledTimeUtc")] public DateTime ScheduledTimeUtc { get; set; } + [JsonProperty("LastRunTimeUtc")] public DateTime LastRunTimeUtc { get; set; } - [JsonProperty("FilterTime")] public DateTime FilterTime { get; set; } + [JsonProperty("ScheduledTime")] public DateTime ScheduledTime { get; set; } - [JsonProperty("FilterTimeUtc")] public DateTime FilterTimeUtc { get; set; } + [JsonProperty("ScheduledTimeUtc")] public DateTime ScheduledTimeUtc { get; set; } - [JsonProperty("Enabled")] public bool Enabled { get; set; } + [JsonProperty("FilterTime")] public DateTime FilterTime { get; set; } - [JsonProperty("Source")] public string Source { get; set; } + [JsonProperty("FilterTimeUtc")] public DateTime FilterTimeUtc { get; set; } - [JsonProperty("SourceId")] public string SourceId { get; set; } + [JsonProperty("Enabled")] public bool Enabled { get; set; } - [JsonProperty("RecurringTaskGuid")] public object RecurringTaskGuid { get; set; } + [JsonProperty("Source")] public string Source { get; set; } - [JsonProperty("RecurringTaskId")] public int RecurringTaskId { get; set; } + [JsonProperty("SourceId")] public string SourceId { get; set; } - [JsonProperty("TotalSteps")] public int TotalSteps { get; set; } + [JsonProperty("RecurringTaskGuid")] public object RecurringTaskGuid { get; set; } - [JsonProperty("RedirectUrl")] public string RedirectUrl { get; set; } + [JsonProperty("RecurringTaskId")] public int RecurringTaskId { get; set; } - [JsonIgnore] - public IEnumerable Steps => - (List) Controller.GetTaskSteps(TaskId).GetAwaiter().GetResult().Result; + [JsonProperty("TotalSteps")] public int TotalSteps { get; set; } - [JsonIgnore] - public TaskStep CurrentStep - { - get - { - return Steps.FirstOrDefault(x => x.StepId == CurrentStepId) ?? throw new InvalidOperationException(); - } - } + [JsonProperty("RedirectUrl")] public string RedirectUrl { get; set; } - public async System.Threading.Tasks.Task Start() - { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"start/{TaskId}"; - request.Method = Method.POST; - await Controller.ExecuteBaseResponseRequest(request); - } + public async System.Threading.Tasks.Task Start() + { + var request = TcaClient.TasksController.GenerateDefaultRequest( TaskId.ToString(), nameof(Start)); + request.Method = HttpMethod.Post; + await TcaClient.TasksController.ExecuteBaseResponseRequest(request); + } - public async System.Threading.Tasks.Task Cancel() - { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"cancel/{TaskId}"; - request.Method = Method.POST; - await Controller.ExecuteBaseResponseRequest(request); - } + public async System.Threading.Tasks.Task Cancel() + { + var request = TcaClient.TasksController.GenerateDefaultRequest(TaskId.ToString(), nameof(Cancel)); + request.Method = HttpMethod.Post; + await TcaClient.TasksController.ExecuteBaseResponseRequest(request); + } + + public async Task> GetSteps() + { + return (await TcaClient.TasksController.GetTaskSteps(TaskId)).Result; + } + + public async Task GetCurrentStep() + { + return (await GetSteps()).First(x => x.StepId == CurrentStepId); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Task/TaskStatus.cs b/TCAdminApiSharp/Entities/Task/TaskStatus.cs index 3af5edf..aa644f4 100644 --- a/TCAdminApiSharp/Entities/Task/TaskStatus.cs +++ b/TCAdminApiSharp/Entities/Task/TaskStatus.cs @@ -1,12 +1,11 @@ -namespace TCAdminApiSharp.Entities.Task +namespace TCAdminApiSharp.Entities.Task; + +public enum TaskStatus { - public enum TaskStatus - { - NotExecuted, - Executing, - Scheduled, - Completed, - Canceled, - TaskError - } + NotExecuted, + Executing, + Scheduled, + Completed, + Canceled, + TaskError } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Task/TaskStep.cs b/TCAdminApiSharp/Entities/Task/TaskStep.cs index eb9a1c9..78765b8 100644 --- a/TCAdminApiSharp/Entities/Task/TaskStep.cs +++ b/TCAdminApiSharp/Entities/Task/TaskStep.cs @@ -1,43 +1,37 @@ using System; using System.Collections.Generic; using Newtonsoft.Json; -using TCAdminApiSharp.Controllers; using TCAdminApiSharp.Entities.Generic; -using Microsoft.Extensions.DependencyInjection; -namespace TCAdminApiSharp.Entities.Task -{ - public class TaskStep : ObjectBase - { - [JsonIgnore] private static readonly TasksController Controller = - TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); +namespace TCAdminApiSharp.Entities.Task; - [JsonProperty("ModuleId")] public string ModuleId { get; set; } +public class TaskStep : ObjectBase +{ + [JsonProperty("ModuleId")] public string ModuleId { get; set; } - [JsonProperty("ProcessId")] public int ProcessId { get; set; } + [JsonProperty("ProcessId")] public int ProcessId { get; set; } - [JsonProperty("TaskId")] public int TaskId { get; set; } + [JsonProperty("TaskId")] public int TaskId { get; set; } - [JsonProperty("StepId")] public int StepId { get; set; } + [JsonProperty("StepId")] public int StepId { get; set; } - [JsonProperty("ServerId")] public int ServerId { get; set; } + [JsonProperty("ServerId")] public int ServerId { get; set; } - [JsonProperty("Log")] public Dictionary Log { get; set; } + [JsonProperty("Log")] public Dictionary Log { get; set; } - [JsonProperty("DebugLog")] public Dictionary DebugLog { get; set; } + [JsonProperty("DebugLog")] public Dictionary DebugLog { get; set; } - [JsonProperty("LastDebugLogKey")] public DateTime LastDebugLogKey { get; set; } + [JsonProperty("LastDebugLogKey")] public DateTime LastDebugLogKey { get; set; } - [JsonProperty("LastLogKey")] public DateTime LastLogKey { get; set; } + [JsonProperty("LastLogKey")] public DateTime LastLogKey { get; set; } - [JsonProperty("Name")] public string Name { get; set; } + [JsonProperty("Name")] public string Name { get; set; } - [JsonProperty("LastLogItem")] public string LastLogItem { get; set; } + [JsonProperty("LastLogItem")] public string LastLogItem { get; set; } - [JsonProperty("Arguments")] public string Arguments { get; set; } + [JsonProperty("Arguments")] public string Arguments { get; set; } - [JsonProperty("ReturnValue")] public string ReturnValue { get; set; } + [JsonProperty("ReturnValue")] public string ReturnValue { get; set; } - [JsonProperty("Progress")] public int Progress { get; set; } - } + [JsonProperty("Progress")] public int Progress { get; set; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/User/User.cs b/TCAdminApiSharp/Entities/User/User.cs index b1d1ca4..a232753 100644 --- a/TCAdminApiSharp/Entities/User/User.cs +++ b/TCAdminApiSharp/Entities/User/User.cs @@ -1,142 +1,142 @@ using System; using System.Collections.Generic; +using System.Net.Http; +using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; -using TCAdminApiSharp.Controllers; +using TCAdminApiSharp.Entities.API; using TCAdminApiSharp.Entities.Generic; -using Microsoft.Extensions.DependencyInjection; -using RestSharp; using TCAdminApiSharp.Helpers; -namespace TCAdminApiSharp.Entities.User +namespace TCAdminApiSharp.Entities.User; + +public class User : ObjectBase, IObjectBaseCrud { - public class User : ObjectBase, IObjectBaseCrud - { - [JsonIgnore] private static readonly UsersController Controller = - TcaClient.ServiceProvider.GetService() ?? throw new InvalidOperationException(); + [JsonProperty("UserId")] public int UserId { get; set; } - [JsonProperty("UserId")] public int UserId { get; set; } + [JsonProperty("UserName")] public string UserName { get; set; } - [JsonProperty("UserName")] public string UserName { get; set; } + [JsonProperty("RoleId")] public int RoleId { get; set; } - [JsonProperty("RoleId")] public int RoleId { get; set; } + [JsonProperty("OwnerId")] public int OwnerId { get; set; } - [JsonProperty("OwnerId")] public int OwnerId { get; set; } + [JsonProperty("RequiresTwoStepVerification")] + public bool RequiresTwoStepVerification { get; set; } - [JsonProperty("RequiresTwoStepVerification")] - public bool RequiresTwoStepVerification { get; set; } + [JsonProperty("FtpRequiresTwoStepVerification")] + public bool FtpRequiresTwoStepVerification { get; set; } - [JsonProperty("FtpRequiresTwoStepVerification")] - public bool FtpRequiresTwoStepVerification { get; set; } + [JsonProperty("FtpSkipTwoStepVerificationIfKnownIp")] + public bool FtpSkipTwoStepVerificationIfKnownIp { get; set; } - [JsonProperty("FtpSkipTwoStepVerificationIfKnownIp")] - public bool FtpSkipTwoStepVerificationIfKnownIp { get; set; } + [JsonProperty("TwoStepVerificationSecret")] + public object TwoStepVerificationSecret { get; set; } - [JsonProperty("TwoStepVerificationSecret")] - public object TwoStepVerificationSecret { get; set; } + [JsonProperty("Status")] public int Status { get; set; } - [JsonProperty("Status")] public int Status { get; set; } + [JsonProperty("LastLogin")] public DateTime LastLogin { get; set; } - [JsonProperty("LastLogin")] public DateTime LastLogin { get; set; } + [JsonProperty("LastLoginUtc")] public DateTime LastLoginUtc { get; set; } - [JsonProperty("LastLoginUtc")] public DateTime LastLoginUtc { get; set; } + [JsonProperty("LastLoginIp")] public string LastLoginIp { get; set; } - [JsonProperty("LastLoginIp")] public string LastLoginIp { get; set; } + [JsonProperty("BillingId")] public string BillingId { get; set; } - [JsonProperty("BillingId")] public string BillingId { get; set; } + [JsonProperty("BillingStatus")] public int BillingStatus { get; set; } - [JsonProperty("BillingStatus")] public int BillingStatus { get; set; } + [JsonProperty("DemoMode")] public bool DemoMode { get; set; } - [JsonProperty("DemoMode")] public bool DemoMode { get; set; } + [JsonProperty("IsSubUser")] public bool IsSubUser { get; set; } - [JsonProperty("IsSubUser")] public bool IsSubUser { get; set; } + [JsonProperty("SubUserOwnerId")] public int SubUserOwnerId { get; set; } - [JsonProperty("SubUserOwnerId")] public int SubUserOwnerId { get; set; } + [JsonProperty("ExternalId")] public string ExternalId { get; set; } - [JsonProperty("ExternalId")] public string ExternalId { get; set; } + [JsonProperty("FirstName")] public string FirstName { get; set; } - [JsonProperty("FirstName")] public string FirstName { get; set; } + [JsonProperty("LastName")] public string LastName { get; set; } - [JsonProperty("LastName")] public string LastName { get; set; } + [JsonProperty("FullName")] public string FullName { get; set; } - [JsonProperty("FullName")] public string FullName { get; set; } + [JsonProperty("AllAddress")] public string AllAddress { get; set; } - [JsonProperty("AllAddress")] public string AllAddress { get; set; } + [JsonProperty("Address1")] public string Address1 { get; set; } - [JsonProperty("Address1")] public string Address1 { get; set; } + [JsonProperty("Address2")] public string Address2 { get; set; } - [JsonProperty("Address2")] public string Address2 { get; set; } + [JsonProperty("Address3")] public string Address3 { get; set; } - [JsonProperty("Address3")] public string Address3 { get; set; } + [JsonProperty("City")] public string City { get; set; } - [JsonProperty("City")] public string City { get; set; } + [JsonProperty("State")] public string State { get; set; } - [JsonProperty("State")] public string State { get; set; } + [JsonProperty("Country")] public string Country { get; set; } - [JsonProperty("Country")] public string Country { get; set; } + [JsonProperty("Zip")] public string Zip { get; set; } - [JsonProperty("Zip")] public string Zip { get; set; } + [JsonProperty("HomePhone")] public string HomePhone { get; set; } - [JsonProperty("HomePhone")] public string HomePhone { get; set; } + [JsonProperty("MobilePhone")] public string MobilePhone { get; set; } - [JsonProperty("MobilePhone")] public string MobilePhone { get; set; } + [JsonProperty("Email1")] public string Email1 { get; set; } - [JsonProperty("Email1")] public string Email1 { get; set; } + [JsonProperty("Email2")] public string Email2 { get; set; } - [JsonProperty("Email2")] public string Email2 { get; set; } + [JsonProperty("TimeZoneId")] public string TimeZoneId { get; set; } - [JsonProperty("TimeZoneId")] public string TimeZoneId { get; set; } + [JsonProperty("UserType")] public UserType UserType { get; set; } + + public async Task SetPassword(string password) + { + var request = TcaClient.UsersController.GenerateDefaultRequest(nameof(SetPassword), UserId.ToString()); + request.Method = HttpMethod.Post; + request.Content = new FormUrlEncodedContent(new[] + { new KeyValuePair(nameof(password), password) }); + return (await TcaClient.UsersController.ExecuteBaseResponseRequest(request)).Success; + } - [JsonProperty("UserType")] public UserType UserType { get; set; } + public async Task Update(Action action) + { + var service = new User(); + action(service); + var putJson = JsonConvert.SerializeObject(service, Constants.IgnoreDefaultValues); + var request = TcaClient.UsersController.GenerateDefaultRequest(UserId.ToString()); + request.Method = HttpMethod.Put; + request.Content = new StringContent(putJson, Encoding.UTF8, Constants.JsonContentType); + return (await TcaClient.UsersController.ExecuteBaseResponseRequest(request)).Success; + } - [JsonIgnore] - public IList Services => - Controller.TcaClient.ServicesController.GetServicesByUserId(UserId).GetAwaiter().GetResult().Result; + public Task Delete() + { + throw new NotImplementedException(); + } - public async Task SetPassword(string password) - { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"setpassword/{UserId}"; - request.Method = Method.POST; - request.AddParameter("password", password, ParameterType.GetOrPost); - return (await Controller.ExecuteBaseResponseRequest(request)).Success; - } - - public async Task Update(Action action) - { - var service = new User(); - action(service); - var putJson = JsonConvert.SerializeObject(service, Constants.IgnoreDefaultValues); - var request = Controller.GenerateDefaultRequest(); - request.Resource += UserId; - request.Method = Method.PUT; - request.AddParameter(Constants.JsonContentType, putJson, ParameterType.RequestBody); - return (await Controller.ExecuteBaseResponseRequest(request)).Success; - } - - public Task Delete() + public async Task Suspend(bool recursive = true, bool suspendServices = true) + { + var request = TcaClient.UsersController.GenerateDefaultRequest(nameof(Suspend), UserId.ToString()); + request.Method = HttpMethod.Post; + request.Content = new FormUrlEncodedContent(new[] { - throw new NotImplementedException(); - } + new KeyValuePair(nameof(recursive), recursive.ToString()), + new KeyValuePair(nameof(suspendServices), suspendServices.ToString()) + }); + return (await TcaClient.UsersController.ExecuteBaseResponseRequest(request)).Success; + } - public async Task Suspend(bool recursive = true, bool suspendServices = true) - { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"suspend/{UserId}"; - request.Method = Method.POST; - request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); - request.AddParameter(nameof(suspendServices), suspendServices, ParameterType.GetOrPost); - return (await Controller.ExecuteBaseResponseRequest(request)).Success; - } - - public async Task Unsuspend(bool recursive = true, bool enableServices = true) + public async Task Unsuspend(bool recursive = true, bool enableServices = true) + { + var request = TcaClient.UsersController.GenerateDefaultRequest(nameof(Unsuspend), UserId.ToString()); + request.Method = HttpMethod.Post; + request.Content = new FormUrlEncodedContent(new[] { - var request = Controller.GenerateDefaultRequest(); - request.Resource += $"unsuspend/{UserId}"; - request.Method = Method.POST; - request.AddParameter(nameof(recursive), recursive, ParameterType.GetOrPost); - request.AddParameter(nameof(enableServices), enableServices, ParameterType.GetOrPost); - return (await Controller.ExecuteBaseResponseRequest(request)).Success; - } + new KeyValuePair(nameof(recursive), recursive.ToString()), + new KeyValuePair(nameof(enableServices), enableServices.ToString()) + }); + return (await TcaClient.UsersController.ExecuteBaseResponseRequest(request)).Success; + } + + public async Task> GetServices() + { + return await TcaClient.ServicesController.GetServicesByUserId(UserId); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/User/UserType.cs b/TCAdminApiSharp/Entities/User/UserType.cs index 9294939..a48b336 100644 --- a/TCAdminApiSharp/Entities/User/UserType.cs +++ b/TCAdminApiSharp/Entities/User/UserType.cs @@ -1,9 +1,8 @@ -namespace TCAdminApiSharp.Entities.User +namespace TCAdminApiSharp.Entities.User; + +public enum UserType { - public enum UserType - { - User = 1, - SubAdmin = 2, - Admin = 3 - } + User = 1, + SubAdmin = 2, + Admin = 3 } \ No newline at end of file diff --git a/TCAdminApiSharp/Exceptions/API/ApiRequestException.cs b/TCAdminApiSharp/Exceptions/API/ApiRequestException.cs deleted file mode 100644 index f31abd5..0000000 --- a/TCAdminApiSharp/Exceptions/API/ApiRequestException.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using RestSharp; - -namespace TCAdminApiSharp.Exceptions.API -{ - public class ApiRequestException : Exception - { - public readonly RestRequest RestRequest; - - internal ApiRequestException(RestRequest restRequest) - { - RestRequest = restRequest; - } - - internal ApiRequestException(RestRequest restRequest, string? message) : base(message) - { - RestRequest = restRequest; - } - - internal ApiRequestException(RestRequest restRequest, string? message, Exception? innerException) : base( - message, innerException) - { - RestRequest = restRequest; - } - - internal ApiRequestException(RestRequest restRequest, Exception? innerException) : base(null, innerException) - { - RestRequest = restRequest; - } - } -} \ No newline at end of file diff --git a/TCAdminApiSharp/Exceptions/API/ApiResponseException.cs b/TCAdminApiSharp/Exceptions/API/ApiResponseException.cs index 521ad85..53a16ab 100644 --- a/TCAdminApiSharp/Exceptions/API/ApiResponseException.cs +++ b/TCAdminApiSharp/Exceptions/API/ApiResponseException.cs @@ -1,29 +1,36 @@ using System; -using RestSharp; -using TCAdminApiSharp.Entities; +using System.Net.Http; +using Newtonsoft.Json; using TCAdminApiSharp.Entities.API; -namespace TCAdminApiSharp.Exceptions.API +namespace TCAdminApiSharp.Exceptions.API; + +public class ApiResponseException : Exception { - public class ApiResponseException : Exception - { - public readonly IRestResponse RestResponse; - public readonly ErrorResponse ErrorResponse; + public readonly HttpResponseMessage HttpResponseMessage; + public readonly BaseResponse ExceptionResponse; - internal ApiResponseException() - { - } + internal ApiResponseException() + { + } - internal ApiResponseException(IRestResponse restResponse) : this() - { - RestResponse = restResponse; - ErrorResponse = new ErrorResponse(restResponse); - } + internal ApiResponseException(HttpResponseMessage httpResponseMessage) : this() + { + this.HttpResponseMessage = httpResponseMessage; + var readAsStringAsync = HttpResponseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + ExceptionResponse = JsonConvert.DeserializeObject>(readAsStringAsync); + } - internal ApiResponseException(IRestResponse restResponse, string message) : base(message) - { - RestResponse = restResponse; - ErrorResponse = new ErrorResponse(restResponse); - } + internal ApiResponseException(HttpResponseMessage httpResponseMessage, string message) : base(message) + { + this.HttpResponseMessage = httpResponseMessage; + var readAsStringAsync = HttpResponseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + ExceptionResponse = JsonConvert.DeserializeObject>(readAsStringAsync); + } + + internal ApiResponseException(HttpResponseMessage httpResponseMessage, BaseResponse exceptionResponse) : base(exceptionResponse.Message) + { + this.HttpResponseMessage = httpResponseMessage; + ExceptionResponse = exceptionResponse; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Exceptions/NotFoundException.cs b/TCAdminApiSharp/Exceptions/NotFoundException.cs deleted file mode 100644 index 1c02ff1..0000000 --- a/TCAdminApiSharp/Exceptions/NotFoundException.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace TCAdminApiSharp.Exceptions -{ - public class NotFoundException : Exception - { - public readonly Type Type; - public readonly int[] Ids; - - public NotFoundException(Type type, params int[] ids) : base( - $"The {type.FullName} could not be found with ids: [{string.Join(", ", ids)}]") - { - Type = type; - Ids = ids; - } - - public NotFoundException(Type type, Exception innerException, int[] ids) : base( - $"The {type.FullName} could not be found", innerException) - { - Type = type; - Ids = ids; - } - } -} \ No newline at end of file diff --git a/TCAdminApiSharp/Helpers/Constants.cs b/TCAdminApiSharp/Helpers/Constants.cs index cbf59de..c561b0d 100644 --- a/TCAdminApiSharp/Helpers/Constants.cs +++ b/TCAdminApiSharp/Helpers/Constants.cs @@ -1,20 +1,20 @@ using Newtonsoft.Json; -namespace TCAdminApiSharp.Helpers +namespace TCAdminApiSharp.Helpers; + +internal static class Constants { - internal static class Constants - { - public const string JsonContentType = "application/json"; + public const string JsonContentType = "application/json"; - public static readonly JsonSerializerSettings IgnoreDefaultValues = new() - { - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; + public static readonly JsonSerializerSettings IgnoreDefaultValues = new() + { + NullValueHandling = NullValueHandling.Ignore, + DefaultValueHandling = DefaultValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }; - public static readonly JsonSerializerSettings IgnoreReferenceLoop = new() - { - ReferenceLoopHandling = ReferenceLoopHandling.Ignore - }; - } + public static readonly JsonSerializerSettings IgnoreReferenceLoop = new() + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }; } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/IQueryOperation.cs b/TCAdminApiSharp/Querying/IQueryOperation.cs index a5c7a46..b10b642 100644 --- a/TCAdminApiSharp/Querying/IQueryOperation.cs +++ b/TCAdminApiSharp/Querying/IQueryOperation.cs @@ -1,15 +1,9 @@ -using Newtonsoft.Json.Linq; -using RestSharp; +using System.Net.Http; -namespace TCAdminApiSharp.Querying -{ - public interface IQueryOperation - { - string JsonKey { get; set; } - - void ModifyRequest(IRestRequest request) - { +namespace TCAdminApiSharp.Querying; - } - } +public interface IQueryOperation +{ + string JsonKey { get; set; } + void ModifyRequest(HttpRequestMessage request); } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operations/FilterList.cs b/TCAdminApiSharp/Querying/Operations/FilterList.cs index 31748b9..e044afb 100644 --- a/TCAdminApiSharp/Querying/Operations/FilterList.cs +++ b/TCAdminApiSharp/Querying/Operations/FilterList.cs @@ -1,62 +1,60 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; +using Microsoft.AspNetCore.WebUtilities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using RestSharp; using TCAdminApiSharp.Querying.Structs; -namespace TCAdminApiSharp.Querying.Operations +namespace TCAdminApiSharp.Querying.Operations; + +public class FilterList : List, IQueryOperation { - public class FilterList : List, IQueryOperation - { - [JsonIgnore] - public string JsonKey { get; set; } = "Fields"; + [JsonIgnore] + public string JsonKey { get; set; } = "Fields"; - public FilterList() - { - } + public FilterList() + { + } - public FilterList(params string[] where) + public FilterList(params string[] where) + { + foreach (var filterInfo in where) { - foreach (var filterInfo in where) - { - Add(filterInfo); - } + Add(filterInfo); } + } - public FilterList(FilterInfo where) - { - Add(where); - } + public FilterList(FilterInfo where) + { + Add(where); + } - public FilterList(params FilterInfo[] where) - { - foreach (var filterInfo in @where) - { - Add(filterInfo); - } - } - - public void Add(string column) + public FilterList(params FilterInfo[] where) + { + foreach (var filterInfo in @where) { - Add(new FilterInfo() - { - Column = column - }); + Add(filterInfo); } + } - public JToken GenerateQuery() + public void Add(string column) + { + Add(new FilterInfo { - var temp = this.Aggregate("(", (current, info) => current + $"[{info.Column}]"); + Column = column + }); + } - temp += ")"; - return new JValue(temp); - } + public JToken GenerateQuery() + { + var temp = this.Aggregate("(", (current, info) => current + $"[{info.Column}]") + ")"; + return new JValue(temp); + } - public void ModifyRequest(IRestRequest request) - { - request.AddQueryParameter("fields", string.Join(",", this.Select(x => x.Column.ToLower()))); - } + public void ModifyRequest(HttpRequestMessage request) + { + request.RequestUri = new Uri(QueryHelpers.AddQueryString(request.RequestUri.ToString(), JsonKey, GenerateQuery().ToString())); } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operations/OrderList.cs b/TCAdminApiSharp/Querying/Operations/OrderList.cs index 898c387..bab5d8a 100644 --- a/TCAdminApiSharp/Querying/Operations/OrderList.cs +++ b/TCAdminApiSharp/Querying/Operations/OrderList.cs @@ -1,53 +1,55 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; +using Microsoft.AspNetCore.WebUtilities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using RestSharp; using TCAdminApiSharp.Querying.Operators; using TCAdminApiSharp.Querying.Structs; -namespace TCAdminApiSharp.Querying.Operations +namespace TCAdminApiSharp.Querying.Operations; + +public class OrderList : List, IQueryOperation { - public class OrderList : List, IQueryOperation + [JsonIgnore] public string JsonKey { get; set; } = "Order"; + + public OrderList() { - [JsonIgnore] public string JsonKey { get; set; } = "Order"; + } - public OrderList() - { - } + public OrderList(string field, OrderOperator @operator) + { + Add(field, @operator); + } - public OrderList(string field, OrderOperator @operator) + public void Add(string column, OrderOperator @operator) + { + Add(new OrderInfo { - Add(field, @operator); - } + Column = column, + Operator = @operator + }); + } - public void Add(string column, OrderOperator @operator) - { - Add(new OrderInfo - { - Column = column, - Operator = @operator - }); - } + public JToken GenerateQuery() + { + return JToken.FromObject(this); + } - public JToken GenerateQuery() + public void ModifyRequest(HttpRequestMessage request) + { + JObject jObject = new(); + var dictionary = QueryHelpers.ParseQuery(request.RequestUri.ToString()); + var queryInfoExists = dictionary.Any(x => x.Key == "queryInfo"); + if (queryInfoExists) { - return JToken.FromObject(this); + jObject = JsonConvert.DeserializeObject(dictionary.FirstOrDefault(x => x.Key == "queryInfo").Value.ToString()!); } - public void ModifyRequest(IRestRequest request) - { - JObject jObject = new(); - var queryInfoExists = request.Parameters.Any(x => x.Name == "queryInfo"); - if (queryInfoExists) - { - jObject = JsonConvert.DeserializeObject(request.Parameters.Find(x => x.Name == "queryInfo")!.Value!.ToString()!); - } - - jObject[JsonKey] = JToken.FromObject(this); - - request.AddOrUpdateParameter("queryInfo", jObject, ParameterType.GetOrPost); - } + jObject[JsonKey] = GenerateQuery(); + request.RequestUri = + new Uri(QueryHelpers.AddQueryString(request.RequestUri.ToString(), "queryInfo", jObject.ToString())); + } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operations/WhereList.cs b/TCAdminApiSharp/Querying/Operations/WhereList.cs index ebaefc5..9e1e9fb 100644 --- a/TCAdminApiSharp/Querying/Operations/WhereList.cs +++ b/TCAdminApiSharp/Querying/Operations/WhereList.cs @@ -1,112 +1,113 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; using System.Runtime.CompilerServices; +using Microsoft.AspNetCore.WebUtilities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using RestSharp; using TCAdminApiSharp.Querying.Operators; using TCAdminApiSharp.Querying.Structs; -namespace TCAdminApiSharp.Querying.Operations +namespace TCAdminApiSharp.Querying.Operations; + +public class WhereList : List, IQueryOperation { - public class WhereList : List, IQueryOperation - { - [System.Text.Json.Serialization.JsonIgnore] public string JsonKey { get; set; } = "Where"; - [System.Text.Json.Serialization.JsonIgnore] public WhereOperator WhereOperator { get; set; } + [System.Text.Json.Serialization.JsonIgnore] public string JsonKey { get; set; } = "Where"; + [System.Text.Json.Serialization.JsonIgnore] public WhereOperator WhereOperator { get; set; } - public WhereList() - { - WhereOperator = WhereOperator.And; - } + public WhereList() + { + WhereOperator = WhereOperator.And; + } - public WhereList(WhereInfo where) - { - WhereOperator = WhereOperator.And; - Add(where); - } + public WhereList(WhereInfo where) + { + WhereOperator = WhereOperator.And; + Add(where); + } - public WhereList(string column, object value) - { - WhereOperator = WhereOperator.And; - Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); - } + public WhereList(string column, object value) + { + WhereOperator = WhereOperator.And; + Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); + } - public WhereList(string column, ColumnOperator @operator, object value) + public WhereList(string column, ColumnOperator @operator, object value) + { + WhereOperator = WhereOperator.And; + Add(new WhereInfo { - WhereOperator = WhereOperator.And; - Add(new WhereInfo - { - Column = column, - ColumnOperator = @operator, - ColumnValue = RuntimeHelpers.GetObjectValue(value) - }); - } + Column = column, + ColumnOperator = @operator, + ColumnValue = RuntimeHelpers.GetObjectValue(value) + }); + } - public void Add(string column, object value) - { - Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); - } + public void Add(string column, object value) + { + Add(column, ColumnOperator.Equal, RuntimeHelpers.GetObjectValue(value)); + } - public void Add(string column, ColumnOperator @operator, object value) + public void Add(string column, ColumnOperator @operator, object value) + { + Add(new WhereInfo { - Add(new WhereInfo - { - Column = column, - ColumnOperator = @operator, - ColumnValue = value - }); - } + Column = column, + ColumnOperator = @operator, + ColumnValue = value + }); + } - public JToken GenerateQuery() + public JToken GenerateQuery() + { + var temp = "("; + foreach (var info in this) { - var temp = "("; - foreach (var info in this) + var tempColumnName = info.Column; + if (!tempColumnName.StartsWith("[") && !tempColumnName.EndsWith("]")) { - var tempColumnName = info.Column; - if (!tempColumnName.StartsWith("[") && !tempColumnName.EndsWith("]")) - { - tempColumnName = $"[{info.Column}]"; - } - - temp += $"{tempColumnName} {ConvertColumnOperator(info.ColumnOperator)} '{info.ColumnValue}'"; - if (!this.Last().Equals(info)) - // Add where operator - temp += $" {WhereOperator.ToString().ToUpper()} "; + tempColumnName = $"[{info.Column}]"; } - - temp += ")"; - return new JValue(temp); + + temp += $"{tempColumnName} {ConvertColumnOperator(info.ColumnOperator)} '{info.ColumnValue}'"; + if (!this.Last().Equals(info)) + // Add where operator + temp += $" {WhereOperator.ToString().ToUpper()} "; } - public void ModifyRequest(IRestRequest request) - { - JObject jObject = new(); - var queryInfoExists = request.Parameters.Any(x => x.Name == "queryInfo"); - if (queryInfoExists) - { - jObject = JsonConvert.DeserializeObject(request.Parameters.Find(x => x.Name == "queryInfo")!.Value!.ToString()!); - } - - jObject[JsonKey] = GenerateQuery(); + temp += ")"; + return new JValue(temp); + } - request.AddOrUpdateParameter("queryInfo", jObject, ParameterType.GetOrPost); + public void ModifyRequest(HttpRequestMessage request) + { + JObject jObject = new(); + var dictionary = QueryHelpers.ParseQuery(request.RequestUri.ToString()); + var queryInfoExists = dictionary.Any(x => x.Key == "queryInfo"); + if (queryInfoExists) + { + jObject = JsonConvert.DeserializeObject(dictionary.FirstOrDefault(x => x.Key == "queryInfo").Value.ToString()!); } - public static string ConvertColumnOperator(ColumnOperator columnOperator) + jObject[JsonKey] = GenerateQuery(); + request.RequestUri = + new Uri(QueryHelpers.AddQueryString(request.RequestUri.ToString(), "queryInfo", jObject.ToString())); + } + + public static string ConvertColumnOperator(ColumnOperator columnOperator) + { + return columnOperator switch { - return columnOperator switch - { - ColumnOperator.Equal => "=", - ColumnOperator.NotEqual => "<>", - ColumnOperator.GreaterThan => ">", - ColumnOperator.GreaterOrEqualTo => ">=", - ColumnOperator.LowerThan => "<", - ColumnOperator.LowerOrEqualTo => "<=", - ColumnOperator.Like => "LIKE", - ColumnOperator.NotLike => "NOT LIKE", - _ => throw new ArgumentOutOfRangeException(nameof(columnOperator), columnOperator, null) - }; - } + ColumnOperator.Equal => "=", + ColumnOperator.NotEqual => "<>", + ColumnOperator.GreaterThan => ">", + ColumnOperator.GreaterOrEqualTo => ">=", + ColumnOperator.LowerThan => "<", + ColumnOperator.LowerOrEqualTo => "<=", + ColumnOperator.Like => "LIKE", + ColumnOperator.NotLike => "NOT LIKE", + _ => throw new ArgumentOutOfRangeException(nameof(columnOperator), columnOperator, null) + }; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operators/ColumnOperator.cs b/TCAdminApiSharp/Querying/Operators/ColumnOperator.cs index e82dd6c..a6b783e 100644 --- a/TCAdminApiSharp/Querying/Operators/ColumnOperator.cs +++ b/TCAdminApiSharp/Querying/Operators/ColumnOperator.cs @@ -1,14 +1,13 @@ -namespace TCAdminApiSharp.Querying.Operators +namespace TCAdminApiSharp.Querying.Operators; + +public enum ColumnOperator { - public enum ColumnOperator - { - Equal, - NotEqual, - GreaterThan, - GreaterOrEqualTo, - LowerThan, - LowerOrEqualTo, - Like, - NotLike - } + Equal, + NotEqual, + GreaterThan, + GreaterOrEqualTo, + LowerThan, + LowerOrEqualTo, + Like, + NotLike } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operators/OrderOperator.cs b/TCAdminApiSharp/Querying/Operators/OrderOperator.cs index c39991c..dbd7d7d 100644 --- a/TCAdminApiSharp/Querying/Operators/OrderOperator.cs +++ b/TCAdminApiSharp/Querying/Operators/OrderOperator.cs @@ -1,8 +1,7 @@ -namespace TCAdminApiSharp.Querying.Operators +namespace TCAdminApiSharp.Querying.Operators; + +public enum OrderOperator { - public enum OrderOperator - { - Ascending, - Descending - } + Ascending, + Descending } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Operators/WhereOperator.cs b/TCAdminApiSharp/Querying/Operators/WhereOperator.cs index faafd5c..4684da5 100644 --- a/TCAdminApiSharp/Querying/Operators/WhereOperator.cs +++ b/TCAdminApiSharp/Querying/Operators/WhereOperator.cs @@ -1,8 +1,7 @@ -namespace TCAdminApiSharp.Querying.Operators +namespace TCAdminApiSharp.Querying.Operators; + +public enum WhereOperator { - public enum WhereOperator - { - And, - Or - } + And, + Or } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/QueryableInfo.cs b/TCAdminApiSharp/Querying/QueryableInfo.cs index 7134908..b776bee 100644 --- a/TCAdminApiSharp/Querying/QueryableInfo.cs +++ b/TCAdminApiSharp/Querying/QueryableInfo.cs @@ -1,40 +1,38 @@ using System.Collections.Generic; +using System.Net.Http; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using RestSharp; -namespace TCAdminApiSharp.Querying +namespace TCAdminApiSharp.Querying; + +public class QueryableInfo { - public class QueryableInfo - { - [JsonProperty("RowCount")] public int RowCount { get; set; } + [JsonProperty("RowCount")] public int RowCount { get; set; } - [JsonProperty("Offset")] public int Offset { get; set; } + [JsonProperty("Offset")] public int Offset { get; set; } - [JsonIgnore] public List QueryOperations { get; set; } = new(); + [JsonIgnore] public List QueryOperations { get; set; } = new(); - public QueryableInfo() - { - } + public QueryableInfo() + { + } - public QueryableInfo(int rowCount, int offset, IQueryOperation queryOperation) - { - RowCount = rowCount; - Offset = offset; - QueryOperations.Add(queryOperation); - } + public QueryableInfo(int rowCount, int offset, IQueryOperation queryOperation) + { + RowCount = rowCount; + Offset = offset; + QueryOperations.Add(queryOperation); + } - public QueryableInfo(params IQueryOperation[] queryOperations) - { - foreach (var queryOperation in queryOperations) QueryOperations.Add(queryOperation); - } + public QueryableInfo(params IQueryOperation[] queryOperations) + { + foreach (var queryOperation in queryOperations) QueryOperations.Add(queryOperation); + } - public void BuildQuery(IRestRequest request) + public void BuildQuery(HttpRequestMessage request) + { + foreach (var queryOperation in QueryOperations) { - foreach (var queryOperation in QueryOperations) - { - queryOperation.ModifyRequest(request); - } + queryOperation.ModifyRequest(request); } } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Structs/FilterInfo.cs b/TCAdminApiSharp/Querying/Structs/FilterInfo.cs index ce70ce4..6c101f9 100644 --- a/TCAdminApiSharp/Querying/Structs/FilterInfo.cs +++ b/TCAdminApiSharp/Querying/Structs/FilterInfo.cs @@ -1,12 +1,11 @@ -namespace TCAdminApiSharp.Querying.Structs +namespace TCAdminApiSharp.Querying.Structs; + +public struct FilterInfo { - public struct FilterInfo - { - public string Column; + public string Column; - public FilterInfo(string column) - { - Column = column; - } + public FilterInfo(string column) + { + Column = column; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Structs/OrderInfo.cs b/TCAdminApiSharp/Querying/Structs/OrderInfo.cs index bd874ab..bd831e4 100644 --- a/TCAdminApiSharp/Querying/Structs/OrderInfo.cs +++ b/TCAdminApiSharp/Querying/Structs/OrderInfo.cs @@ -2,13 +2,12 @@ using Newtonsoft.Json.Converters; using TCAdminApiSharp.Querying.Operators; -namespace TCAdminApiSharp.Querying.Structs +namespace TCAdminApiSharp.Querying.Structs; + +public struct OrderInfo { - public struct OrderInfo - { - [JsonProperty("Field")] public string Column; + [JsonProperty("Field")] public string Column; - [JsonProperty("Direction")] [JsonConverter(typeof(StringEnumConverter))] - public OrderOperator Operator; - } + [JsonProperty("Direction")] [JsonConverter(typeof(StringEnumConverter))] + public OrderOperator Operator; } \ No newline at end of file diff --git a/TCAdminApiSharp/Querying/Structs/WhereInfo.cs b/TCAdminApiSharp/Querying/Structs/WhereInfo.cs index ee71a30..f30af32 100644 --- a/TCAdminApiSharp/Querying/Structs/WhereInfo.cs +++ b/TCAdminApiSharp/Querying/Structs/WhereInfo.cs @@ -2,14 +2,13 @@ using Newtonsoft.Json.Converters; using TCAdminApiSharp.Querying.Operators; -namespace TCAdminApiSharp.Querying.Structs +namespace TCAdminApiSharp.Querying.Structs; + +public struct WhereInfo { - public struct WhereInfo - { - public string Column; - public object ColumnValue; + public string Column; + public object ColumnValue; - [JsonConverter(typeof(StringEnumConverter))] - public ColumnOperator ColumnOperator; - } + [JsonConverter(typeof(StringEnumConverter))] + public ColumnOperator ColumnOperator; } \ No newline at end of file diff --git a/TCAdminApiSharp/TCAdminApiSharp.csproj b/TCAdminApiSharp/TCAdminApiSharp.csproj index 3ab1d15..be263b5 100644 --- a/TCAdminApiSharp/TCAdminApiSharp.csproj +++ b/TCAdminApiSharp/TCAdminApiSharp.csproj @@ -1,7 +1,7 @@ - net5.0 + net6.0 enable true TCAdminAPISharp @@ -12,22 +12,16 @@ https://avatars3.githubusercontent.com/u/67070230?s=200&v=4 https://github.com/TotalControlAdmin/TCAdminApiSharp TCAdmin, Wrapper, Rest, Api - 1.0.2 - 1.0.2 + 2.0.0 + 2.0.0 1.0.2 - - - - - - - - - - + + + + diff --git a/TCAdminApiSharp/TcaClient.cs b/TCAdminApiSharp/TcaClient.cs index 40a06a4..0f0aa56 100644 --- a/TCAdminApiSharp/TcaClient.cs +++ b/TCAdminApiSharp/TcaClient.cs @@ -1,71 +1,60 @@ using System; -using Microsoft.Extensions.DependencyInjection; -using RestSharp; +using System.Net.Http; using Serilog; using Serilog.Events; using TCAdminApiSharp.Controllers; +using TCAdminApiSharp.Helpers; -// ReSharper disable NotAccessedField.Global +namespace TCAdminApiSharp; -namespace TCAdminApiSharp +public class TcaClient : IDisposable { - public class TcaClient + public readonly string Host; + private readonly string _apiKey; + public readonly ServicesController ServicesController; + public readonly ServersController ServersController; + public readonly UsersController UsersController; + public readonly TasksController TasksController; + public readonly TcaClientSettings Settings; + internal readonly HttpClient HttpClient; + + public TcaClient(string host, string apiKey, TcaClientSettings? clientSettings = null) { - public readonly string Host; - private readonly string _apiKey; - internal static ServiceProvider ServiceProvider = new ServiceCollection().BuildServiceProvider(); - internal readonly RestClient RestClient; - public readonly ServicesController ServicesController; - public readonly ServersController ServersController; - public readonly UsersController UsersController; - public readonly TasksController TasksController; - public readonly TcaClientSettings Settings; - - public TcaClient(string host, string apiKey, TcaClientSettings? clientSettings = null) - { - clientSettings ??= TcaClientSettings.Default; - SetupDefaultLogger(clientSettings.MinimumLogLevel); - InitializeDI(); - if (string.IsNullOrEmpty(host)) throw new ArgumentException("Parameter is null/empty", nameof(host)); - if (string.IsNullOrEmpty(apiKey)) throw new ArgumentException("Parameter is null/empty", nameof(apiKey)); - - Settings = clientSettings; - Host = host; - _apiKey = apiKey; - - RestClient = new RestClient(Host); - RestClient.AddDefaultHeader("api_key", apiKey); - - ServicesController = ServiceProvider.GetService() ?? - throw new InvalidOperationException(); - ServersController = - ServiceProvider.GetService() ?? throw new InvalidOperationException(); - UsersController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); - TasksController = ServiceProvider.GetService() ?? throw new InvalidOperationException(); - } + clientSettings ??= TcaClientSettings.Default; + SetupDefaultLogger(clientSettings.MinimumLogLevel); + if (string.IsNullOrEmpty(host)) throw new ArgumentException("Parameter is null/empty", nameof(host)); + if (string.IsNullOrEmpty(apiKey)) throw new ArgumentException("Parameter is null/empty", nameof(apiKey)); + + Settings = clientSettings; + Host = host; + _apiKey = apiKey; + + HttpClient = new HttpClient(); + HttpClient.BaseAddress = new Uri(Host); + HttpClient.DefaultRequestHeaders.Add("api_key", _apiKey); + HttpClient.DefaultRequestHeaders.Add("accept", Constants.JsonContentType); + + ServicesController = new ServicesController(this); + ServersController = new ServersController(this); + UsersController = new UsersController(this); + TasksController = new TasksController(this); + } - internal int GetTokenUserId() - { - return int.Parse(_apiKey.Split('#')[0]); - } + internal int GetTokenUserId() + { + return int.Parse(_apiKey.Split('#')[0]); + } - private void InitializeDI() - { - ServiceProvider = new ServiceCollection() - .AddTransient(_ => this) - .AddScoped() - .AddScoped() - .AddScoped() - .AddScoped() - .BuildServiceProvider(); - } + private static void SetupDefaultLogger(LogEventLevel logEventLevel) + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Is(logEventLevel) + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .CreateLogger(); + } - private static void SetupDefaultLogger(LogEventLevel logEventLevel) - { - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Is(logEventLevel) - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .CreateLogger(); - } + public void Dispose() + { + HttpClient.Dispose(); } } \ No newline at end of file diff --git a/TCAdminApiSharp/TcaClientSettings.cs b/TCAdminApiSharp/TcaClientSettings.cs index 618fd50..dc36912 100644 --- a/TCAdminApiSharp/TcaClientSettings.cs +++ b/TCAdminApiSharp/TcaClientSettings.cs @@ -1,21 +1,18 @@ using Serilog.Events; -namespace TCAdminApiSharp +namespace TCAdminApiSharp; + +public class TcaClientSettings { - public class TcaClientSettings - { - public LogEventLevel MinimumLogLevel { get; set; } = LogEventLevel.Error; - public bool ThrowOnApiSuccessFailure { get; set; } = true; + public LogEventLevel MinimumLogLevel { get; set; } = LogEventLevel.Information; - public bool ThrowOnApiResponseStatusNonComplete { get; set; } = true; - public bool ThrowOnApiStatusCodeNonOk { get; set; } = true; + public bool ThrowOnApiResponseStatusNonComplete { get; set; } - public static TcaClientSettings Default => new(); + public static TcaClientSettings Default => new(); - public static TcaClientSettings Debug => new() - { - MinimumLogLevel = LogEventLevel.Debug, - ThrowOnApiSuccessFailure = true - }; - } + public static TcaClientSettings Debug => new() + { + MinimumLogLevel = LogEventLevel.Debug, + ThrowOnApiResponseStatusNonComplete = true + }; } \ No newline at end of file From d4823fce5a6b00e0586bf7d33e672a6c338453bc Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Thu, 30 Jun 2022 12:58:09 +0100 Subject: [PATCH 28/31] Remove property --- .github/workflows/Publish - Dev.yml | 2 +- TCAdminApiSharp/TCAdminApiSharp.csproj | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/Publish - Dev.yml b/.github/workflows/Publish - Dev.yml index 17cf35b..2dadaff 100644 --- a/.github/workflows/Publish - Dev.yml +++ b/.github/workflows/Publish - Dev.yml @@ -1,4 +1,4 @@ -name: Dev - Build + Deploy +name: Dev - Build + Publish on: push: diff --git a/TCAdminApiSharp/TCAdminApiSharp.csproj b/TCAdminApiSharp/TCAdminApiSharp.csproj index be263b5..c6300a5 100644 --- a/TCAdminApiSharp/TCAdminApiSharp.csproj +++ b/TCAdminApiSharp/TCAdminApiSharp.csproj @@ -3,7 +3,6 @@ net6.0 enable - true TCAdminAPISharp Alex Redding A C# Wrapper for the TCAdmin REST API. From 79203f375ed1d7104031aa14321701a0cc28951b Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Thu, 7 Jul 2022 01:12:58 +0100 Subject: [PATCH 29/31] Update --- TCAdminApiSharp.Tests/ServerTests.cs | 2 +- TCAdminApiSharp.Tests/ServiceTests.cs | 3 +- TCAdminApiSharp.Tests/UserTests.cs | 57 +++++++++++++++++++ TCAdminApiSharp/Controllers/BaseController.cs | 12 ++-- .../Controllers/ServicesController.cs | 3 +- .../Controllers/UsersController.cs | 5 +- .../Entities/Service/EServiceStatus.cs | 16 ++++++ TCAdminApiSharp/Entities/Service/Player.cs | 12 ++++ TCAdminApiSharp/Entities/Service/Service.cs | 26 +++++---- .../Entities/Service/ServiceQuery.cs | 41 +++++++++++++ .../Entities/Service/ServiceStatus.cs | 41 ++++++++----- TCAdminApiSharp/Entities/User/User.cs | 20 +++---- .../Querying/Operations/WhereList.cs | 3 +- TCAdminApiSharp/TCAdminApiSharp.csproj | 16 ++++-- TCAdminApiSharp/TcaClient.cs | 13 ++++- 15 files changed, 215 insertions(+), 55 deletions(-) create mode 100644 TCAdminApiSharp.Tests/UserTests.cs create mode 100644 TCAdminApiSharp/Entities/Service/EServiceStatus.cs create mode 100644 TCAdminApiSharp/Entities/Service/Player.cs create mode 100644 TCAdminApiSharp/Entities/Service/ServiceQuery.cs diff --git a/TCAdminApiSharp.Tests/ServerTests.cs b/TCAdminApiSharp.Tests/ServerTests.cs index 5a6fcdd..4d99d09 100644 --- a/TCAdminApiSharp.Tests/ServerTests.cs +++ b/TCAdminApiSharp.Tests/ServerTests.cs @@ -27,7 +27,7 @@ public async Task GetServerTest() var server = await _tcaClient.ServersController.GetServer(1); Assert.AreEqual("Master", server.Name); } - + // [Test] // public async Task GetServersTest() // { diff --git a/TCAdminApiSharp.Tests/ServiceTests.cs b/TCAdminApiSharp.Tests/ServiceTests.cs index d0c54c9..77b26c8 100644 --- a/TCAdminApiSharp.Tests/ServiceTests.cs +++ b/TCAdminApiSharp.Tests/ServiceTests.cs @@ -35,7 +35,7 @@ public async Task ServiceStart() var service = await _tcaClient.ServicesController.GetService(1); await service.Start(); service = await _tcaClient.ServicesController.GetService(1); - Assert.AreEqual(ServiceStatus.Running, service.ServiceStatus); + Assert.AreEqual(EServiceStatus.Running, service.EServiceStatus); } [Test] @@ -97,6 +97,7 @@ public async Task UpdateServiceTest() await service.Update(x => { x.Slots = 5; + x.Variables.Add("test", 123); // x.Executable = "changed.exe"; }); } diff --git a/TCAdminApiSharp.Tests/UserTests.cs b/TCAdminApiSharp.Tests/UserTests.cs new file mode 100644 index 0000000..d83490c --- /dev/null +++ b/TCAdminApiSharp.Tests/UserTests.cs @@ -0,0 +1,57 @@ +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using NUnit.Framework; +using TCAdminApiSharp.Entities.User; +using TCAdminApiSharp.Querying; +using TCAdminApiSharp.Querying.Operations; + +namespace TCAdminApiSharp.Tests; + +public class UserTests +{ + private TcaClient _tcaClient; + + [SetUp] + public void Setup() + { + var config = new ConfigurationBuilder().AddJsonFile("appsettings.json") + .AddJsonFile("appsettings.local.json", true) + .Build().GetSection("TCAdmin"); + var activeProfile = config["ActiveProfile"]; + var profileSection = config.GetSection("Profiles").GetSection(activeProfile); + var host = profileSection["Host"]; + var key = profileSection["Key"]; + _tcaClient = new TcaClient(host, key, TcaClientSettings.Debug); + } + + [Test] + public async Task GetUserAdvancedTest() + { + var users = await _tcaClient.UsersController.FindUsers(new QueryableInfo(new WhereList(nameof(User.UserName), "admin"))); + Assert.AreEqual(1, users.Count); + var user = users.Result.First(); + Assert.AreEqual("Admin", user.UserName); + } + + [Test] + public async Task GetUserTest() + { + var user = await _tcaClient.UsersController.GetUser(3); + Assert.AreEqual("Admin", user.UserName); + } + + [Test] + public async Task UpdateUserTest() + { + var user = await _tcaClient.UsersController.GetUser(4); + await user.Update(x => + { + x.FirstName = "Api"; + x.LastName = "Update"; + }); + user = await _tcaClient.UsersController.GetUser(4); + Assert.AreEqual("Api", user.FirstName); + Assert.AreEqual("Update", user.LastName); + } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Controllers/BaseController.cs b/TCAdminApiSharp/Controllers/BaseController.cs index c83dd00..906ac13 100644 --- a/TCAdminApiSharp/Controllers/BaseController.cs +++ b/TCAdminApiSharp/Controllers/BaseController.cs @@ -103,20 +103,20 @@ public async Task> ExecuteRequestAsync(HttpRequ if (!string.IsNullOrEmpty(strResponse)) { var exceptionResponse = JsonConvert.DeserializeObject>(strResponse); - throw new ApiResponseException(httpResponseMessage, exceptionResponse); + if (exceptionResponse != null) throw new ApiResponseException(httpResponseMessage, exceptionResponse); } - throw new ApiResponseException(httpResponseMessage, "Response Status Code is: " + httpResponseMessage.StatusCode); + throw new ApiResponseException(httpResponseMessage, $"Response Status Code is: {httpResponseMessage.StatusCode} ({httpResponseMessage.ReasonPhrase})"); } var response = JsonConvert.DeserializeObject(strResponse, Constants.IgnoreDefaultValues); - if (response != null) ApplyObjectBaseTCAClient(response, true); + if (response != null) ApplyObjectBaseTcaClient(response, true); return new Tuple(response, httpResponseMessage);; } - public void ApplyObjectBaseTCAClient(object obj, bool recursive) + public void ApplyObjectBaseTcaClient(object obj, bool recursive) { var type = obj.GetType(); // if (type.IsSubclassOf(typeof(ITCAdminClientCompatible))) @@ -132,7 +132,7 @@ public void ApplyObjectBaseTCAClient(object obj, bool recursive) var value = type.GetProperty("Result")?.GetValue(obj); if (value != null) { - ApplyObjectBaseTCAClient(value, recursive); + ApplyObjectBaseTcaClient(value, recursive); } } @@ -141,7 +141,7 @@ public void ApplyObjectBaseTCAClient(object obj, bool recursive) var enumerable = (IEnumerable)obj; foreach (var o in enumerable) { - ApplyObjectBaseTCAClient(o, recursive); + ApplyObjectBaseTcaClient(o, recursive); } } } diff --git a/TCAdminApiSharp/Controllers/ServicesController.cs b/TCAdminApiSharp/Controllers/ServicesController.cs index b54cf39..6f65264 100644 --- a/TCAdminApiSharp/Controllers/ServicesController.cs +++ b/TCAdminApiSharp/Controllers/ServicesController.cs @@ -28,8 +28,7 @@ public async Task CreateService(ServiceBuilder builder) public async Task> FindServices(QueryableInfo query) { - var request = GenerateDefaultRequest("gameservices"); - request.Method = HttpMethod.Post;; + var request = GenerateDefaultRequest(HttpMethod.Post, "gameservices"); query.BuildQuery(request); var result = await ExecuteListResponseRequest(request); return result; diff --git a/TCAdminApiSharp/Controllers/UsersController.cs b/TCAdminApiSharp/Controllers/UsersController.cs index 48c90c6..40e6d2e 100644 --- a/TCAdminApiSharp/Controllers/UsersController.cs +++ b/TCAdminApiSharp/Controllers/UsersController.cs @@ -28,10 +28,9 @@ public async Task GetMe() public async Task> FindUsers(QueryableInfo query) { - var request = GenerateDefaultRequest("users", TcaClient.GetTokenUserId().ToString()); - // Logger.Debug(query.BuildQuery(request)); + var tokenUserId = await TcaClient.GetTokenUserId(); + var request = GenerateDefaultRequest(HttpMethod.Post, "myusers", tokenUserId.ToString()); request.Method = HttpMethod.Post; - // request.AddParameter("queryInfo", query.BuildQuery(request), ParameterType.GetOrPost); query.BuildQuery(request); return await ExecuteListResponseRequest(request); } diff --git a/TCAdminApiSharp/Entities/Service/EServiceStatus.cs b/TCAdminApiSharp/Entities/Service/EServiceStatus.cs new file mode 100644 index 0000000..be0f05c --- /dev/null +++ b/TCAdminApiSharp/Entities/Service/EServiceStatus.cs @@ -0,0 +1,16 @@ +namespace TCAdminApiSharp.Entities.Service; + +public enum EServiceStatus +{ + Processing = -3, // 0xFFFFFFFD + StartError = -2, // 0xFFFFFFFE + Unknown = -1, // 0xFFFFFFFF + Disabled = 0, + Stopped = 1, + Starting = 2, + Stopping = 3, + Running = 4, + Resuming = 5, + Pausing = 6, + Paused = 7 +} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/Player.cs b/TCAdminApiSharp/Entities/Service/Player.cs new file mode 100644 index 0000000..6a4b8e8 --- /dev/null +++ b/TCAdminApiSharp/Entities/Service/Player.cs @@ -0,0 +1,12 @@ +using Newtonsoft.Json; + +namespace TCAdminApiSharp.Entities.Service; + +public class Player +{ + [JsonProperty("Name", NullValueHandling = NullValueHandling.Ignore)] + public string Name { get; set; } + + [JsonProperty("Ping", NullValueHandling = NullValueHandling.Ignore)] + public int Ping { get; set; } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/Service.cs b/TCAdminApiSharp/Entities/Service/Service.cs index 42092f4..aad74f7 100644 --- a/TCAdminApiSharp/Entities/Service/Service.cs +++ b/TCAdminApiSharp/Entities/Service/Service.cs @@ -90,7 +90,7 @@ public class Service : ObjectBase, IObjectBaseCrud, IPowerable [JsonProperty("CurrentName")] public string CurrentName { get; set; } - [JsonProperty("ServiceStatus")] public ServiceStatus ServiceStatus { get; set; } + [JsonProperty("ServiceStatus")] public EServiceStatus EServiceStatus { get; set; } [JsonProperty("StartTime")] public DateTime StartTime { get; set; } @@ -228,7 +228,7 @@ public class Service : ObjectBase, IObjectBaseCrud, IPowerable [JsonProperty("GameKey")] public string GameKey { get; set; } - [JsonProperty("Variables")] public TcaXmlField Variables { get; set; } + [JsonProperty("Variables")] public TcaXmlField Variables { get; set; } = new(); [JsonProperty("InstalledMods")] public IList InstalledMods { get; set; } @@ -239,15 +239,7 @@ public class Service : ObjectBase, IObjectBaseCrud, IPowerable [JsonProperty("Notes")] public string Notes { get; set; } [JsonIgnore] public FileManagerService FileManagerService => new(this); - - // [JsonIgnore] - // public User.User User => Controller.TcaClient.UsersController.GetUser(UserId).ConfigureAwait(false).GetAwaiter() - // .GetResult(); - // - // [JsonIgnore] - // public Server.Server Server => - // Controller.TcaClient.ServersController.GetServer(ServerId).ConfigureAwait(false).GetAwaiter().GetResult(); - + public async Task Update(Action action) { var service = new Service(); @@ -321,4 +313,16 @@ public async Task Unsuspend() request.Method = HttpMethod.Post; return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Success; } + + public async Task GetStatus() + { + var request = TcaClient.ServicesController.GenerateDefaultRequest( ServiceId.ToString(), "Status"); + return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Result; + } + + public async Task GetQuery() + { + var request = TcaClient.ServicesController.GenerateDefaultRequest( ServiceId.ToString(), "Query"); + return (await TcaClient.ServicesController.ExecuteBaseResponseRequest(request)).Result; + } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/ServiceQuery.cs b/TCAdminApiSharp/Entities/Service/ServiceQuery.cs new file mode 100644 index 0000000..ff5f208 --- /dev/null +++ b/TCAdminApiSharp/Entities/Service/ServiceQuery.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using Newtonsoft.Json; +using TCAdminApiSharp.Entities.Generic; + +namespace TCAdminApiSharp.Entities.Service; + +public class ServiceQuery +{ + [JsonProperty("Running")] + public bool Running { get; set; } + + [JsonProperty("Name")] + public string Name { get; set; } + + [JsonProperty("Map")] + public string Map { get; set; } + + [JsonProperty("Game")] + public string Game { get; set; } + + [JsonProperty("GameType")] + public string GameType { get; set; } + + [JsonProperty("MaxPlayers")] + public long MaxPlayers { get; set; } + + [JsonProperty("NumPlayers")] + public long NumPlayers { get; set; } + + [JsonProperty("MaxSpectators")] + public long MaxSpectators { get; set; } + + [JsonProperty("NumSpectators")] + public long NumSpectators { get; set; } + + [JsonProperty("Players", NullValueHandling = NullValueHandling.Ignore)] + public List Players { get; set; } + + [JsonProperty("Rules", NullValueHandling = NullValueHandling.Ignore)] + public TcaXmlField Rules { get; set; } +} \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/ServiceStatus.cs b/TCAdminApiSharp/Entities/Service/ServiceStatus.cs index 69030ff..6ed0e1c 100644 --- a/TCAdminApiSharp/Entities/Service/ServiceStatus.cs +++ b/TCAdminApiSharp/Entities/Service/ServiceStatus.cs @@ -1,16 +1,31 @@ -namespace TCAdminApiSharp.Entities.Service; +using System; +using Newtonsoft.Json; -public enum ServiceStatus +namespace TCAdminApiSharp.Entities.Service; + +public class ServiceStatus { - Processing = -3, // 0xFFFFFFFD - StartError = -2, // 0xFFFFFFFE - Unknown = -1, // 0xFFFFFFFF - Disabled = 0, - Stopped = 1, - Starting = 2, - Stopping = 3, - Running = 4, - Resuming = 5, - Pausing = 6, - Paused = 7 + [JsonProperty("StartTime")] + public DateTimeOffset StartTime { get; set; } + + [JsonProperty("ServiceStatus")] + public EServiceStatus Status { get; set; } + + [JsonProperty("ProcessId")] + public long ProcessId { get; set; } + + [JsonProperty("ServiceId")] + public long ServiceId { get; set; } + + [JsonProperty("BandwidthLastSecond")] + public long BandwidthLastSecond { get; set; } + + [JsonProperty("CpuLastSecond")] + public double CpuLastSecond { get; set; } + + [JsonProperty("MemoryLastSecond")] + public long MemoryLastSecond { get; set; } + + [JsonProperty("MemoryPercentageLastSecond")] + public double MemoryPercentageLastSecond { get; set; } } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/User/User.cs b/TCAdminApiSharp/Entities/User/User.cs index a232753..0e02450 100644 --- a/TCAdminApiSharp/Entities/User/User.cs +++ b/TCAdminApiSharp/Entities/User/User.cs @@ -88,7 +88,7 @@ public class User : ObjectBase, IObjectBaseCrud public async Task SetPassword(string password) { - var request = TcaClient.UsersController.GenerateDefaultRequest(nameof(SetPassword), UserId.ToString()); + var request = TcaClient.UsersController.GenerateDefaultRequest(UserId.ToString(), nameof(SetPassword)); request.Method = HttpMethod.Post; request.Content = new FormUrlEncodedContent(new[] { new KeyValuePair(nameof(password), password) }); @@ -113,24 +113,22 @@ public Task Delete() public async Task Suspend(bool recursive = true, bool suspendServices = true) { - var request = TcaClient.UsersController.GenerateDefaultRequest(nameof(Suspend), UserId.ToString()); - request.Method = HttpMethod.Post; - request.Content = new FormUrlEncodedContent(new[] + var request = TcaClient.UsersController.GenerateDefaultRequest(HttpMethod.Post, UserId.ToString(), nameof(Suspend)); + request.Content = new FormUrlEncodedContent(new KeyValuePair[] { - new KeyValuePair(nameof(recursive), recursive.ToString()), - new KeyValuePair(nameof(suspendServices), suspendServices.ToString()) + new(nameof(recursive), recursive.ToString()), + new(nameof(suspendServices), suspendServices.ToString()) }); return (await TcaClient.UsersController.ExecuteBaseResponseRequest(request)).Success; } public async Task Unsuspend(bool recursive = true, bool enableServices = true) { - var request = TcaClient.UsersController.GenerateDefaultRequest(nameof(Unsuspend), UserId.ToString()); - request.Method = HttpMethod.Post; - request.Content = new FormUrlEncodedContent(new[] + var request = TcaClient.UsersController.GenerateDefaultRequest(HttpMethod.Post, UserId.ToString(), nameof(Unsuspend)); + request.Content = new FormUrlEncodedContent(new KeyValuePair[] { - new KeyValuePair(nameof(recursive), recursive.ToString()), - new KeyValuePair(nameof(enableServices), enableServices.ToString()) + new(nameof(recursive), recursive.ToString()), + new(nameof(enableServices), enableServices.ToString()) }); return (await TcaClient.UsersController.ExecuteBaseResponseRequest(request)).Success; } diff --git a/TCAdminApiSharp/Querying/Operations/WhereList.cs b/TCAdminApiSharp/Querying/Operations/WhereList.cs index 9e1e9fb..33f09e9 100644 --- a/TCAdminApiSharp/Querying/Operations/WhereList.cs +++ b/TCAdminApiSharp/Querying/Operations/WhereList.cs @@ -91,8 +91,9 @@ public void ModifyRequest(HttpRequestMessage request) } jObject[JsonKey] = GenerateQuery(); + var addQueryString = QueryHelpers.AddQueryString(request.RequestUri.ToString(), "queryInfo", jObject.ToString()); request.RequestUri = - new Uri(QueryHelpers.AddQueryString(request.RequestUri.ToString(), "queryInfo", jObject.ToString())); + new Uri(addQueryString, UriKind.RelativeOrAbsolute); } public static string ConvertColumnOperator(ColumnOperator columnOperator) diff --git a/TCAdminApiSharp/TCAdminApiSharp.csproj b/TCAdminApiSharp/TCAdminApiSharp.csproj index c6300a5..a223473 100644 --- a/TCAdminApiSharp/TCAdminApiSharp.csproj +++ b/TCAdminApiSharp/TCAdminApiSharp.csproj @@ -7,13 +7,17 @@ Alex Redding A C# Wrapper for the TCAdmin REST API. https://github.com/TotalControlAdmin/TCAdminApiSharp - https://opensource.org/licenses/MIT - https://avatars3.githubusercontent.com/u/67070230?s=200&v=4 + TC_LOGO_SMALL.png https://github.com/TotalControlAdmin/TCAdminApiSharp TCAdmin, Wrapper, Rest, Api 2.0.0 - 2.0.0 - 1.0.2 + $(AssemblyVersion) + + + + $(AssemblyVersion) + $(VersionPrefix)-$(VersionSuffix)-$(BuildNumber) + $(VersionPrefix) @@ -23,4 +27,8 @@ + + + + diff --git a/TCAdminApiSharp/TcaClient.cs b/TCAdminApiSharp/TcaClient.cs index 0f0aa56..ef09b89 100644 --- a/TCAdminApiSharp/TcaClient.cs +++ b/TCAdminApiSharp/TcaClient.cs @@ -1,5 +1,6 @@ using System; using System.Net.Http; +using System.Threading.Tasks; using Serilog; using Serilog.Events; using TCAdminApiSharp.Controllers; @@ -17,6 +18,7 @@ public class TcaClient : IDisposable public readonly TasksController TasksController; public readonly TcaClientSettings Settings; internal readonly HttpClient HttpClient; + private int? _myUserId; public TcaClient(string host, string apiKey, TcaClientSettings? clientSettings = null) { @@ -40,9 +42,15 @@ public TcaClient(string host, string apiKey, TcaClientSettings? clientSettings = TasksController = new TasksController(this); } - internal int GetTokenUserId() + internal async Task GetTokenUserId() { - return int.Parse(_apiKey.Split('#')[0]); + if (_myUserId == null) + { + var me = await UsersController.GetMe(); + _myUserId = me.UserId; + } + + return _myUserId.Value; } private static void SetupDefaultLogger(LogEventLevel logEventLevel) @@ -56,5 +64,6 @@ private static void SetupDefaultLogger(LogEventLevel logEventLevel) public void Dispose() { HttpClient.Dispose(); + GC.SuppressFinalize(this); } } \ No newline at end of file From 66fa58d0fef01e400b9ec66727afd177e24c13dc Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Thu, 7 Jul 2022 01:15:28 +0100 Subject: [PATCH 30/31] Include image --- TCAdminApiSharp/TC_LOGO_SMALL.png | Bin 0 -> 24628 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 TCAdminApiSharp/TC_LOGO_SMALL.png diff --git a/TCAdminApiSharp/TC_LOGO_SMALL.png b/TCAdminApiSharp/TC_LOGO_SMALL.png new file mode 100644 index 0000000000000000000000000000000000000000..b391e3cc789cb860a9d7bf9b6a2615312fcfcba0 GIT binary patch literal 24628 zcmbSTRaaYGw=PoL-J!U9@#5}QB)GdfMT>j!;!p@4Jh;0Bio08JcUr!@7v~S0i=Ca^ zWQ;lXTF-oBt{tPUDu<3jg7V?R2XqB_X-(+8_`eGY0s499SQ7%hA-l@!dwlqSG5FsF zlg@%c`r!lB2L)*fZQs?iE}I{gOI}CM9gkUerJcto_HhWmZHf9*sF1!F@>9#W)7qD$ zliJaHi>Wy>np^n5uK(Of$ctI#=)lIsMiOhXIFbWO5q9`XpSwg|;9L z7oY`@)WPU7rNhgHDwv9Ni=pjH(-Mo7!70MQQ}4o{1GS0u;1;DV6_~up%V8+CW1?pO zIiv{D$a!)e{MpmLS_yw5G$0{pBM;Gqmmw`|&D?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M5|-n|HK*J^ky!uo{k$LL}PWEMBg0@@WhTd;y$ObdZNI@pB;O4($1#0z?=JP q@9fFthviay!Q%h#^YJ1SbG1;b@}9J+1pONTjCV>}iq-NK5&s9yHeGiB literal 0 HcmV?d00001 From 97834b87872eab8f60206f2f547fe19f852b9029 Mon Sep 17 00:00:00 2001 From: Alex Redding Date: Thu, 7 Jul 2022 01:39:00 +0100 Subject: [PATCH 31/31] Implement file manager delete --- .../Entities/Service/FileManager/DirectoryListing.cs | 1 + TCAdminApiSharp/Entities/Service/FileManager/FileInfo.cs | 1 + .../Entities/Service/FileManager/FileManagerService.cs | 9 +++++++++ 3 files changed, 11 insertions(+) diff --git a/TCAdminApiSharp/Entities/Service/FileManager/DirectoryListing.cs b/TCAdminApiSharp/Entities/Service/FileManager/DirectoryListing.cs index 7fef326..6893175 100644 --- a/TCAdminApiSharp/Entities/Service/FileManager/DirectoryListing.cs +++ b/TCAdminApiSharp/Entities/Service/FileManager/DirectoryListing.cs @@ -44,4 +44,5 @@ public class DirectoryListing public System.Threading.Tasks.Task Move(string target, bool overwrite = true) => FileManagerService.Move(new []{this.Path}, target, overwrite); public System.Threading.Tasks.Task Copy(string target, bool overwrite = true) => FileManagerService.Copy(new []{this.Path}, target, overwrite); public System.Threading.Tasks.Task Compress(string target) => FileManagerService.Compress(new []{this.Path}, target); + public System.Threading.Tasks.Task Delete() => FileManagerService.Delete(this.Path); } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/FileManager/FileInfo.cs b/TCAdminApiSharp/Entities/Service/FileManager/FileInfo.cs index fe3e7c0..17dacf0 100644 --- a/TCAdminApiSharp/Entities/Service/FileManager/FileInfo.cs +++ b/TCAdminApiSharp/Entities/Service/FileManager/FileInfo.cs @@ -58,4 +58,5 @@ public class FileInfo public System.Threading.Tasks.Task Copy(string target, bool overwrite = true) => FileManagerService.Copy(new []{this.FullName}, target, overwrite); public System.Threading.Tasks.Task Compress(string target) => FileManagerService.Compress(new []{this.FullName}, target); public System.Threading.Tasks.Task Extract(string target) => FileManagerService.Extract(this.FullName, target); + public System.Threading.Tasks.Task Delete() => FileManagerService.Delete(this.FullName); } \ No newline at end of file diff --git a/TCAdminApiSharp/Entities/Service/FileManager/FileManagerService.cs b/TCAdminApiSharp/Entities/Service/FileManager/FileManagerService.cs index 3542088..9514c1c 100644 --- a/TCAdminApiSharp/Entities/Service/FileManager/FileManagerService.cs +++ b/TCAdminApiSharp/Entities/Service/FileManager/FileManagerService.cs @@ -133,4 +133,13 @@ public async System.Threading.Tasks.Task Extract(string file, string extra var executeBaseResponseRequest = await TcaClient.ServicesController.ExecuteBaseResponseRequest(request); return executeBaseResponseRequest.Success; } + + public async System.Threading.Tasks.Task Delete(string path) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + var endpoint = QueryHelpers.AddQueryString(FileManagerEndpoint, nameof(path), path); + var request = TcaClient.ServicesController.GenerateDefaultRequest(HttpMethod.Post, endpoint); + var executeBaseResponseRequest = await TcaClient.ServicesController.ExecuteBaseResponseRequest(request); + return executeBaseResponseRequest.Success; + } } \ No newline at end of file