Files
ArchiSteamFarm/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/RemoteCommunication.cs

957 lines
39 KiB
C#
Raw Normal View History

2019-02-16 17:34:17 +01:00
// _ _ _ ____ _ _____
2017-11-18 17:27:06 +01:00
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
2019-01-14 19:11:17 +01:00
// |
// Copyright 2015-2023 Łukasz "JustArchi" Domeradzki
2018-07-27 04:52:14 +02:00
// Contact: JustArchi@JustArchi.net
2019-01-14 19:11:17 +01:00
// |
2018-07-27 04:52:14 +02:00
// 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
2019-01-14 19:11:17 +01:00
// |
2018-07-27 04:52:14 +02:00
// http://www.apache.org/licenses/LICENSE-2.0
2019-01-14 19:11:17 +01:00
// |
2018-07-27 04:52:14 +02:00
// 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.Collections.Generic;
2018-12-14 16:07:46 +01:00
using System.Collections.Immutable;
2020-11-14 22:37:00 +01:00
using System.Globalization;
2018-02-21 17:44:06 +01:00
using System.Linq;
using System.Net;
using System.Net.Http;
2016-12-04 02:49:56 +01:00
using System.Threading;
using System.Threading.Tasks;
using ArchiSteamFarm.Core;
using ArchiSteamFarm.Localization;
2022-12-15 19:16:28 +01:00
using ArchiSteamFarm.OfficialPlugins.ItemsMatcher.Data;
using ArchiSteamFarm.Steam;
2021-05-08 12:49:46 +02:00
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;
using ArchiSteamFarm.Web.Responses;
namespace ArchiSteamFarm.OfficialPlugins.ItemsMatcher;
2021-11-10 21:23:24 +01:00
internal sealed class RemoteCommunication : IAsyncDisposable, IDisposable {
2023-01-13 17:16:15 +01:00
private const byte MaxAnnouncementTTL = 60; // Maximum amount of minutes we can wait if the next announcement doesn't happen naturally
private const byte MaxTradeOffersActive = 10; // The actual upper limit is 30, but we should use lower amount to allow some bots to react before we hit the maximum allowed
private const byte MinAnnouncementTTL = 5; // Minimum amount of minutes we must wait before the next Announcement
2021-11-10 21:23:24 +01:00
private const byte MinHeartBeatTTL = 10; // Minimum amount of minutes we must wait before sending next HeartBeat
private const byte MinPersonaStateTTL = 5; // Minimum amount of minutes we must wait before requesting persona state update
2021-11-10 21:23:24 +01:00
private static readonly ImmutableHashSet<Asset.EType> AcceptedMatchableTypes = ImmutableHashSet.Create(
Asset.EType.Emoticon,
Asset.EType.FoilTradingCard,
Asset.EType.ProfileBackground,
Asset.EType.TradingCard
);
private readonly Bot Bot;
private readonly Timer? HeartBeatTimer;
// We access this collection only within a semaphore, therefore there is no need for concurrent access
private readonly Dictionary<ulong, uint> LastAnnouncedItems = new();
private readonly SemaphoreSlim MatchActivelySemaphore = new(1, 1);
private readonly Timer? MatchActivelyTimer;
2021-11-10 21:23:24 +01:00
private readonly SemaphoreSlim RequestsSemaphore = new(1, 1);
2023-01-18 23:11:17 +01:00
private readonly WebBrowser WebBrowser;
2017-07-13 06:08:52 +02:00
private string? LastAnnouncedTradeToken;
private DateTime LastAnnouncement;
2021-11-10 21:23:24 +01:00
private DateTime LastHeartBeat;
private DateTime LastPersonaStateRequest;
private bool ShouldSendAnnouncementEarlier;
2021-11-10 21:23:24 +01:00
private bool ShouldSendHeartBeats;
private bool SignedInWithSteam;
2016-12-04 02:08:45 +01:00
internal RemoteCommunication(Bot bot) {
ArgumentNullException.ThrowIfNull(bot);
2016-12-04 02:08:45 +01:00
Bot = bot;
WebBrowser = new WebBrowser(bot.ArchiLogger, ASF.GlobalConfig?.WebProxy, true);
2023-01-18 23:11:17 +01:00
if (Bot.BotConfig.TradingPreferences.HasFlag(BotConfig.ETradingPreferences.SteamTradeMatcher) && Bot.BotConfig.RemoteCommunication.HasFlag(BotConfig.ERemoteCommunication.PublicListing)) {
HeartBeatTimer = new Timer(
HeartBeat,
null,
TimeSpan.FromMinutes(1) + TimeSpan.FromSeconds(ASF.LoadBalancingDelay * Bot.Bots?.Count ?? 0),
TimeSpan.FromMinutes(1)
);
}
if (Bot.BotConfig.TradingPreferences.HasFlag(BotConfig.ETradingPreferences.MatchActively)) {
if ((ASF.GlobalConfig?.LicenseID != null) && (ASF.GlobalConfig.LicenseID != Guid.Empty)) {
MatchActivelyTimer = new Timer(
MatchActively,
null,
TimeSpan.FromHours(1) + TimeSpan.FromSeconds(ASF.LoadBalancingDelay * Bot.Bots?.Count ?? 0),
TimeSpan.FromHours(6)
);
} else {
bot.ArchiLogger.LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.WarningNoLicense, nameof(BotConfig.ETradingPreferences.MatchActively)));
}
}
2021-11-10 21:23:24 +01:00
}
public void Dispose() {
// Those are objects that are always being created if constructor doesn't throw exception
MatchActivelySemaphore.Dispose();
RequestsSemaphore.Dispose();
2023-01-18 23:11:17 +01:00
WebBrowser.Dispose();
// Those are objects that might be null and the check should be in-place
HeartBeatTimer?.Dispose();
if (MatchActivelyTimer != null) {
// ReSharper disable once SuspiciousLockOverSynchronizationPrimitive - this is not a mistake, we need extra synchronization, and we can re-use the semaphore object for that
lock (MatchActivelySemaphore) {
MatchActivelyTimer.Dispose();
}
}
}
2021-11-10 21:23:24 +01:00
public async ValueTask DisposeAsync() {
// Those are objects that are always being created if constructor doesn't throw exception
2021-11-10 21:23:24 +01:00
MatchActivelySemaphore.Dispose();
RequestsSemaphore.Dispose();
2023-01-18 23:11:17 +01:00
WebBrowser.Dispose();
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
// Those are objects that might be null and the check should be in-place
if (HeartBeatTimer != null) {
await HeartBeatTimer.DisposeAsync().ConfigureAwait(false);
}
if (MatchActivelyTimer != null) {
// ReSharper disable once SuspiciousLockOverSynchronizationPrimitive - this is not a mistake, we need extra synchronization, and we can re-use the semaphore object for that
lock (MatchActivelySemaphore) {
MatchActivelyTimer.Dispose();
}
}
2021-11-10 21:23:24 +01:00
}
internal void OnNewItemsNotification() => ShouldSendAnnouncementEarlier = true;
2019-04-05 14:29:35 +02:00
2021-11-10 21:23:24 +01:00
internal async Task OnPersonaState(string? nickname = null, string? avatarHash = null) {
if (!Bot.BotConfig.RemoteCommunication.HasFlag(BotConfig.ERemoteCommunication.PublicListing) || !Bot.BotConfig.TradingPreferences.HasFlag(BotConfig.ETradingPreferences.SteamTradeMatcher)) {
return;
}
if ((DateTime.UtcNow < LastAnnouncement.AddMinutes(ShouldSendAnnouncementEarlier ? MinAnnouncementTTL : MaxAnnouncementTTL)) && ShouldSendHeartBeats) {
2021-11-10 21:23:24 +01:00
return;
2019-05-19 15:38:06 +02:00
}
2023-01-18 22:52:25 +01:00
if (MatchActivelySemaphore.CurrentCount == 0) {
// We shouldn't bother with announcements while we're matching, it can wait until we're done
return;
}
2021-11-10 21:23:24 +01:00
await RequestsSemaphore.WaitAsync().ConfigureAwait(false);
try {
if ((DateTime.UtcNow < LastAnnouncement.AddMinutes(ShouldSendAnnouncementEarlier ? MinAnnouncementTTL : MaxAnnouncementTTL)) && ShouldSendHeartBeats) {
return;
}
2023-01-18 22:52:25 +01:00
if (MatchActivelySemaphore.CurrentCount == 0) {
// We shouldn't bother with announcements while we're matching, it can wait until we're done
return;
}
2021-11-10 21:23:24 +01:00
// Don't announce if we don't meet conditions
bool? eligible = await IsEligibleForListing().ConfigureAwait(false);
2016-12-04 02:49:56 +01:00
2021-11-10 21:23:24 +01:00
if (!eligible.HasValue) {
// This is actually network failure, so we'll stop sending heartbeats but not record it as valid check
ShouldSendHeartBeats = false;
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, $"{nameof(IsEligibleForListing)}: {eligible?.ToString() ?? "null"}"));
2021-11-10 21:23:24 +01:00
return;
}
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
if (!eligible.Value) {
// We're not eligible, record this as a valid check
LastAnnouncement = DateTime.UtcNow;
ShouldSendAnnouncementEarlier = ShouldSendHeartBeats = false;
2019-04-05 15:12:54 +02:00
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, $"{nameof(IsEligibleForListing)}: {eligible.Value}"));
2021-11-10 21:23:24 +01:00
return;
}
2019-04-05 15:12:54 +02:00
HashSet<Asset.EType> acceptedMatchableTypes = Bot.BotConfig.MatchableTypes.Where(AcceptedMatchableTypes.Contains).ToHashSet();
if (acceptedMatchableTypes.Count == 0) {
throw new InvalidOperationException(nameof(acceptedMatchableTypes));
2021-11-10 21:23:24 +01:00
}
2019-04-05 15:12:54 +02:00
string? tradeToken = await Bot.ArchiHandler.GetTradeToken().ConfigureAwait(false);
2019-04-05 15:12:54 +02:00
if (string.IsNullOrEmpty(tradeToken)) {
// This is actually a network failure, so we'll stop sending heartbeats but not record it as valid check
2021-11-10 21:23:24 +01:00
ShouldSendHeartBeats = false;
2019-04-05 15:12:54 +02:00
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, nameof(tradeToken)));
2021-11-10 21:23:24 +01:00
return;
}
2018-12-15 00:27:15 +01:00
// We require to fetch whole inventory as a list here, as we need to know the order for calculating index and previousAssetID
List<Asset> inventory;
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
try {
inventory = await Bot.ArchiWebHandler.GetInventoryAsync().ToListAsync().ConfigureAwait(false);
2021-11-10 21:23:24 +01:00
} catch (HttpRequestException e) {
// This is actually a network failure, so we'll stop sending heartbeats but not record it as valid check
2021-11-10 21:23:24 +01:00
ShouldSendHeartBeats = false;
Bot.ArchiLogger.LogGenericWarningException(e);
2021-11-10 21:23:24 +01:00
return;
} catch (Exception e) {
// This is actually a network failure, so we'll stop sending heartbeats but not record it as valid check
2021-11-10 21:23:24 +01:00
ShouldSendHeartBeats = false;
Bot.ArchiLogger.LogGenericException(e);
2021-11-10 21:23:24 +01:00
return;
}
2023-01-14 23:08:13 +01:00
if (inventory.Count == 0) {
// We're not eligible, record this as a valid check
LastAnnouncement = DateTime.UtcNow;
ShouldSendAnnouncementEarlier = ShouldSendHeartBeats = false;
2016-12-04 02:49:56 +01:00
2021-11-10 21:23:24 +01:00
return;
}
2018-12-20 17:40:51 +01:00
bool matchEverything = Bot.BotConfig.TradingPreferences.HasFlag(BotConfig.ETradingPreferences.MatchEverything);
ulong previousAssetID = 0;
List<AssetForListing> assetsForListing = new();
Dictionary<(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity), bool> tradableSets = new();
foreach (Asset item in inventory) {
if (acceptedMatchableTypes.Contains(item.Type)) {
// Only tradable assets matter for MatchEverything bots
if (!matchEverything || item.Tradable) {
assetsForListing.Add(new AssetForListing(item, previousAssetID));
}
// But even for Fair bots, we should track and skip sets where we don't have any item to trade with
if (!matchEverything) {
(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity) key = (item.RealAppID, item.Type, item.Rarity);
if (tradableSets.TryGetValue(key, out bool tradable)) {
if (!tradable && item.Tradable) {
tradableSets[key] = true;
}
} else {
tradableSets[key] = item.Tradable;
}
}
}
previousAssetID = item.AssetID;
}
2023-01-14 23:08:13 +01:00
if (assetsForListing.Count == 0) {
// We're not eligible, record this as a valid check
LastAnnouncement = DateTime.UtcNow;
ShouldSendAnnouncementEarlier = ShouldSendHeartBeats = false;
return;
}
// We can now skip sets where we don't have any item to trade with, MatchEverything bots are already filtered to tradable only
if (!matchEverything) {
assetsForListing.RemoveAll(item => tradableSets.TryGetValue((item.RealAppID, item.Type, item.Rarity), out bool tradable) && !tradable);
if (assetsForListing.Count == 0) {
// We're not eligible, record this as a valid check
LastAnnouncement = DateTime.UtcNow;
ShouldSendAnnouncementEarlier = ShouldSendHeartBeats = false;
return;
}
}
if (ShouldSendHeartBeats && (tradeToken == LastAnnouncedTradeToken) && (assetsForListing.Count == LastAnnouncedItems.Count) && assetsForListing.All(item => LastAnnouncedItems.TryGetValue(item.AssetID, out uint amount) && (item.Amount == amount))) {
// There is nothing new to announce, this is fine, skip the request
LastAnnouncement = DateTime.UtcNow;
ShouldSendAnnouncementEarlier = false;
return;
}
if (!SignedInWithSteam) {
HttpStatusCode? signInWithSteam = await ArchiNet.SignInWithSteam(Bot, WebBrowser).ConfigureAwait(false);
if (signInWithSteam == null) {
// This is actually a network failure, so we'll stop sending heartbeats but not record it as valid check
ShouldSendHeartBeats = false;
return;
}
if (!signInWithSteam.Value.IsSuccessCode()) {
// SignIn procedure failed and it wasn't a network error, hold off with future tries at least for a full day
LastAnnouncement = DateTime.UtcNow.AddDays(1);
ShouldSendHeartBeats = false;
return;
}
SignedInWithSteam = true;
}
Bot.ArchiLogger.LogGenericInfo(string.Format(CultureInfo.CurrentCulture, Localization.Strings.ListingAnnouncing, Bot.SteamID, nickname ?? Bot.SteamID.ToString(CultureInfo.InvariantCulture), assetsForListing.Count));
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
BasicResponse? response = await Backend.AnnounceForListing(Bot.SteamID, WebBrowser, assetsForListing, acceptedMatchableTypes, (uint) inventory.Count, matchEverything, tradeToken!, nickname, avatarHash).ConfigureAwait(false);
2018-12-15 00:27:15 +01:00
if (response == null) {
// This is actually a network failure, so we'll stop sending heartbeats but not record it as valid check
ShouldSendHeartBeats = false;
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.ErrorObjectIsNull, nameof(response)));
2021-11-10 21:23:24 +01:00
return;
}
2016-12-04 02:49:56 +01:00
if (response.StatusCode.IsRedirectionCode()) {
ShouldSendHeartBeats = false;
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, response.StatusCode));
if (response.FinalUri.Host != ArchiWebHandler.SteamCommunityURL.Host) {
ASF.ArchiLogger.LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.WarningUnknownValuePleaseReport, nameof(response.FinalUri), response.FinalUri));
return;
}
// We've expected the result, not the redirection to the sign in, we need to authenticate again
SignedInWithSteam = false;
return;
}
if (response.StatusCode.IsClientErrorCode()) {
// ArchiNet told us that we've sent a bad request, so the process should restart from the beginning at later time
2021-11-10 21:23:24 +01:00
ShouldSendHeartBeats = false;
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, response.StatusCode));
switch (response.StatusCode) {
case HttpStatusCode.Forbidden:
// ArchiNet told us to stop submitting data for now
LastAnnouncement = DateTime.UtcNow.AddYears(1);
return;
#if NETFRAMEWORK
case (HttpStatusCode) 429:
#else
case HttpStatusCode.TooManyRequests:
#endif
// ArchiNet told us to try again later
LastAnnouncement = DateTime.UtcNow.AddDays(1);
return;
default:
// There is something wrong with our payload or the server, we shouldn't retry for at least several hours
LastAnnouncement = DateTime.UtcNow.AddHours(6);
return;
}
2021-11-10 21:23:24 +01:00
}
LastAnnouncement = LastHeartBeat = DateTime.UtcNow;
ShouldSendAnnouncementEarlier = false;
2021-11-10 21:23:24 +01:00
ShouldSendHeartBeats = true;
LastAnnouncedTradeToken = tradeToken;
LastAnnouncedItems.Clear();
foreach (AssetForListing item in assetsForListing) {
LastAnnouncedItems[item.AssetID] = item.Amount;
}
LastAnnouncedItems.TrimExcess();
} finally {
RequestsSemaphore.Release();
}
Bot.ArchiLogger.LogGenericInfo(Strings.Success);
}
internal void TriggerMatchActivelyEarlier() {
if (MatchActivelyTimer == null) {
throw new InvalidOperationException(nameof(MatchActivelyTimer));
}
// ReSharper disable once SuspiciousLockOverSynchronizationPrimitive - this is not a mistake, we need extra synchronization, and we can re-use the semaphore object for that
lock (MatchActivelySemaphore) {
MatchActivelyTimer.Change(TimeSpan.Zero, TimeSpan.FromHours(6));
}
}
private async void HeartBeat(object? state = null) {
if (!Bot.IsConnectedAndLoggedOn || (Bot.HeartBeatFailures > 0)) {
return;
}
// Request persona update if needed
2023-01-18 23:11:17 +01:00
if ((DateTime.UtcNow > LastPersonaStateRequest.AddMinutes(MinPersonaStateTTL)) && (DateTime.UtcNow > LastAnnouncement.AddMinutes(ShouldSendAnnouncementEarlier ? MinAnnouncementTTL : MaxAnnouncementTTL))) {
LastPersonaStateRequest = DateTime.UtcNow;
Bot.RequestPersonaStateUpdate();
}
if (!ShouldSendHeartBeats || (DateTime.UtcNow < LastHeartBeat.AddMinutes(MinHeartBeatTTL))) {
return;
}
if (!await RequestsSemaphore.WaitAsync(0).ConfigureAwait(false)) {
return;
}
try {
BasicResponse? response = await Backend.HeartBeatForListing(Bot, WebBrowser).ConfigureAwait(false);
if (response == null) {
// This is actually a network failure, we should keep sending heartbeats for now
return;
}
if (response.StatusCode.IsRedirectionCode()) {
ShouldSendHeartBeats = false;
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, response.StatusCode));
if (response.FinalUri.Host != ArchiWebHandler.SteamCommunityURL.Host) {
ASF.ArchiLogger.LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.WarningUnknownValuePleaseReport, nameof(response.FinalUri), response.FinalUri));
return;
}
// We've expected the result, not the redirection to the sign in, we need to authenticate again
SignedInWithSteam = false;
return;
}
if (response.StatusCode.IsClientErrorCode()) {
ShouldSendHeartBeats = false;
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, response.StatusCode));
return;
}
LastHeartBeat = DateTime.UtcNow;
2021-11-10 21:23:24 +01:00
} finally {
RequestsSemaphore.Release();
}
}
2019-04-05 16:25:44 +02:00
2021-11-10 21:23:24 +01:00
private async Task<bool?> IsEligibleForListing() {
// Bot must be eligible for matching
2021-11-10 21:23:24 +01:00
bool? isEligibleForMatching = await IsEligibleForMatching().ConfigureAwait(false);
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
if (isEligibleForMatching != true) {
return isEligibleForMatching;
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
}
// Bot must have a public inventory
2021-11-10 21:23:24 +01:00
bool? hasPublicInventory = await Bot.HasPublicInventory().ConfigureAwait(false);
2019-06-19 18:50:26 +02:00
2021-11-10 21:23:24 +01:00
if (hasPublicInventory != true) {
Bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, $"{nameof(Bot.HasPublicInventory)}: {hasPublicInventory?.ToString() ?? "null"}"));
2019-06-19 18:50:26 +02:00
2021-11-10 21:23:24 +01:00
return hasPublicInventory;
}
2019-06-19 18:50:26 +02:00
2021-11-10 21:23:24 +01:00
return true;
}
2019-06-19 18:50:26 +02:00
2021-11-10 21:23:24 +01:00
private async Task<bool?> IsEligibleForMatching() {
// Bot must have ASF 2FA
if (!Bot.HasMobileAuthenticator) {
Bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, $"{nameof(Bot.HasMobileAuthenticator)}: {Bot.HasMobileAuthenticator}"));
2019-06-19 18:50:26 +02:00
2021-11-10 21:23:24 +01:00
return false;
2019-06-19 18:50:26 +02:00
}
2021-11-10 21:23:24 +01:00
// Bot must have at least one accepted matchable type set
if ((Bot.BotConfig.MatchableTypes.Count == 0) || Bot.BotConfig.MatchableTypes.All(static type => !AcceptedMatchableTypes.Contains(type))) {
Bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, $"{nameof(Bot.BotConfig.MatchableTypes)}: {string.Join(", ", Bot.BotConfig.MatchableTypes)}"));
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
return false;
}
2018-03-24 17:14:01 +01:00
2021-11-10 21:23:24 +01:00
// Bot must have valid API key (e.g. not being restricted account)
bool? hasValidApiKey = await Bot.ArchiWebHandler.HasValidApiKey().ConfigureAwait(false);
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
if (hasValidApiKey != true) {
Bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, $"{nameof(Bot.ArchiWebHandler.HasValidApiKey)}: {hasValidApiKey?.ToString() ?? "null"}"));
2018-03-24 17:14:01 +01:00
2021-11-10 21:23:24 +01:00
return hasValidApiKey;
}
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
return true;
}
2019-04-05 15:12:54 +02:00
2021-11-10 21:23:24 +01:00
private async void MatchActively(object? state = null) {
if (ASF.GlobalConfig == null) {
throw new InvalidOperationException(nameof(ASF.GlobalConfig));
}
if (!ASF.GlobalConfig.LicenseID.HasValue || (ASF.GlobalConfig.LicenseID == Guid.Empty)) {
throw new InvalidOperationException(nameof(ASF.GlobalConfig.LicenseID));
}
if (!Bot.IsConnectedAndLoggedOn || Bot.BotConfig.TradingPreferences.HasFlag(BotConfig.ETradingPreferences.MatchEverything) || !Bot.BotConfig.TradingPreferences.HasFlag(BotConfig.ETradingPreferences.MatchActively)) {
Bot.ArchiLogger.LogGenericTrace(Strings.ErrorAborted);
2018-12-08 01:45:13 +01:00
2021-11-10 21:23:24 +01:00
return;
2018-03-24 17:14:01 +01:00
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
bool? eligible = await IsEligibleForMatching().ConfigureAwait(false);
if (eligible != true) {
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, $"{nameof(IsEligibleForMatching)}: {eligible?.ToString() ?? "null"}"));
return;
}
2021-11-10 21:23:24 +01:00
HashSet<Asset.EType> acceptedMatchableTypes = Bot.BotConfig.MatchableTypes.Where(AcceptedMatchableTypes.Contains).ToHashSet();
2021-11-10 21:23:24 +01:00
if (acceptedMatchableTypes.Count == 0) {
Bot.ArchiLogger.LogNullError(acceptedMatchableTypes);
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
return;
}
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
if (!await MatchActivelySemaphore.WaitAsync(0).ConfigureAwait(false)) {
Bot.ArchiLogger.LogGenericTrace(Strings.ErrorAborted);
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
return;
}
2018-12-15 00:27:15 +01:00
2023-01-18 22:52:25 +01:00
bool tradesSent;
2021-11-10 21:23:24 +01:00
try {
Bot.ArchiLogger.LogGenericInfo(Strings.Starting);
Dictionary<ulong, Asset> ourInventory;
2018-12-15 00:27:15 +01:00
try {
ourInventory = await Bot.ArchiWebHandler.GetInventoryAsync().Where(item => acceptedMatchableTypes.Contains(item.Type) && !Bot.BotDatabase.MatchActivelyBlacklistAppIDs.Contains(item.RealAppID)).ToDictionaryAsync(static item => item.AssetID).ConfigureAwait(false);
} catch (HttpRequestException e) {
Bot.ArchiLogger.LogGenericWarningException(e);
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, nameof(ourInventory)));
return;
} catch (Exception e) {
Bot.ArchiLogger.LogGenericException(e);
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, nameof(ourInventory)));
return;
}
if (ourInventory.Count == 0) {
Bot.ArchiLogger.LogGenericInfo(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(ourInventory)));
return;
}
2022-12-23 15:08:36 +01:00
// Remove from our inventory items that can't be possibly matched due to no dupes to offer available
HashSet<(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity)> setsToKeep = Trading.GetInventorySets(ourInventory.Values).Where(static set => set.Value.Any(static amount => amount > 1)).Select(static set => set.Key).ToHashSet();
2022-12-23 15:08:36 +01:00
HashSet<ulong> assetIDsToRemove = ourInventory.Where(item => !setsToKeep.Contains((item.Value.RealAppID, item.Value.Type, item.Value.Rarity))).Select(static item => item.Key).ToHashSet();
foreach (ulong assetIDToRemove in assetIDsToRemove) {
ourInventory.Remove(assetIDToRemove);
}
2022-12-23 15:08:36 +01:00
if (ourInventory.Count == 0) {
Bot.ArchiLogger.LogGenericInfo(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(ourInventory)));
return;
}
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
(HttpStatusCode StatusCode, ImmutableHashSet<ListedUser> Users)? response = await Backend.GetListedUsersForMatching(ASF.GlobalConfig.LicenseID.Value, Bot, WebBrowser, ourInventory.Values, acceptedMatchableTypes).ConfigureAwait(false);
if (response == null) {
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, nameof(response)));
return;
}
if (!response.Value.StatusCode.IsSuccessCode()) {
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, response.Value.StatusCode));
return;
}
if (response.Value.Users.IsEmpty) {
2023-01-11 20:15:19 +01:00
Bot.ArchiLogger.LogGenericInfo(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(response.Value.Users)));
return;
}
2018-12-03 05:21:12 +01:00
#pragma warning disable CA2000 // False positive, we're actually wrapping it in the using clause below exactly for that purpose
using (await Bot.Actions.GetTradingLock().ConfigureAwait(false)) {
#pragma warning restore CA2000 // False positive, we're actually wrapping it in the using clause below exactly for that purpose
Bot.ArchiLogger.LogGenericInfo(Strings.Starting);
2023-01-18 22:52:25 +01:00
tradesSent = await MatchActively(response.Value.Users, ourInventory, acceptedMatchableTypes).ConfigureAwait(false);
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
}
Bot.ArchiLogger.LogGenericInfo(Strings.Done);
2021-11-10 21:23:24 +01:00
} finally {
MatchActivelySemaphore.Release();
}
2023-01-18 22:52:25 +01:00
if (tradesSent && ShouldSendHeartBeats && (DateTime.UtcNow > LastAnnouncement.AddMinutes(ShouldSendAnnouncementEarlier ? MinAnnouncementTTL : MaxAnnouncementTTL))) {
// If we're announced, it makes sense to update our state now, at least once
Bot.RequestPersonaStateUpdate();
}
2021-11-10 21:23:24 +01:00
}
2020-11-14 22:37:00 +01:00
2023-01-18 22:52:25 +01:00
private async Task<bool> MatchActively(IReadOnlyCollection<ListedUser> listedUsers, Dictionary<ulong, Asset> ourInventory, IReadOnlyCollection<Asset.EType> acceptedMatchableTypes) {
if ((listedUsers == null) || (listedUsers.Count == 0)) {
throw new ArgumentNullException(nameof(listedUsers));
2021-11-10 21:23:24 +01:00
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
if ((ourInventory == null) || (ourInventory.Count == 0)) {
throw new ArgumentNullException(nameof(ourInventory));
2021-11-10 21:23:24 +01:00
}
2018-12-15 00:27:15 +01:00
if ((acceptedMatchableTypes == null) || (acceptedMatchableTypes.Count == 0)) {
throw new ArgumentNullException(nameof(acceptedMatchableTypes));
2021-11-10 21:23:24 +01:00
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
(Dictionary<(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity), Dictionary<ulong, uint>> ourFullState, Dictionary<(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity), Dictionary<ulong, uint>> ourTradableState) = Trading.GetDividedInventoryState(ourInventory.Values);
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
if (Trading.IsEmptyForMatching(ourFullState, ourTradableState)) {
// User doesn't have any more dupes in the inventory
Bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, $"{nameof(ourFullState)} || {nameof(ourTradableState)}"));
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2023-01-18 22:52:25 +01:00
return false;
2021-11-10 21:23:24 +01:00
}
2018-12-15 00:27:15 +01:00
HashSet<ulong> pendingMobileTradeOfferIDs = new();
2021-11-10 21:23:24 +01:00
byte maxTradeHoldDuration = ASF.GlobalConfig?.MaxTradeHoldDuration ?? GlobalConfig.DefaultMaxTradeHoldDuration;
2019-02-04 03:09:20 +01:00
byte failuresInRow = 0;
uint matchedSets = 0;
foreach (ListedUser listedUser in listedUsers.Where(listedUser => (listedUser.SteamID != Bot.SteamID) && acceptedMatchableTypes.Any(listedUser.MatchableTypes.Contains) && !Bot.IsBlacklistedFromTrades(listedUser.SteamID)).OrderByDescending(static listedUser => listedUser.MatchEverything).ThenBy(static listedUser => listedUser.TotalInventoryCount)) {
if (failuresInRow >= WebBrowser.MaxTries) {
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.WarningFailedWithError, $"{nameof(failuresInRow)} >= {WebBrowser.MaxTries}"));
break;
}
HashSet<(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity)> wantedSets = ourTradableState.Keys.Where(set => listedUser.MatchableTypes.Contains(set.Type)).ToHashSet();
2019-02-04 03:09:20 +01:00
2021-11-10 21:23:24 +01:00
if (wantedSets.Count == 0) {
continue;
}
2021-11-10 21:23:24 +01:00
Bot.ArchiLogger.LogGenericTrace($"{listedUser.SteamID}...");
byte? tradeHoldDuration = await Bot.ArchiWebHandler.GetCombinedTradeHoldDurationAgainstUser(listedUser.SteamID, listedUser.TradeToken).ConfigureAwait(false);
switch (tradeHoldDuration) {
2021-11-10 21:23:24 +01:00
case null:
Bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(tradeHoldDuration)));
2021-11-10 21:23:24 +01:00
continue;
case > 0 when (tradeHoldDuration.Value > maxTradeHoldDuration) || (tradeHoldDuration.Value > listedUser.MaxTradeHoldDuration):
Bot.ArchiLogger.LogGenericTrace($"{tradeHoldDuration.Value} > {maxTradeHoldDuration} || {listedUser.MaxTradeHoldDuration}");
2021-11-10 21:23:24 +01:00
continue;
}
HashSet<Asset> theirInventory = listedUser.Assets.Where(item => (!listedUser.MatchEverything || item.Tradable) && wantedSets.Contains((item.RealAppID, item.Type, item.Rarity)) && ((tradeHoldDuration.Value == 0) || !(item.Type is Asset.EType.FoilTradingCard or Asset.EType.TradingCard && CardsFarmer.SalesBlacklist.Contains(item.RealAppID)))).Select(static asset => asset.ToAsset()).ToHashSet();
2022-12-17 13:09:01 +01:00
if (theirInventory.Count == 0) {
continue;
}
2021-11-10 21:23:24 +01:00
HashSet<(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity)> skippedSetsThisUser = new();
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
Dictionary<(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity), Dictionary<ulong, uint>> theirTradableState = Trading.GetTradableInventoryState(theirInventory);
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
for (byte i = 0; i < Trading.MaxTradesPerAccount; i++) {
byte itemsInTrade = 0;
HashSet<(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity)> skippedSetsThisTrade = new();
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
Dictionary<ulong, uint> classIDsToGive = new();
Dictionary<ulong, uint> classIDsToReceive = new();
Dictionary<ulong, uint> fairClassIDsToGive = new();
Dictionary<ulong, uint> fairClassIDsToReceive = new();
2021-11-10 21:23:24 +01:00
foreach (((uint RealAppID, Asset.EType Type, Asset.ERarity Rarity) set, Dictionary<ulong, uint> ourFullItems) in ourFullState.Where(set => !skippedSetsThisUser.Contains(set.Key) && listedUser.MatchableTypes.Contains(set.Key.Type) && set.Value.Values.Any(static count => count > 1))) {
if (!ourTradableState.TryGetValue(set, out Dictionary<ulong, uint>? ourTradableItems) || (ourTradableItems.Count == 0)) {
// We may have no more tradable items from this set
2021-11-10 21:23:24 +01:00
continue;
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
if (!theirTradableState.TryGetValue(set, out Dictionary<ulong, uint>? theirTradableItems) || (theirTradableItems.Count == 0)) {
// They may have no more tradable items from this set
continue;
}
if (Trading.IsEmptyForMatching(ourFullItems, ourTradableItems)) {
// We may have no more matchable items from this set
2021-11-10 21:23:24 +01:00
continue;
}
2018-12-09 21:26:22 +01:00
// Those 2 collections are on user-basis since we can't be sure that the trade passes through (and therefore we need to keep original state in case of a failure)
2021-11-10 21:23:24 +01:00
Dictionary<ulong, uint> ourFullSet = new(ourFullItems);
Dictionary<ulong, uint> ourTradableSet = new(ourTradableItems);
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
bool match;
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
do {
match = false;
2021-11-10 21:23:24 +01:00
foreach ((ulong ourItem, uint ourFullAmount) in ourFullSet.Where(static item => item.Value > 1).OrderByDescending(static item => item.Value)) {
if (!ourTradableSet.TryGetValue(ourItem, out uint ourTradableAmount) || (ourTradableAmount == 0)) {
continue;
}
foreach ((ulong theirItem, uint theirTradableAmount) in theirTradableItems.OrderBy(item => ourFullSet.TryGetValue(item.Key, out uint ourAmountOfTheirItem) ? ourAmountOfTheirItem : 0)) {
if (ourFullSet.TryGetValue(theirItem, out uint ourAmountOfTheirItem) && (ourFullAmount <= ourAmountOfTheirItem + 1)) {
continue;
}
2021-11-10 21:23:24 +01:00
if (!listedUser.MatchEverything) {
// We have a potential match, let's check fairness for them
fairClassIDsToGive.TryGetValue(ourItem, out uint fairGivenAmount);
fairClassIDsToReceive.TryGetValue(theirItem, out uint fairReceivedAmount);
fairClassIDsToGive[ourItem] = ++fairGivenAmount;
fairClassIDsToReceive[theirItem] = ++fairReceivedAmount;
// Filter their inventory for the sets we're trading or have traded with this user
HashSet<Asset> fairFiltered = theirInventory.Where(item => ((item.RealAppID == set.RealAppID) && (item.Type == set.Type) && (item.Rarity == set.Rarity)) || skippedSetsThisTrade.Contains((item.RealAppID, item.Type, item.Rarity))).Select(static item => item.CreateShallowCopy()).ToHashSet();
// Copy list to HashSet<Steam.Asset>
HashSet<Asset> fairItemsToGive = Trading.GetTradableItemsFromInventory(ourInventory.Values.Where(item => ((item.RealAppID == set.RealAppID) && (item.Type == set.Type) && (item.Rarity == set.Rarity)) || skippedSetsThisTrade.Contains((item.RealAppID, item.Type, item.Rarity))).Select(static item => item.CreateShallowCopy()).ToHashSet(), fairClassIDsToGive.ToDictionary(static classID => classID.Key, static classID => classID.Value));
2021-11-10 21:23:24 +01:00
HashSet<Asset> fairItemsToReceive = Trading.GetTradableItemsFromInventory(fairFiltered.Select(static item => item.CreateShallowCopy()).ToHashSet(), fairClassIDsToReceive.ToDictionary(static classID => classID.Key, static classID => classID.Value));
// Actual check
2021-11-10 21:23:24 +01:00
if (!Trading.IsTradeNeutralOrBetter(fairFiltered, fairItemsToReceive, fairItemsToGive)) {
// Revert the changes
2021-11-10 21:23:24 +01:00
if (fairGivenAmount > 1) {
fairClassIDsToGive[ourItem] = fairGivenAmount - 1;
} else {
fairClassIDsToGive.Remove(ourItem);
}
2021-11-10 21:23:24 +01:00
if (fairReceivedAmount > 1) {
fairClassIDsToReceive[theirItem] = fairReceivedAmount - 1;
} else {
fairClassIDsToReceive.Remove(theirItem);
}
2018-12-09 21:26:22 +01:00
2021-11-10 21:23:24 +01:00
continue;
2018-12-09 21:26:22 +01:00
}
2021-11-10 21:23:24 +01:00
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
// Skip this set from the remaining of this round
skippedSetsThisTrade.Add(set);
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
// Update our state based on given items
classIDsToGive[ourItem] = classIDsToGive.TryGetValue(ourItem, out uint ourGivenAmount) ? ourGivenAmount + 1 : 1;
ourFullSet[ourItem] = ourFullAmount - 1; // We don't need to remove anything here because we can guarantee that ourItem.Value is at least 2
2021-11-10 21:23:24 +01:00
// Update our state based on received items
classIDsToReceive[theirItem] = classIDsToReceive.TryGetValue(theirItem, out uint ourReceivedAmount) ? ourReceivedAmount + 1 : 1;
ourFullSet[theirItem] = ourAmountOfTheirItem + 1;
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
if (ourTradableAmount > 1) {
ourTradableSet[ourItem] = ourTradableAmount - 1;
} else {
ourTradableSet.Remove(ourItem);
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
}
2021-11-10 21:23:24 +01:00
// Update their state based on taken items
if (theirTradableAmount > 1) {
theirTradableItems[theirItem] = theirTradableAmount - 1;
} else {
theirTradableItems.Remove(theirItem);
}
2021-11-10 21:23:24 +01:00
itemsInTrade += 2;
match = true;
break;
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
}
2021-11-10 21:23:24 +01:00
if (match) {
break;
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
}
2021-11-10 21:23:24 +01:00
} while (match && (itemsInTrade < Trading.MaxItemsPerTrade - 1));
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
if (itemsInTrade >= Trading.MaxItemsPerTrade - 1) {
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
break;
}
2021-11-10 21:23:24 +01:00
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
if (skippedSetsThisTrade.Count == 0) {
Bot.ArchiLogger.LogGenericTrace(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(skippedSetsThisTrade)));
2021-11-10 21:23:24 +01:00
break;
}
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
// Remove the items from inventories
HashSet<Asset> itemsToGive = Trading.GetTradableItemsFromInventory(ourInventory.Values, classIDsToGive);
HashSet<Asset> itemsToReceive = Trading.GetTradableItemsFromInventory(theirInventory, classIDsToReceive, true);
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
if ((itemsToGive.Count != itemsToReceive.Count) || !Trading.IsFairExchange(itemsToGive, itemsToReceive)) {
// Failsafe
2023-01-18 22:52:25 +01:00
throw new InvalidOperationException($"{nameof(itemsToGive)} && {nameof(itemsToReceive)}");
2021-11-10 21:23:24 +01:00
}
Bot.ArchiLogger.LogGenericInfo(string.Format(CultureInfo.CurrentCulture, Localization.Strings.MatchingFound, itemsToReceive.Count, listedUser.SteamID, listedUser.Nickname));
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
Bot.ArchiLogger.LogGenericTrace($"{Bot.SteamID} <- {string.Join(", ", itemsToReceive.Select(static item => $"{item.RealAppID}/{item.Type}/{item.Rarity}/{item.ClassID} #{item.Amount}"))} | {string.Join(", ", itemsToGive.Select(static item => $"{item.RealAppID}/{item.Type}/{item.Rarity}/{item.ClassID} #{item.Amount}"))} -> {listedUser.SteamID}");
2019-01-23 17:58:37 +01:00
2021-11-10 21:23:24 +01:00
(bool success, HashSet<ulong>? mobileTradeOfferIDs) = await Bot.ArchiWebHandler.SendTradeOffer(listedUser.SteamID, itemsToGive, itemsToReceive, listedUser.TradeToken, true).ConfigureAwait(false);
2018-12-15 00:27:15 +01:00
if (mobileTradeOfferIDs?.Count > 0) {
pendingMobileTradeOfferIDs.UnionWith(mobileTradeOfferIDs);
if (pendingMobileTradeOfferIDs.Count >= MaxTradeOffersActive) {
(bool twoFactorSuccess, IReadOnlyCollection<Confirmation>? handledConfirmations, _) = await Bot.Actions.HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EType.Trade, pendingMobileTradeOfferIDs, true).ConfigureAwait(false);
if (!twoFactorSuccess) {
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Localization.Strings.ActivelyMatchingSomeConfirmationsFailed, handledConfirmations?.Count ?? 0, pendingMobileTradeOfferIDs.Count));
}
pendingMobileTradeOfferIDs.Clear();
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
}
2021-11-10 21:23:24 +01:00
if (!success) {
// The user likely no longer has the items we need, this is fine, we can continue the matching with other ones
failuresInRow++;
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Localization.Strings.TradeOfferFailed, listedUser.SteamID, listedUser.Nickname));
2021-11-10 21:23:24 +01:00
break;
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
}
failuresInRow = 0;
Bot.ArchiLogger.LogGenericInfo(Strings.Success);
// Assume the trade offer has went through and was accepted, this will allow us to keep matching the same set with different users as if we've got what we wanted
foreach (Asset itemToGive in itemsToGive) {
if (!ourInventory.TryGetValue(itemToGive.AssetID, out Asset? item) || (itemToGive.Amount > item.Amount)) {
throw new InvalidOperationException(nameof(item));
}
if (itemToGive.Amount == item.Amount) {
ourInventory.Remove(itemToGive.AssetID);
} else {
item.Amount -= itemToGive.Amount;
}
if (!ourFullState.TryGetValue((itemToGive.RealAppID, itemToGive.Type, itemToGive.Rarity), out Dictionary<ulong, uint>? fullAmounts) || !fullAmounts.TryGetValue(itemToGive.ClassID, out uint fullAmount) || (itemToGive.Amount > fullAmount)) {
// We're giving items we don't even have?
throw new InvalidOperationException(nameof(fullAmounts));
}
if (itemToGive.Amount == fullAmount) {
fullAmounts.Remove(itemToGive.ClassID);
} else {
fullAmounts[itemToGive.ClassID] = fullAmount - itemToGive.Amount;
}
if (!ourTradableState.TryGetValue((itemToGive.RealAppID, itemToGive.Type, itemToGive.Rarity), out Dictionary<ulong, uint>? tradableAmounts) || !tradableAmounts.TryGetValue(itemToGive.ClassID, out uint tradableAmount) || (itemToGive.Amount > tradableAmount)) {
// We're giving items we don't even have?
throw new InvalidOperationException(nameof(tradableAmounts));
}
if (itemToGive.Amount == tradableAmount) {
tradableAmounts.Remove(itemToGive.ClassID);
} else {
tradableAmounts[itemToGive.ClassID] = tradableAmount - itemToGive.Amount;
}
}
// However, since this is only an assumption, we must mark newly acquired items as untradable so we're sure that they're not considered for trading, only for matching
foreach (Asset itemToReceive in itemsToReceive) {
if (ourInventory.TryGetValue(itemToReceive.AssetID, out Asset? item)) {
item.Tradable = false;
item.Amount += itemToReceive.Amount;
} else {
itemToReceive.Tradable = false;
ourInventory[itemToReceive.AssetID] = itemToReceive;
}
if (!ourFullState.TryGetValue((itemToReceive.RealAppID, itemToReceive.Type, itemToReceive.Rarity), out Dictionary<ulong, uint>? fullAmounts)) {
// We're receiving items from a set we don't even have?
throw new InvalidOperationException(nameof(fullAmounts));
}
if (!fullAmounts.TryGetValue(itemToReceive.ClassID, out uint fullAmount)) {
fullAmount = 0;
}
fullAmounts[itemToReceive.ClassID] = itemToReceive.Amount + fullAmount;
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
skippedSetsThisUser.UnionWith(skippedSetsThisTrade);
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
2021-11-10 21:23:24 +01:00
if (skippedSetsThisUser.Count == 0) {
continue;
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
}
matchedSets += (uint) skippedSetsThisUser.Count;
2021-11-10 21:23:24 +01:00
if (Trading.IsEmptyForMatching(ourFullState, ourTradableState)) {
// User doesn't have any more dupes in the inventory
break;
}
Implement ETradingPreferences.MatchActively This will probably need a lot more tests, tweaking and bugfixing, but basic logic is: - MatchActively added to TradingPreferences with value of 16 - User must also use SteamTradeMatcher, can't use MatchEverything - User must have statistics enabled and be eligible for being listed (no requirement of having 100 items minimum) Once all requirements are passed, statistics module will communicate with the listing and fetch match everything bots: - The matching will start in 1h since ASF start and will repeat every day (right now it starts in 1 minute to aid debugging). - Each matching is composed of up to 10 rounds maximum. - In each round ASF will fetch our inventory and inventory of listed bots in order to find MatchableTypes items to be matched. If match is found, offer is being sent and confirmed automatically. - Each set (composition of item type + appID it's from) can be matched in a single round only once, this is to minimize "items no longer available" as much as possible and also avoid a need to wait for each bot to react before sending all trades. - Round ends when we try to match a total of 20 bots, or we hit no items to match in consecutive 10 tries with 10 different bots. - If last round resulted in at least a single trade being sent, next round starts within 5 minutes since last one, otherwise matching ends and repeats the next day. We'll see how it works in practice, expect a lot of follow-up commits, unless I won't have anything to fix or improve.
2018-11-29 18:35:58 +01:00
}
if (pendingMobileTradeOfferIDs.Count > 0) {
(bool twoFactorSuccess, IReadOnlyCollection<Confirmation>? handledConfirmations, _) = await Bot.Actions.HandleTwoFactorAuthenticationConfirmations(true, Confirmation.EType.Trade, pendingMobileTradeOfferIDs, true).ConfigureAwait(false);
if (!twoFactorSuccess) {
Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Localization.Strings.ActivelyMatchingSomeConfirmationsFailed, handledConfirmations?.Count ?? 0, pendingMobileTradeOfferIDs.Count));
}
}
Bot.ArchiLogger.LogGenericInfo(string.Format(CultureInfo.CurrentCulture, Localization.Strings.ActivelyMatchingItemsRound, matchedSets));
2023-01-18 22:52:25 +01:00
return matchedSets > 0;
2021-11-10 21:23:24 +01:00
}
2018-09-08 00:46:40 +02:00
}