Refactor confirmations

Make it so the design actually follows what Steam gives us now. There is no need for standalone Confirmation object anymore, rather re-use what Steam gives us. Optimize parsing type, expose it as public API. Small breaking change in HandleConfirmations() action.
This commit is contained in:
Archi 2023-06-29 22:34:26 +02:00
parent d7722fae84
commit 3f91b18a4d
No known key found for this signature in database
GPG key ID: 6B138B4C64555AEA
10 changed files with 60 additions and 124 deletions

View file

@ -37,7 +37,6 @@ using ArchiSteamFarm.Steam.Cards;
using ArchiSteamFarm.Steam.Data;
using ArchiSteamFarm.Steam.Exchange;
using ArchiSteamFarm.Steam.Integration;
using ArchiSteamFarm.Steam.Security;
using ArchiSteamFarm.Steam.Storage;
using ArchiSteamFarm.Storage;
using ArchiSteamFarm.Web;
@ -990,7 +989,7 @@ internal sealed class RemoteCommunication : IAsyncDisposable, IDisposable {
pendingMobileTradeOfferIDs.UnionWith(mobileTradeOfferIDs);
if (pendingMobileTradeOfferIDs.Count >= MaxTradeOffersActive) {
(bool twoFactorSuccess, IReadOnlyCollection<Confirmation>? handledConfirmations, _) = await Bot.Actions.HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EType.Trade, pendingMobileTradeOfferIDs, true).ConfigureAwait(false);
(bool twoFactorSuccess, IReadOnlyCollection<Confirmation>? handledConfirmations, _) = await Bot.Actions.HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EConfirmationType.Trade, pendingMobileTradeOfferIDs, true).ConfigureAwait(false);
if (!twoFactorSuccess) {
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Localization.Strings.ActivelyMatchingSomeConfirmationsFailed, handledConfirmations?.Count ?? 0, pendingMobileTradeOfferIDs.Count));
@ -1086,7 +1085,7 @@ internal sealed class RemoteCommunication : IAsyncDisposable, IDisposable {
}
if (pendingMobileTradeOfferIDs.Count > 0) {
(bool twoFactorSuccess, IReadOnlyCollection<Confirmation>? handledConfirmations, _) = Bot.IsConnectedAndLoggedOn ? await Bot.Actions.HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EType.Trade, pendingMobileTradeOfferIDs, true).ConfigureAwait(false) : (false, null, null);
(bool twoFactorSuccess, IReadOnlyCollection<Confirmation>? handledConfirmations, _) = Bot.IsConnectedAndLoggedOn ? await Bot.Actions.HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EConfirmationType.Trade, pendingMobileTradeOfferIDs, true).ConfigureAwait(false) : (false, null, null);
if (!twoFactorSuccess) {
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Localization.Strings.ActivelyMatchingSomeConfirmationsFailed, handledConfirmations?.Count ?? 0, pendingMobileTradeOfferIDs.Count));

View file

@ -30,6 +30,7 @@ using ArchiSteamFarm.IPC.Requests;
using ArchiSteamFarm.IPC.Responses;
using ArchiSteamFarm.Localization;
using ArchiSteamFarm.Steam;
using ArchiSteamFarm.Steam.Data;
using ArchiSteamFarm.Steam.Security;
using Microsoft.AspNetCore.Mvc;
@ -51,7 +52,7 @@ public sealed class TwoFactorAuthenticationController : ArchiController {
ArgumentNullException.ThrowIfNull(request);
if (request.AcceptedType.HasValue && ((request.AcceptedType.Value == Confirmation.EType.Unknown) || !Enum.IsDefined(request.AcceptedType.Value))) {
if (request.AcceptedType.HasValue && ((request.AcceptedType.Value == Confirmation.EConfirmationType.Unknown) || !Enum.IsDefined(request.AcceptedType.Value))) {
return BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsInvalid, nameof(request.AcceptedType))));
}

View file

