* Start working on nullable checks

help me

* Update GlobalConfig.cs

* Finish initial fixup round

* nullability code review
This commit is contained in:
Łukasz Domeradzki
2020-08-22 21:41:01 +02:00
committed by GitHub
parent e5f64ec9dd
commit 9fc1ea65a5
91 changed files with 1996 additions and 2808 deletions

View File

@@ -39,6 +39,10 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[HttpGet]
[ProducesResponseType(typeof(GenericResponse<ASFResponse>), (int) HttpStatusCode.OK)]
public ActionResult<GenericResponse<ASFResponse>> ASFGet() {
if (ASF.GlobalConfig == null) {
throw new ArgumentNullException(nameof(ASF.GlobalConfig));
}
uint memoryUsage = (uint) GC.GetTotalMemory(false) / 1024;
ASFResponse result = new ASFResponse(SharedInfo.BuildInfo.Variant, ASF.GlobalConfig, memoryUsage, RuntimeCompatibility.ProcessStartTime, SharedInfo.Version);
@@ -54,13 +58,15 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> ASFPost([FromBody] ASFRequest request) {
if (request == null) {
ASF.ArchiLogger.LogNullError(nameof(request));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(request))));
if ((request == null) || (ASF.GlobalConfig == null)) {
throw new ArgumentNullException(nameof(request) + " || " + nameof(ASF.GlobalConfig));
}
(bool valid, string errorMessage) = request.GlobalConfig.CheckValidation();
if (request.GlobalConfig == null) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(request.GlobalConfig))));
}
(bool valid, string? errorMessage) = request.GlobalConfig.CheckValidation();
if (!valid) {
return BadRequest(new GenericResponse(false, errorMessage));
@@ -125,13 +131,13 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[HttpPost("Update")]
[ProducesResponseType(typeof(GenericResponse<string>), (int) HttpStatusCode.OK)]
public async Task<ActionResult<GenericResponse<string>>> UpdatePost() {
(bool success, string message, Version version) = await Actions.Update().ConfigureAwait(false);
(bool success, string? message, Version? version) = await Actions.Update().ConfigureAwait(false);
if (string.IsNullOrEmpty(message)) {
message = success ? Strings.Success : Strings.WarningFailed;
}
return Ok(new GenericResponse<string>(success, message, version?.ToString()));
return Ok(new GenericResponse<string>(success, message!, version?.ToString()));
}
}
}

View File

