From 4b4b323164cf883ec3fd234d997fe5be8207e2ee Mon Sep 17 00:00:00 2001 From: JustArchi Date: Sat, 18 Apr 2020 16:54:57 +0200 Subject: [PATCH] R# code improvements --- ArchiSteamFarm/ArchiHandler.cs | 66 ++----------------- ArchiSteamFarm/ArchiWebHandler.cs | 14 +++- ArchiSteamFarm/Bot.cs | 26 +++++--- ArchiSteamFarm/CardsFarmer.cs | 4 +- ArchiSteamFarm/Commands.cs | 6 -- .../IPC/Controllers/Api/ASFController.cs | 4 +- .../IPC/Controllers/Api/BotController.cs | 4 +- .../IPC/Controllers/Api/TypeController.cs | 12 +++- .../ApiAuthenticationMiddleware.cs | 14 ++-- ArchiSteamFarm/RuntimeCompatibility.cs | 7 ++ 10 files changed, 60 insertions(+), 97 deletions(-) diff --git a/ArchiSteamFarm/ArchiHandler.cs b/ArchiSteamFarm/ArchiHandler.cs index e9add55f2..6f20cc88a 100644 --- a/ArchiSteamFarm/ArchiHandler.cs +++ b/ArchiSteamFarm/ArchiHandler.cs @@ -67,6 +67,12 @@ namespace ArchiSteamFarm { return; } + if (Client == null) { + ASF.ArchiLogger.LogNullError(nameof(Client)); + + return; + } + LastPacketReceived = DateTime.UtcNow; switch (packetMsg.MsgType) { @@ -196,12 +202,6 @@ namespace ArchiSteamFarm { return false; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return false; - } - return response.Result == EResult.OK; } @@ -231,12 +231,6 @@ namespace ArchiSteamFarm { return 0; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return 0; - } - if (response.Result != EResult.OK) { return 0; } @@ -262,12 +256,6 @@ namespace ArchiSteamFarm { return null; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return null; - } - if (response.Result != EResult.OK) { return null; } @@ -294,12 +282,6 @@ namespace ArchiSteamFarm { return null; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return null; - } - if (response.Result != EResult.OK) { return null; } @@ -326,12 +308,6 @@ namespace ArchiSteamFarm { return null; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return null; - } - if (response.Result != EResult.OK) { return null; } @@ -364,12 +340,6 @@ namespace ArchiSteamFarm { return false; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return false; - } - return response.Result == EResult.OK; } @@ -500,12 +470,6 @@ namespace ArchiSteamFarm { return false; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return false; - } - return response.Result == EResult.OK; } @@ -546,12 +510,6 @@ namespace ArchiSteamFarm { return EResult.Timeout; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return EResult.Fail; - } - return response.Result; } @@ -582,12 +540,6 @@ namespace ArchiSteamFarm { return EResult.Timeout; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return EResult.Fail; - } - return response.Result; } @@ -617,12 +569,6 @@ namespace ArchiSteamFarm { return EResult.Timeout; } - if (response == null) { - ArchiLogger.LogNullError(nameof(response)); - - return EResult.Fail; - } - return response.Result; } diff --git a/ArchiSteamFarm/ArchiWebHandler.cs b/ArchiSteamFarm/ArchiWebHandler.cs index a40a747e7..819b8d367 100644 --- a/ArchiSteamFarm/ArchiWebHandler.cs +++ b/ArchiSteamFarm/ArchiWebHandler.cs @@ -1595,7 +1595,7 @@ namespace ArchiSteamFarm { List apps = response["apps"].Children; - if ((apps == null) || (apps.Count == 0)) { + if (apps.Count == 0) { Bot.ArchiLogger.LogNullError(nameof(apps)); return null; @@ -2024,7 +2024,13 @@ namespace ArchiSteamFarm { return false; } - string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString())); + byte[] publicKey = KeyDictionary.GetPublicKey(universe); + + if ((publicKey == null) || (publicKey.Length == 0)) { + Bot.ArchiLogger.LogNullError(nameof(publicKey)); + + return false; + } // Generate a random 32-byte session key byte[] sessionKey = CryptoHelper.GenerateRandomBlock(32); @@ -2032,7 +2038,7 @@ namespace ArchiSteamFarm { // RSA encrypt our session key with the public key for the universe we're on byte[] encryptedSessionKey; - using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(universe))) { + using (RSACrypto rsa = new RSACrypto(publicKey)) { encryptedSessionKey = rsa.Encrypt(sessionKey); } @@ -2097,6 +2103,8 @@ namespace ArchiSteamFarm { return false; } + string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString())); + WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunityHost)); WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamHelpHost)); WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamStoreHost)); diff --git a/ArchiSteamFarm/Bot.cs b/ArchiSteamFarm/Bot.cs index 6b288bb39..a35840c2e 100755 --- a/ArchiSteamFarm/Bot.cs +++ b/ArchiSteamFarm/Bot.cs @@ -236,7 +236,7 @@ namespace ArchiSteamFarm { SteamUnifiedMessages steamUnifiedMessages = SteamClient.GetHandler(); - ArchiHandler = new ArchiHandler(ArchiLogger, steamUnifiedMessages); + ArchiHandler = new ArchiHandler(ArchiLogger, steamUnifiedMessages ?? throw new ArgumentNullException(nameof(steamUnifiedMessages))); SteamClient.AddHandler(ArchiHandler); CallbackManager = new CallbackManager(SteamClient); @@ -634,7 +634,7 @@ namespace ArchiSteamFarm { } } - if (productInfoResultSet == null) { + if (productInfoResultSet?.Results == null) { return (optimisticDiscovery ? appID : 0, DateTime.MinValue, true); } @@ -794,7 +794,7 @@ namespace ArchiSteamFarm { } } - if (productInfoResultSet == null) { + if (productInfoResultSet?.Results == null) { return null; } @@ -1058,7 +1058,7 @@ namespace ArchiSteamFarm { return false; } - if (string.IsNullOrEmpty(callback?.Nonce)) { + if (string.IsNullOrEmpty(callback.Nonce)) { await Connect(true).ConfigureAwait(false); return false; @@ -1802,7 +1802,8 @@ namespace ArchiSteamFarm { CardsFarmer.SetInitialState(BotConfig.Paused); if (SendItemsTimer != null) { - SendItemsTimer.Dispose(); + await SendItemsTimer.DisposeAsync().ConfigureAwait(false); + SendItemsTimer = null; } @@ -2544,8 +2545,14 @@ namespace ArchiSteamFarm { } private void OnLoginKey(SteamUser.LoginKeyCallback callback) { - if (string.IsNullOrEmpty(callback?.LoginKey)) { - ArchiLogger.LogNullError(nameof(callback) + " || " + nameof(callback.LoginKey)); + if (callback == null) { + ArchiLogger.LogNullError(nameof(callback)); + + return; + } + + if (string.IsNullOrEmpty(callback.LoginKey)) { + ArchiLogger.LogNullError(nameof(callback.LoginKey)); return; } @@ -2636,7 +2643,7 @@ namespace ArchiSteamFarm { string avatarHash = null; - if ((callback.AvatarHash != null) && (callback.AvatarHash.Length > 0) && callback.AvatarHash.Any(singleByte => singleByte != 0)) { + if ((callback.AvatarHash.Length > 0) && callback.AvatarHash.Any(singleByte => singleByte != 0)) { avatarHash = BitConverter.ToString(callback.AvatarHash).Replace("-", "").ToLowerInvariant(); if (string.IsNullOrEmpty(avatarHash) || avatarHash.All(singleChar => singleChar == '0')) { @@ -2795,7 +2802,8 @@ namespace ArchiSteamFarm { try { if (GamesRedeemerInBackgroundTimer != null) { - GamesRedeemerInBackgroundTimer.Dispose(); + await GamesRedeemerInBackgroundTimer.DisposeAsync().ConfigureAwait(false); + GamesRedeemerInBackgroundTimer = null; } diff --git a/ArchiSteamFarm/CardsFarmer.cs b/ArchiSteamFarm/CardsFarmer.cs index 4bc43e65e..8175f9915 100755 --- a/ArchiSteamFarm/CardsFarmer.cs +++ b/ArchiSteamFarm/CardsFarmer.cs @@ -670,9 +670,7 @@ namespace ArchiSteamFarm { break; default: - if (backgroundTasks == null) { - backgroundTasks = new HashSet(); - } + backgroundTasks ??= new HashSet(); backgroundTasks.Add(task); diff --git a/ArchiSteamFarm/Commands.cs b/ArchiSteamFarm/Commands.cs index 095a84392..93598b7cf 100644 --- a/ArchiSteamFarm/Commands.cs +++ b/ArchiSteamFarm/Commands.cs @@ -585,12 +585,6 @@ namespace ArchiSteamFarm { break; } - if (callback == null) { - response.AppendLine(FormatBotResponse(string.Format(Strings.BotAddLicense, "app/" + gameID, EResult.Timeout))); - - break; - } - response.AppendLine(FormatBotResponse((callback.GrantedApps.Count > 0) || (callback.GrantedPackages.Count > 0) ? string.Format(Strings.BotAddLicenseWithItems, "app/" + gameID, callback.Result, string.Join(", ", callback.GrantedApps.Select(appID => "app/" + appID).Union(callback.GrantedPackages.Select(subID => "sub/" + subID)))) : string.Format(Strings.BotAddLicense, "app/" + gameID, callback.Result))); break; diff --git a/ArchiSteamFarm/IPC/Controllers/Api/ASFController.cs b/ArchiSteamFarm/IPC/Controllers/Api/ASFController.cs index 19e838577..76719529c 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/ASFController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/ASFController.cs @@ -74,9 +74,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api { } if ((ASF.GlobalConfig.AdditionalProperties != null) && (ASF.GlobalConfig.AdditionalProperties.Count > 0)) { - if (request.GlobalConfig.AdditionalProperties == null) { - request.GlobalConfig.AdditionalProperties = new Dictionary(ASF.GlobalConfig.AdditionalProperties.Count, ASF.GlobalConfig.AdditionalProperties.Comparer); - } + request.GlobalConfig.AdditionalProperties ??= new Dictionary(ASF.GlobalConfig.AdditionalProperties.Count, ASF.GlobalConfig.AdditionalProperties.Comparer); foreach ((string key, JToken value) in ASF.GlobalConfig.AdditionalProperties.Where(property => !request.GlobalConfig.AdditionalProperties.ContainsKey(property.Key))) { request.GlobalConfig.AdditionalProperties.Add(key, value); diff --git a/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs b/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs index 668428db2..ff4b7c063 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs @@ -122,9 +122,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api { } if ((bot.BotConfig.AdditionalProperties != null) && (bot.BotConfig.AdditionalProperties.Count > 0)) { - if (request.BotConfig.AdditionalProperties == null) { - request.BotConfig.AdditionalProperties = new Dictionary(bot.BotConfig.AdditionalProperties.Count, bot.BotConfig.AdditionalProperties.Comparer); - } + request.BotConfig.AdditionalProperties ??= new Dictionary(bot.BotConfig.AdditionalProperties.Count, bot.BotConfig.AdditionalProperties.Comparer); foreach ((string key, JToken value) in bot.BotConfig.AdditionalProperties.Where(property => !request.BotConfig.AdditionalProperties.ContainsKey(property.Key))) { request.BotConfig.AdditionalProperties.Add(key, value); diff --git a/ArchiSteamFarm/IPC/Controllers/Api/TypeController.cs b/ArchiSteamFarm/IPC/Controllers/Api/TypeController.cs index 88f399fe8..ef1a40475 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/TypeController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/TypeController.cs @@ -69,7 +69,7 @@ namespace ArchiSteamFarm.IPC.Controllers.Api { } } - foreach (PropertyInfo property in targetType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where(property => property.CanRead && !property.GetMethod.IsPrivate)) { + foreach (PropertyInfo property in targetType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where(property => property.CanRead && (property.GetMethod?.IsPrivate == false))) { JsonPropertyAttribute jsonProperty = property.GetCustomAttribute(); if (jsonProperty != null) { @@ -81,7 +81,15 @@ namespace ArchiSteamFarm.IPC.Controllers.Api { underlyingType = enumType.GetUnifiedName(); foreach (object value in Enum.GetValues(targetType)) { - body[value.ToString()] = Convert.ChangeType(value, enumType).ToString(); + string valueText = value.ToString(); + + if (string.IsNullOrEmpty(valueText)) { + ASF.ArchiLogger.LogNullError(nameof(valueText)); + + return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorObjectIsNull, nameof(valueText)))); + } + + body[valueText] = Convert.ChangeType(value, enumType).ToString(); } } diff --git a/ArchiSteamFarm/IPC/Integration/ApiAuthenticationMiddleware.cs b/ArchiSteamFarm/IPC/Integration/ApiAuthenticationMiddleware.cs index 31baebbb0..405b4cf44 100644 --- a/ArchiSteamFarm/IPC/Integration/ApiAuthenticationMiddleware.cs +++ b/ArchiSteamFarm/IPC/Integration/ApiAuthenticationMiddleware.cs @@ -49,14 +49,12 @@ namespace ArchiSteamFarm.IPC.Integration { Next = next ?? throw new ArgumentNullException(nameof(next)); lock (FailedAuthorizations) { - if (ClearFailedAuthorizationsTimer == null) { - ClearFailedAuthorizationsTimer = new Timer( - e => FailedAuthorizations.Clear(), - null, - TimeSpan.FromHours(FailedAuthorizationsCooldownInHours), // Delay - TimeSpan.FromHours(FailedAuthorizationsCooldownInHours) // Period - ); - } + ClearFailedAuthorizationsTimer ??= new Timer( + e => FailedAuthorizations.Clear(), + null, + TimeSpan.FromHours(FailedAuthorizationsCooldownInHours), // Delay + TimeSpan.FromHours(FailedAuthorizationsCooldownInHours) // Period + ); } } diff --git a/ArchiSteamFarm/RuntimeCompatibility.cs b/ArchiSteamFarm/RuntimeCompatibility.cs index 722886bec..93a8073fb 100644 --- a/ArchiSteamFarm/RuntimeCompatibility.cs +++ b/ArchiSteamFarm/RuntimeCompatibility.cs @@ -132,6 +132,13 @@ namespace ArchiSteamFarm { value = kv.Value; } + [NotNull] + public static Task DisposeAsync([NotNull] this IDisposable disposable) { + disposable.Dispose(); + + return Task.CompletedTask; + } + public static async Task ReceiveAsync([NotNull] this WebSocket webSocket, [NotNull] byte[] buffer, CancellationToken cancellationToken) => await webSocket.ReceiveAsync(new ArraySegment(buffer), cancellationToken).ConfigureAwait(false); public static async Task SendAsync([NotNull] this WebSocket webSocket, [NotNull] byte[] buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => await webSocket.SendAsync(new ArraySegment(buffer), messageType, endOfMessage, cancellationToken).ConfigureAwait(false);