@ -27,6 +27,7 @@ using System.Globalization;
using System.Linq;
using ArchiSteamFarm.Core;
using ArchiSteamFarm.Localization;
using ArchiSteamFarm.Steam.Data;
using ArchiSteamFarm.Steam.Security;
using Newtonsoft.Json;
@ -50,7 +51,7 @@ public sealed class TwoFactorAuthenticationConfirmationsRequest {
/// Specifies the type of confirmations to handle. If not provided, all confirmation types are considered for an action.
/// </summary>
[JsonProperty]
public Confirmation.EType? AcceptedType { get; private set; }
public Confirmation.EConfirmationType? AcceptedType { get; private set; }
/// <summary>
/// A helper property which works the same as <see cref="AcceptedCreatorIDs" /> but with values written as strings - for javascript compatibility purposes. Use either this one, or <see cref="AcceptedCreatorIDs" />, not both.

View file

@ -19,20 +19,39 @@
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using Newtonsoft.Json;
namespace ArchiSteamFarm.Steam.Data;
internal sealed class ConfirmationData {
[JsonProperty(PropertyName = "creator_id", Required = Required.Always)]
internal readonly ulong CreatorID;
[JsonProperty(PropertyName = "id", Required = Required.Always)]
internal readonly ulong ID;
[PublicAPI]
[SuppressMessage("ReSharper", "ClassCannotBeInstantiated")]
public sealed class Confirmation {
[JsonProperty(PropertyName = "nonce", Required = Required.Always)]
internal readonly ulong Nonce;
[JsonProperty(PropertyName = "type", Required = Required.Always)]
internal readonly string TypeText = "";
public EConfirmationType ConfirmationType { get; private set; }
[JsonProperty(PropertyName = "creator_id", Required = Required.Always)]
public ulong CreatorID { get; private set; }
[JsonProperty(PropertyName = "id", Required = Required.Always)]
public ulong ID { get; private set; }
[JsonConstructor]
private Confirmation() { }
[PublicAPI]
public enum EConfirmationType : byte {
Unknown,
Generic,
Trade,
Market,
// We're missing information about definition of number 4 type
PhoneNumberChange = 5,
AccountRecovery = 6
}
}

View file

@ -19,17 +19,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Collections.Immutable;
using Newtonsoft.Json;
namespace ArchiSteamFarm.Steam.Data;
internal sealed class ConfirmationsResponse : BooleanResponse {
[JsonProperty("conf", Required = Required.DisallowNull)]
internal readonly HashSet<ConfirmationData>? Confirmations;
[JsonProperty("needauth", Required = Required.DisallowNull)]
internal readonly bool NeedAuthentication;
[JsonProperty("conf", Required = Required.Always)]
internal readonly ImmutableHashSet<Confirmation> Confirmations = ImmutableHashSet<Confirmation>.Empty;
[JsonConstructor]
private ConfirmationsResponse() { }

View file

@ -32,7 +32,6 @@ using ArchiSteamFarm.Localization;
using ArchiSteamFarm.Plugins;
using ArchiSteamFarm.Steam.Cards;
using ArchiSteamFarm.Steam.Data;
using ArchiSteamFarm.Steam.Security;
using ArchiSteamFarm.Steam.Storage;
using ArchiSteamFarm.Storage;
using JetBrains.Annotations;
@ -417,7 +416,7 @@ public sealed class Trading : IDisposable {
if (mobileTradeResults.Count > 0) {
HashSet<ulong> mobileTradeOfferIDs = mobileTradeResults.Select(static tradeOffer => tradeOffer.TradeOfferID).ToHashSet();
(bool twoFactorSuccess, _, _) = await Bot.Actions.HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EType.Trade, mobileTradeOfferIDs, true).ConfigureAwait(false);
(bool twoFactorSuccess, _, _) = await Bot.Actions.HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EConfirmationType.Trade, mobileTradeOfferIDs, true).ConfigureAwait(false);
if (twoFactorSuccess) {
foreach (ParseTradeResult mobileTradeResult in mobileTradeResults) {

View file

@ -36,7 +36,6 @@ using ArchiSteamFarm.Helpers;
using ArchiSteamFarm.Localization;
using ArchiSteamFarm.Steam.Data;
using ArchiSteamFarm.Steam.Exchange;
using ArchiSteamFarm.Steam.Security;
using ArchiSteamFarm.Storage;
using ArchiSteamFarm.Web;
using ArchiSteamFarm.Web.Responses;
@ -1856,7 +1855,7 @@ public sealed class ArchiWebHandler : IDisposable {
return resultInSeconds == 0 ? (byte) 0 : (byte) (resultInSeconds / 86400);
}
internal async Task<ConfirmationsResponse?> GetConfirmationsPage(string deviceID, string confirmationHash, ulong time) {
internal async Task<ConfirmationsResponse?> GetConfirmations(string deviceID, string confirmationHash, ulong time) {
if (string.IsNullOrEmpty(deviceID)) {
throw new ArgumentNullException(nameof(deviceID));
}
@ -2177,7 +2176,7 @@ public sealed class ArchiWebHandler : IDisposable {
foreach (Confirmation confirmation in confirmations) {
data.Add(new KeyValuePair<string, string>("cid[]", confirmation.ID.ToString(CultureInfo.InvariantCulture)));
data.Add(new KeyValuePair<string, string>("ck[]", confirmation.Key.ToString(CultureInfo.InvariantCulture)));
data.Add(new KeyValuePair<string, string>("ck[]", confirmation.Nonce.ToString(CultureInfo.InvariantCulture)));
}
ObjectResponse<BooleanResponse>? response = await UrlPostToJsonObjectWithSession<BooleanResponse>(request, data: data).ConfigureAwait(false);

View file

@ -21,6 +21,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
@ -33,7 +34,6 @@ using ArchiSteamFarm.Helpers;
using ArchiSteamFarm.Localization;
using ArchiSteamFarm.Steam.Data;
using ArchiSteamFarm.Steam.Exchange;
using ArchiSteamFarm.Steam.Security;
using ArchiSteamFarm.Steam.Storage;
using ArchiSteamFarm.Storage;
using ArchiSteamFarm.Web;
@ -133,7 +133,7 @@ public sealed class Actions : IAsyncDisposable, IDisposable {
}
[PublicAPI]
public async Task<(bool Success, IReadOnlyCollection<Confirmation>? HandledConfirmations, string Message)> HandleTwoFactorAuthenticationConfirmations(bool accept, Confirmation.EType? acceptedType = null, IReadOnlyCollection<ulong>? acceptedCreatorIDs = null, bool waitIfNeeded = false) {
public async Task<(bool Success, IReadOnlyCollection<Confirmation>? HandledConfirmations, string Message)> HandleTwoFactorAuthenticationConfirmations(bool accept, Confirmation.EConfirmationType? acceptedType = null, IReadOnlyCollection<ulong>? acceptedCreatorIDs = null, bool waitIfNeeded = false) {
if (Bot.BotDatabase.MobileAuthenticator == null) {
return (false, null, Strings.BotNoASFAuthenticator);
}
@ -149,36 +149,38 @@ public sealed class Actions : IAsyncDisposable, IDisposable {
await Task.Delay(1000).ConfigureAwait(false);
}
HashSet<Confirmation>? confirmations = await Bot.BotDatabase.MobileAuthenticator.GetConfirmations().ConfigureAwait(false);
ImmutableHashSet<Confirmation>? confirmations = await Bot.BotDatabase.MobileAuthenticator.GetConfirmations().ConfigureAwait(false);
if ((confirmations == null) || (confirmations.Count == 0)) {
continue;
}
HashSet<Confirmation> remainingConfirmations = confirmations.ToHashSet();
if (acceptedType.HasValue) {
if (confirmations.RemoveWhere(confirmation => confirmation.Type != acceptedType.Value) > 0) {
if (confirmations.Count == 0) {
if (remainingConfirmations.RemoveWhere(confirmation => confirmation.ConfirmationType != acceptedType.Value) > 0) {
if (remainingConfirmations.Count == 0) {
continue;
}
}
}
if (acceptedCreatorIDs?.Count > 0) {
if (confirmations.RemoveWhere(confirmation => !acceptedCreatorIDs.Contains(confirmation.Creator)) > 0) {
if (confirmations.Count == 0) {
if (remainingConfirmations.RemoveWhere(confirmation => !acceptedCreatorIDs.Contains(confirmation.CreatorID)) > 0) {
if (remainingConfirmations.Count == 0) {
continue;
}
}
}
if (!await Bot.BotDatabase.MobileAuthenticator.HandleConfirmations(confirmations, accept).ConfigureAwait(false)) {
if (!await Bot.BotDatabase.MobileAuthenticator.HandleConfirmations(remainingConfirmations, accept).ConfigureAwait(false)) {
return (false, handledConfirmations?.Values, Strings.WarningFailed);
}
handledConfirmations ??= new Dictionary<ulong, Confirmation>();
foreach (Confirmation? confirmation in confirmations) {
handledConfirmations[confirmation.Creator] = confirmation;
foreach (Confirmation? confirmation in remainingConfirmations) {
handledConfirmations[confirmation.CreatorID] = confirmation;
}
// We've accepted *something*, if caller didn't specify the IDs, that's enough for us
@ -343,7 +345,7 @@ public sealed class Actions : IAsyncDisposable, IDisposable {
(bool success, _, HashSet<ulong>? mobileTradeOfferIDs) = await Bot.ArchiWebHandler.SendTradeOffer(targetSteamID, items, token: tradeToken, itemsPerTrade: itemsPerTrade).ConfigureAwait(false);
if ((mobileTradeOfferIDs?.Count > 0) && Bot.HasMobileAuthenticator) {
(bool twoFactorSuccess, _, _) = await HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EType.Trade, mobileTradeOfferIDs, true).ConfigureAwait(false);
(bool twoFactorSuccess, _, _) = await HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EConfirmationType.Trade, mobileTradeOfferIDs, true).ConfigureAwait(false);
if (!twoFactorSuccess) {
return (false, Strings.BotLootingFailed);

View file

@ -1,61 +0,0 @@
// _ _ _ ____ _ _____
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
// |
// Copyright 2015-2023 Łukasz "JustArchi" Domeradzki
// Contact: JustArchi@JustArchi.net
// |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// |
// http://www.apache.org/licenses/LICENSE-2.0
// |
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.ComponentModel;
using JetBrains.Annotations;
using Newtonsoft.Json;
namespace ArchiSteamFarm.Steam.Security;
public sealed class Confirmation {
[JsonProperty(Required = Required.Always)]
public ulong Creator { get; }
[JsonProperty(Required = Required.Always)]
public ulong ID { get; }
[JsonProperty(Required = Required.Always)]
public ulong Key { get; }
[JsonProperty(Required = Required.Always)]
public EType Type { get; }
internal Confirmation(ulong id, ulong key, ulong creator, EType type) {
ID = id > 0 ? id : throw new ArgumentOutOfRangeException(nameof(id));
Key = key > 0 ? key : throw new ArgumentOutOfRangeException(nameof(key));
Creator = creator > 0 ? creator : throw new ArgumentOutOfRangeException(nameof(creator));
Type = Enum.IsDefined(type) ? type : throw new InvalidEnumArgumentException(nameof(type), (int) type, typeof(EType));
}
// REF: Internal documentation
[PublicAPI]
public enum EType : byte {
Unknown,
Generic,
Trade,
Market,
// We're missing information about definition of number 4 type
PhoneNumberChange = 5,
AccountRecovery = 6
}
}

View file

@ -24,6 +24,7 @@ using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
@ -142,7 +143,7 @@ public sealed class MobileAuthenticator : IDisposable {
);
}
internal async Task<HashSet<Confirmation>?> GetConfirmations() {
internal async Task<ImmutableHashSet<Confirmation>?> GetConfirmations() {
if (Bot == null) {
throw new InvalidOperationException(nameof(Bot));
}
@ -172,38 +173,17 @@ public sealed class MobileAuthenticator : IDisposable {
}
// ReSharper disable RedundantSuppressNullableWarningExpression - required for .NET Framework
ConfirmationsResponse? response = await Bot.ArchiWebHandler.GetConfirmationsPage(deviceID!, confirmationHash!, time).ConfigureAwait(false);
ConfirmationsResponse? response = await Bot.ArchiWebHandler.GetConfirmations(deviceID!, confirmationHash!, time).ConfigureAwait(false);
// ReSharper restore RedundantSuppressNullableWarningExpression - required for .NET Framework
if (response?.Confirmations == null) {
if (response?.Success != true) {
return null;
}
if (!response.Success) {
return null;
foreach (Confirmation? confirmation in response.Confirmations.Where(static confirmation => (confirmation.ConfirmationType == Confirmation.EConfirmationType.Unknown) || !Enum.IsDefined(confirmation.ConfirmationType))) {
Bot.ArchiLogger.LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.WarningUnknownValuePleaseReport, nameof(confirmation.ConfirmationType), confirmation.ConfirmationType));
}
HashSet<Confirmation> result = new();
foreach (ConfirmationData confirmation in response.Confirmations) {
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
if (!Enum.TryParse(confirmation.TypeText!, out Confirmation.EType type) || (type == Confirmation.EType.Unknown)) {
Bot.ArchiLogger.LogNullError(type);
return null;
}
if (!Enum.IsDefined(type)) {
Bot.ArchiLogger.LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.WarningUnknownValuePleaseReport, nameof(type), type));
return null;
}
result.Add(new Confirmation(confirmation.ID, confirmation.Nonce, confirmation.CreatorID, type));
}
return result;
return response.Confirmations;
}
internal async Task<ulong> GetSteamTime() {
@ -295,7 +275,7 @@ public sealed class MobileAuthenticator : IDisposable {
// We totally ignore actual result returned by those calls, abort only if request timed out
foreach (Confirmation confirmation in confirmations) {
// ReSharper disable RedundantSuppressNullableWarningExpression - required for .NET Framework
bool? confirmationResult = await Bot.ArchiWebHandler.HandleConfirmation(deviceID!, confirmationHash!, time, confirmation.ID, confirmation.Key, accept).ConfigureAwait(false);
bool? confirmationResult = await Bot.ArchiWebHandler.HandleConfirmation(deviceID!, confirmationHash!, time, confirmation.ID, confirmation.Nonce, accept).ConfigureAwait(false);
// ReSharper restore RedundantSuppressNullableWarningExpression - required for .NET Framework