@@ -42,12 +42,10 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> BotDelete(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
ASF.ArchiLogger.LogNullError(nameof(botNames));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames))));
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
@@ -66,18 +64,16 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public ActionResult<GenericResponse> BotGet(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
ASF.ArchiLogger.LogNullError(nameof(botNames));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames))));
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if (bots == null) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, nameof(bots))));
}
return Ok(new GenericResponse<IReadOnlyDictionary<string, Bot>>(bots.ToDictionary(bot => bot.BotName, bot => bot, Bot.BotsComparer)));
return Ok(new GenericResponse<IReadOnlyDictionary<string, Bot>>(bots.Where(bot => !string.IsNullOrEmpty(bot.BotName)).ToDictionary(bot => bot.BotName, bot => bot, Bot.BotsComparer)!));
}
/// <summary>
@@ -88,13 +84,15 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse<IReadOnlyDictionary<string, bool>>), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> BotPost(string botNames, [FromBody] BotRequest request) {
if (string.IsNullOrEmpty(botNames) || (request == null)) {
ASF.ArchiLogger.LogNullError(nameof(botNames) + " || " + nameof(request));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames) + " || " + nameof(request))));
if (string.IsNullOrEmpty(botNames) || (request == null) || (Bot.Bots == null)) {
throw new ArgumentNullException(nameof(botNames) + " || " + nameof(request) + " || " + nameof(Bot.Bots));
}
(bool valid, string errorMessage) = request.BotConfig.CheckValidation();
if (request.BotConfig == null) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(request.BotConfig))));
}
(bool valid, string? errorMessage) = request.BotConfig.CheckValidation();
if (!valid) {
return BadRequest(new GenericResponse(false, errorMessage));
@@ -109,7 +107,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
Dictionary<string, bool> result = new Dictionary<string, bool>(bots.Count, Bot.BotsComparer);
foreach (string botName in bots) {
if (Bot.Bots.TryGetValue(botName, out Bot bot)) {
if (Bot.Bots.TryGetValue(botName, out Bot? bot)) {
if (!request.BotConfig.IsSteamLoginSet && bot.BotConfig.IsSteamLoginSet) {
request.BotConfig.SteamLogin = bot.BotConfig.SteamLogin;
}
@@ -155,12 +153,10 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> GamesToRedeemInBackgroundDelete(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
ASF.ArchiLogger.LogNullError(nameof(botNames));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames))));
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
@@ -179,23 +175,21 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> GamesToRedeemInBackgroundGet(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
ASF.ArchiLogger.LogNullError(nameof(botNames));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames))));
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
}
IList<(Dictionary<string, string> UnusedKeys, Dictionary<string, string> UsedKeys)> results = await Utilities.InParallel(bots.Select(bot => bot.GetUsedAndUnusedKeys())).ConfigureAwait(false);
IList<(Dictionary<string, string>? UnusedKeys, Dictionary<string, string>? UsedKeys)> results = await Utilities.InParallel(bots.Select(bot => bot.GetUsedAndUnusedKeys())).ConfigureAwait(false);
Dictionary<string, GamesToRedeemInBackgroundResponse> result = new Dictionary<string, GamesToRedeemInBackgroundResponse>(bots.Count, Bot.BotsComparer);
foreach (Bot bot in bots) {
(Dictionary<string, string> unusedKeys, Dictionary<string, string> usedKeys) = results[result.Count];
(Dictionary<string, string>? unusedKeys, Dictionary<string, string>? usedKeys) = results[result.Count];
result[bot.BotName] = new GamesToRedeemInBackgroundResponse(unusedKeys, usedKeys);
}
@@ -211,16 +205,14 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> GamesToRedeemInBackgroundPost(string botNames, [FromBody] BotGamesToRedeemInBackgroundRequest request) {
if (string.IsNullOrEmpty(botNames) || (request == null)) {
ASF.ArchiLogger.LogNullError(nameof(botNames) + " || " + nameof(request));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames) + " || " + nameof(request))));
throw new ArgumentNullException(nameof(botNames) + " || " + nameof(request));
}
if (request.GamesToRedeemInBackground.Count == 0) {
if ((request.GamesToRedeemInBackground == null) || (request.GamesToRedeemInBackground.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(request.GamesToRedeemInBackground))));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
@@ -252,22 +244,20 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> InputPost(string botNames, [FromBody] BotInputRequest request) {
if (string.IsNullOrEmpty(botNames) || (request == null)) {
ASF.ArchiLogger.LogNullError(nameof(botNames) + " || " + nameof(request));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames) + " || " + nameof(request))));
throw new ArgumentNullException(nameof(botNames) + " || " + nameof(request));
}
if ((request.Type == ASF.EUserInputType.None) || !Enum.IsDefined(typeof(ASF.EUserInputType), request.Type) || string.IsNullOrEmpty(request.Value)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, nameof(request.Type) + " || " + nameof(request.Value))));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
}
IList<bool> results = await Utilities.InParallel(bots.Select(bot => Task.Run(() => bot.SetUserInput(request.Type, request.Value)))).ConfigureAwait(false);
IList<bool> results = await Utilities.InParallel(bots.Select(bot => Task.Run(() => bot.SetUserInput(request.Type, request.Value!)))).ConfigureAwait(false);
return Ok(results.All(result => result) ? new GenericResponse(true) : new GenericResponse(false, Strings.WarningFailed));
}
@@ -281,12 +271,10 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> PausePost(string botNames, [FromBody] BotPauseRequest request) {
if (string.IsNullOrEmpty(botNames) || (request == null)) {
ASF.ArchiLogger.LogNullError(nameof(botNames) + " || " + nameof(request));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames) + " || " + nameof(request))));
throw new ArgumentNullException(nameof(botNames) + " || " + nameof(request));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
@@ -310,29 +298,27 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> RedeemPost(string botNames, [FromBody] BotRedeemRequest request) {
if (string.IsNullOrEmpty(botNames) || (request == null)) {
ASF.ArchiLogger.LogNullError(nameof(botNames) + " || " + nameof(request));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames) + " || " + nameof(request))));
throw new ArgumentNullException(nameof(botNames) + " || " + nameof(request));
}
if (request.KeysToRedeem.Count == 0) {
if ((request.KeysToRedeem == null) || (request.KeysToRedeem.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(request.KeysToRedeem))));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
}
IList<ArchiHandler.PurchaseResponseCallback> results = await Utilities.InParallel(bots.Select(bot => request.KeysToRedeem.Select(key => bot.Actions.RedeemKey(key))).SelectMany(task => task)).ConfigureAwait(false);
IList<ArchiHandler.PurchaseResponseCallback?> results = await Utilities.InParallel(bots.Select(bot => request.KeysToRedeem.Select(key => bot.Actions.RedeemKey(key))).SelectMany(task => task)).ConfigureAwait(false);
Dictionary<string, IReadOnlyDictionary<string, ArchiHandler.PurchaseResponseCallback>> result = new Dictionary<string, IReadOnlyDictionary<string, ArchiHandler.PurchaseResponseCallback>>(bots.Count, Bot.BotsComparer);
Dictionary<string, IReadOnlyDictionary<string, ArchiHandler.PurchaseResponseCallback?>> result = new Dictionary<string, IReadOnlyDictionary<string, ArchiHandler.PurchaseResponseCallback?>>(bots.Count, Bot.BotsComparer);
int count = 0;
foreach (Bot bot in bots) {
Dictionary<string, ArchiHandler.PurchaseResponseCallback> responses = new Dictionary<string, ArchiHandler.PurchaseResponseCallback>(request.KeysToRedeem.Count, StringComparer.Ordinal);
Dictionary<string, ArchiHandler.PurchaseResponseCallback?> responses = new Dictionary<string, ArchiHandler.PurchaseResponseCallback?>(request.KeysToRedeem.Count, StringComparer.Ordinal);
result[bot.BotName] = responses;
foreach (string key in request.KeysToRedeem) {
@@ -340,7 +326,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
}
}
return Ok(new GenericResponse<IReadOnlyDictionary<string, IReadOnlyDictionary<string, ArchiHandler.PurchaseResponseCallback>>>(result.Values.SelectMany(responses => responses.Values).All(value => value != null), result));
return Ok(new GenericResponse<IReadOnlyDictionary<string, IReadOnlyDictionary<string, ArchiHandler.PurchaseResponseCallback?>>>(result.Values.SelectMany(responses => responses.Values).All(value => value != null), result));
}
/// <summary>
@@ -351,17 +337,15 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> RenamePost(string botName, [FromBody] BotRenameRequest request) {
if (string.IsNullOrEmpty(botName) || (request == null)) {
ASF.ArchiLogger.LogNullError(nameof(botName) + " || " + nameof(request));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botName) + " || " + nameof(request))));
if (string.IsNullOrEmpty(botName) || (request == null) || (Bot.Bots == null)) {
throw new ArgumentNullException(nameof(botName) + " || " + nameof(request) + " || " + nameof(Bot.Bots));
}
if (string.IsNullOrEmpty(request.NewName) || request.NewName.Equals(SharedInfo.ASF) || Bot.Bots.ContainsKey(request.NewName)) {
if (string.IsNullOrEmpty(request.NewName) || request.NewName!.Equals(SharedInfo.ASF) || Bot.Bots.ContainsKey(request.NewName)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, nameof(request.NewName))));
}
if (!Bot.Bots.TryGetValue(botName, out Bot bot)) {
if (!Bot.Bots.TryGetValue(botName, out Bot? bot)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botName)));
}
@@ -378,12 +362,10 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> ResumePost(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
ASF.ArchiLogger.LogNullError(nameof(botNames));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames))));
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
@@ -402,12 +384,10 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> StartPost(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
ASF.ArchiLogger.LogNullError(nameof(botNames));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames))));
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
@@ -426,12 +406,10 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> StopPost(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
ASF.ArchiLogger.LogNullError(nameof(botNames));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames))));
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.BotNotFound, botNames)));
@@ -450,16 +428,14 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> TwoFactorAuthenticationConfirmationsPost(string botNames, [FromBody] TwoFactorAuthenticationConfirmationsRequest request) {
if (string.IsNullOrEmpty(botNames) || (request == null)) {
ASF.ArchiLogger.LogNullError(nameof(botNames));
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse>>(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames) + " || " + nameof(request))));
throw new ArgumentNullException(nameof(botNames));
}
if (request.AcceptedType.HasValue && ((request.AcceptedType.Value == MobileAuthenticator.Confirmation.EType.Unknown) || !Enum.IsDefined(typeof(MobileAuthenticator.Confirmation.EType), request.AcceptedType.Value))) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, nameof(request.AcceptedType))));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse>>(false, string.Format(Strings.BotNotFound, botNames)));
@@ -485,23 +461,21 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> TwoFactorAuthenticationTokenGet(string botNames) {
if (string.IsNullOrEmpty(botNames)) {
ASF.ArchiLogger.LogNullError(nameof(botNames));
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames))));
throw new ArgumentNullException(nameof(botNames));
}
HashSet<Bot> bots = Bot.GetBots(botNames);
HashSet<Bot>? bots = Bot.GetBots(botNames);
if ((bots == null) || (bots.Count == 0)) {
return BadRequest(new GenericResponse<IReadOnlyDictionary<string, GenericResponse<string>>>(false, string.Format(Strings.BotNotFound, botNames)));
}
IList<(bool Success, string Token, string Message)> results = await Utilities.InParallel(bots.Select(bot => bot.Actions.GenerateTwoFactorAuthenticationToken())).ConfigureAwait(false);
IList<(bool Success, string? Token, string Message)> results = await Utilities.InParallel(bots.Select(bot => bot.Actions.GenerateTwoFactorAuthenticationToken())).ConfigureAwait(false);
Dictionary<string, GenericResponse<string>> result = new Dictionary<string, GenericResponse<string>>(bots.Count, Bot.BotsComparer);
foreach (Bot bot in bots) {
(bool success, string token, string message) = results[result.Count];
(bool success, string? token, string message) = results[result.Count];
result[bot.BotName] = new GenericResponse<string>(success, message, token);
}

View File

@@ -44,36 +44,37 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public async Task<ActionResult<GenericResponse>> CommandPost([FromBody] CommandRequest request) {
if (request == null) {
ASF.ArchiLogger.LogNullError(nameof(request));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(request))));
throw new ArgumentNullException(nameof(request));
}
if (string.IsNullOrEmpty(request.Command)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(request.Command))));
}
if (ASF.GlobalConfig.SteamOwnerID == 0) {
ulong steamOwnerID = ASF.GlobalConfig?.SteamOwnerID ?? GlobalConfig.DefaultSteamOwnerID;
if (steamOwnerID == 0) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, nameof(ASF.GlobalConfig.SteamOwnerID))));
}
Bot targetBot = Bot.Bots.OrderBy(bot => bot.Key, Bot.BotsComparer).Select(bot => bot.Value).FirstOrDefault();
Bot? targetBot = Bot.Bots.OrderBy(bot => bot.Key, Bot.BotsComparer).Select(bot => bot.Value).FirstOrDefault();
if (targetBot == null) {
return BadRequest(new GenericResponse(false, Strings.ErrorNoBotsDefined));
}
string command = request.Command;
string command = request.Command!;
string? commandPrefix = ASF.GlobalConfig?.CommandPrefix ?? GlobalConfig.DefaultCommandPrefix;
if (!string.IsNullOrEmpty(ASF.GlobalConfig.CommandPrefix) && command.StartsWith(ASF.GlobalConfig.CommandPrefix, StringComparison.Ordinal)) {
command = command.Substring(ASF.GlobalConfig.CommandPrefix.Length);
if (!string.IsNullOrEmpty(commandPrefix) && command.StartsWith(commandPrefix, StringComparison.Ordinal)) {
command = command.Substring(commandPrefix!.Length);
if (string.IsNullOrEmpty(command)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(command))));
}
}
string response = await targetBot.Commands.Response(ASF.GlobalConfig.SteamOwnerID, command).ConfigureAwait(false);
string? response = await targetBot.Commands.Response(steamOwnerID, command).ConfigureAwait(false);
return Ok(new GenericResponse<string>(response));
}

View File

@@ -19,6 +19,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
@@ -86,7 +87,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
break;
}
} finally {
if (ActiveLogWebSockets.TryRemove(webSocket, out SemaphoreSlim closedSemaphore)) {
if (ActiveLogWebSockets.TryRemove(webSocket, out SemaphoreSlim? closedSemaphore)) {
await closedSemaphore.WaitAsync().ConfigureAwait(false); // Ensure that our semaphore is truly closed by now
closedSemaphore.Dispose();
}
@@ -98,11 +99,9 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
return new EmptyResult();
}
internal static async void OnNewHistoryEntry(object sender, HistoryTarget.NewHistoryEntryArgs newHistoryEntryArgs) {
if ((sender == null) || (newHistoryEntryArgs == null)) {
ASF.ArchiLogger.LogNullError(nameof(sender) + " || " + nameof(newHistoryEntryArgs));
return;
internal static async void OnNewHistoryEntry(object? sender, HistoryTarget.NewHistoryEntryArgs newHistoryEntryArgs) {
if (newHistoryEntryArgs == null) {
throw new ArgumentNullException(nameof(newHistoryEntryArgs));
}
if (ActiveLogWebSockets.Count == 0) {
@@ -110,14 +109,13 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
}
string json = JsonConvert.SerializeObject(new GenericResponse<string>(newHistoryEntryArgs.Message));
await Task.WhenAll(ActiveLogWebSockets.Where(kv => kv.Key.State == WebSocketState.Open).Select(kv => PostLoggedJsonUpdate(kv.Key, kv.Value, json))).ConfigureAwait(false);
}
private static async Task PostLoggedJsonUpdate(WebSocket webSocket, SemaphoreSlim sendSemaphore, string json) {
if ((webSocket == null) || (sendSemaphore == null) || string.IsNullOrEmpty(json)) {
ASF.ArchiLogger.LogNullError(nameof(webSocket) + " || " + nameof(sendSemaphore) + " || " + nameof(json));
return;
throw new ArgumentNullException(nameof(webSocket) + " || " + nameof(sendSemaphore) + " || " + nameof(json));
}
if (webSocket.State != WebSocketState.Open) {
@@ -141,9 +139,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
private static async Task PostLoggedMessageUpdate(WebSocket webSocket, SemaphoreSlim sendSemaphore, string loggedMessage) {
if ((webSocket == null) || (sendSemaphore == null) || string.IsNullOrEmpty(loggedMessage)) {
ASF.ArchiLogger.LogNullError(nameof(webSocket) + " || " + nameof(sendSemaphore) + " || " + nameof(loggedMessage));
return;
throw new ArgumentNullException(nameof(webSocket) + " || " + nameof(sendSemaphore) + " || " + nameof(loggedMessage));
}
if (webSocket.State != WebSocketState.Open) {
@@ -151,6 +147,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
}
string response = JsonConvert.SerializeObject(new GenericResponse<string>(loggedMessage));
await PostLoggedJsonUpdate(webSocket, sendSemaphore, response).ConfigureAwait(false);
}
}

View File

@@ -39,18 +39,16 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public ActionResult<GenericResponse> StructureGet(string structure) {
if (string.IsNullOrEmpty(structure)) {
ASF.ArchiLogger.LogNullError(nameof(structure));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(structure))));
throw new ArgumentNullException(nameof(structure));
}
Type targetType = WebUtilities.ParseType(structure);
Type? targetType = WebUtilities.ParseType(structure);
if (targetType == null) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, structure)));
}
object obj;
object? obj;
try {
obj = Activator.CreateInstance(targetType, true);

View File

@@ -43,45 +43,55 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
public ActionResult<GenericResponse> TypeGet(string type) {
if (string.IsNullOrEmpty(type)) {
ASF.ArchiLogger.LogNullError(nameof(type));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(type))));
throw new ArgumentNullException(nameof(type));
}
Type targetType = WebUtilities.ParseType(type);
Type? targetType = WebUtilities.ParseType(type);
if (targetType == null) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, type)));
}
string baseType = targetType.BaseType?.GetUnifiedName();
HashSet<string> customAttributes = targetType.CustomAttributes.Select(attribute => attribute.AttributeType.GetUnifiedName()).ToHashSet(StringComparer.Ordinal);
string underlyingType = null;
string? baseType = targetType.BaseType?.GetUnifiedName();
HashSet<string> customAttributes = targetType.CustomAttributes.Select(attribute => attribute.AttributeType.GetUnifiedName()).Where(customAttribute => !string.IsNullOrEmpty(customAttribute)).ToHashSet(StringComparer.Ordinal)!;
string? underlyingType = null;
Dictionary<string, string> body = new Dictionary<string, string>(StringComparer.Ordinal);
if (targetType.IsClass) {
foreach (FieldInfo field in targetType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where(field => !field.IsPrivate)) {
JsonPropertyAttribute jsonProperty = field.GetCustomAttribute<JsonPropertyAttribute>();
JsonPropertyAttribute? jsonProperty = field.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null) {
body[jsonProperty.PropertyName ?? field.Name] = field.FieldType.GetUnifiedName();
string? unifiedName = field.FieldType.GetUnifiedName();
if (!string.IsNullOrEmpty(unifiedName)) {
body[jsonProperty.PropertyName ?? field.Name] = unifiedName!;
}
}
}
foreach (PropertyInfo property in targetType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where(property => property.CanRead && (property.GetMethod?.IsPrivate == false))) {
JsonPropertyAttribute jsonProperty = property.GetCustomAttribute<JsonPropertyAttribute>();
JsonPropertyAttribute? jsonProperty = property.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null) {
body[jsonProperty.PropertyName ?? property.Name] = property.PropertyType.GetUnifiedName();
string? unifiedName = property.PropertyType.GetUnifiedName();
if (!string.IsNullOrEmpty(unifiedName)) {
body[jsonProperty.PropertyName ?? property.Name] = unifiedName!;
}
}
}
} else if (targetType.IsEnum) {
Type enumType = Enum.GetUnderlyingType(targetType);
underlyingType = enumType.GetUnifiedName();
foreach (object value in Enum.GetValues(targetType)) {
string valueText = value.ToString();
foreach (object? value in Enum.GetValues(targetType)) {
if (value == null) {
continue;
}
string? valueText = value.ToString();
if (string.IsNullOrEmpty(valueText)) {
ASF.ArchiLogger.LogNullError(nameof(valueText));
@@ -89,7 +99,13 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorObjectIsNull, nameof(valueText))));
}
body[valueText] = Convert.ChangeType(value, enumType).ToString();
string? valueObjText = Convert.ChangeType(value, enumType)?.ToString();
if (string.IsNullOrEmpty(valueObjText)) {
continue;
}
body[valueText] = valueObjText!;
}
}

View File

@@ -45,9 +45,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.InternalServerError)]
public ActionResult<GenericResponse> DirectoryGet(string directory) {
if (string.IsNullOrEmpty(directory)) {
ASF.ArchiLogger.LogNullError(nameof(directory));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(directory))));
throw new ArgumentNullException(directory);
}
string directoryPath = Path.Combine(ArchiKestrel.WebsiteDirectory, directory);
@@ -64,7 +62,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
return StatusCode((int) HttpStatusCode.InternalServerError, new GenericResponse(false, string.Format(Strings.ErrorParsingObject, nameof(files)) + Environment.NewLine + e));
}
HashSet<string> result = files.Select(Path.GetFileName).ToHashSet();
HashSet<string> result = files.Select(Path.GetFileName).Where(fileName => !string.IsNullOrEmpty(fileName)).ToHashSet()!;
return Ok(new GenericResponse<IReadOnlyCollection<string>>(result));
}
@@ -79,7 +77,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse<GitHubReleaseResponse>), (int) HttpStatusCode.OK)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.ServiceUnavailable)]
public async Task<ActionResult<GenericResponse>> GitHubReleaseGet() {
GitHub.ReleaseResponse releaseResponse = await GitHub.GetLatestRelease(false).ConfigureAwait(false);
GitHub.ReleaseResponse? releaseResponse = await GitHub.GetLatestRelease(false).ConfigureAwait(false);
return releaseResponse != null ? Ok(new GenericResponse<GitHubReleaseResponse>(new GitHubReleaseResponse(releaseResponse))) : StatusCode((int) HttpStatusCode.ServiceUnavailable, new GenericResponse(false, string.Format(Strings.ErrorRequestFailedTooManyTimes, WebBrowser.MaxTries)));
}
@@ -96,10 +94,25 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.ServiceUnavailable)]
public async Task<ActionResult<GenericResponse>> GitHubReleaseGet(string version) {
if (string.IsNullOrEmpty(version)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(version))));
throw new ArgumentNullException(nameof(version));
}
GitHub.ReleaseResponse releaseResponse = version.Equals("latest", StringComparison.OrdinalIgnoreCase) ? await GitHub.GetLatestRelease().ConfigureAwait(false) : await GitHub.GetRelease(version).ConfigureAwait(false);
GitHub.ReleaseResponse? releaseResponse;
switch (version.ToUpperInvariant()) {
case "LATEST":
releaseResponse = await GitHub.GetLatestRelease().ConfigureAwait(false);
break;
default:
if (!Version.TryParse(version, out Version? parsedVersion)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, nameof(version))));
}
releaseResponse = await GitHub.GetRelease(parsedVersion.ToString(4)).ConfigureAwait(false);
break;
}
return releaseResponse != null ? Ok(new GenericResponse<GitHubReleaseResponse>(new GitHubReleaseResponse(releaseResponse))) : StatusCode((int) HttpStatusCode.ServiceUnavailable, new GenericResponse(false, string.Format(Strings.ErrorRequestFailedTooManyTimes, WebBrowser.MaxTries)));
}
@@ -116,17 +129,15 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.ServiceUnavailable)]
public async Task<ActionResult<GenericResponse>> SendPost([FromBody] WWWSendRequest request) {
if (request == null) {
ASF.ArchiLogger.LogNullError(nameof(request));
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(request))));
if ((request == null) || (ASF.WebBrowser == null)) {
throw new ArgumentNullException(nameof(request) + " || " + nameof(ASF.WebBrowser));
}
if (string.IsNullOrEmpty(request.URL) || !Uri.TryCreate(request.URL, UriKind.Absolute, out Uri uri) || !uri.Scheme.Equals(Uri.UriSchemeHttps)) {
if (string.IsNullOrEmpty(request.URL) || !Uri.TryCreate(request.URL, UriKind.Absolute, out Uri? uri) || !uri.Scheme.Equals(Uri.UriSchemeHttps)) {
return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, nameof(request.URL))));
}
WebBrowser.StringResponse urlResponse = await ASF.WebBrowser.UrlGetToString(request.URL).ConfigureAwait(false);
WebBrowser.StringResponse? urlResponse = await ASF.WebBrowser.UrlGetToString(request.URL!).ConfigureAwait(false);
return urlResponse?.Content != null ? Ok(new GenericResponse<string>(urlResponse.Content)) : StatusCode((int) HttpStatusCode.ServiceUnavailable, new GenericResponse(false, string.Format(Strings.ErrorRequestFailedTooManyTimes, WebBrowser.MaxTries)));
}