From f7dfec8b057109f400b3d8914d0b7f3026e075b6 Mon Sep 17 00:00:00 2001 From: Citrinate Date: Sat, 24 Feb 2024 17:50:29 -0500 Subject: [PATCH 01/10] Update ArchiSteamFarm to 6.0.0.2 --- ArchiSteamFarm | 2 +- FreePackages/Data/AppDetails.cs | 41 ++++++---- FreePackages/Data/BotCache.cs | 42 ++++++---- FreePackages/Data/CardApps.cs | 6 +- FreePackages/Data/FilterConfig.cs | 70 ++++++++-------- FreePackages/Data/FreeSubResponse.cs | 12 +-- FreePackages/Data/GlobalCache.cs | 13 ++- FreePackages/Data/Package.cs | 19 +++-- FreePackages/Data/PlaytestAccessResponse.cs | 15 ++-- FreePackages/Data/UserData.cs | 81 +++++++++++-------- FreePackages/FreePackages.cs | 28 +++---- .../IPC/Requests/QueueLicensesRequest.cs | 14 ++-- FreePackages/WebRequest.cs | 8 +- 13 files changed, 198 insertions(+), 153 deletions(-) diff --git a/ArchiSteamFarm b/ArchiSteamFarm index 716b253..7a13895 160000 --- a/ArchiSteamFarm +++ b/ArchiSteamFarm @@ -1 +1 @@ -Subproject commit 716b253a044c9560bea1e9a77cb34afede93c6a3 +Subproject commit 7a13895429f3161c0e32736cd3086c515e42464c diff --git a/FreePackages/Data/AppDetails.cs b/FreePackages/Data/AppDetails.cs index 21bab80..d335890 100644 --- a/FreePackages/Data/AppDetails.cs +++ b/FreePackages/Data/AppDetails.cs @@ -1,42 +1,51 @@ using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; namespace FreePackages { internal sealed class AppDetails { - [JsonProperty(PropertyName = "success", Required = Required.Always)] - internal bool Success = false; + [JsonInclude] + [JsonPropertyName("success")] + [JsonRequired] + internal bool Success { get; private init; } = false; - [JsonProperty(PropertyName = "data", Required = Required.Default)] - internal AppDetailsData? Data = null; + [JsonInclude] + [JsonPropertyName("data")] + internal AppDetailsData? Data { get; private init; } = null; [JsonConstructor] internal AppDetails() {} } internal sealed class AppDetailsData { - [JsonProperty(PropertyName = "is_free", Required = Required.Default)] - internal bool IsFree = false; + [JsonInclude] + [JsonPropertyName("is_free")] + internal bool IsFree { get; private init; } = false; - [JsonProperty(PropertyName = "packages", Required = Required.Default)] - internal HashSet Packages = new(); + [JsonInclude] + [JsonPropertyName("packages")] + internal HashSet Packages { get; private init; } = new(); - [JsonProperty(PropertyName = "release_date", Required = Required.Default)] - internal AppDetailsReleaseDate? ReleaseDate = null; + [JsonInclude] + [JsonPropertyName("release_date")] + internal AppDetailsReleaseDate? ReleaseDate { get; private init; } = null; + [JsonInclude] [JsonExtensionData] - internal Dictionary AdditionalData = new(); + internal Dictionary AdditionalData { get; private init; } = new(); [JsonConstructor] internal AppDetailsData() {} } internal sealed class AppDetailsReleaseDate { - [JsonProperty(PropertyName = "coming_soon", Required = Required.Default)] - internal bool ComingSoon = true; + [JsonInclude] + [JsonPropertyName("coming_soon")] + internal bool ComingSoon { get; private init; } = true; + [JsonInclude] [JsonExtensionData] - internal Dictionary AdditionalData = new(); + internal Dictionary AdditionalData { get; private init; } = new(); [JsonConstructor] internal AppDetailsReleaseDate() {} diff --git a/FreePackages/Data/BotCache.cs b/FreePackages/Data/BotCache.cs index 381e2bf..76aab3e 100644 --- a/FreePackages/Data/BotCache.cs +++ b/FreePackages/Data/BotCache.cs @@ -2,36 +2,44 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.Json.Serialization; using System.Threading.Tasks; using ArchiSteamFarm.Collections; using ArchiSteamFarm.Core; using ArchiSteamFarm.Helpers; +using ArchiSteamFarm.Helpers.Json; using ArchiSteamFarm.Localization; -using Newtonsoft.Json; using SteamKit2; namespace FreePackages { internal sealed class BotCache : SerializableFile { - [JsonProperty(Required = Required.DisallowNull)] - internal ConcurrentHashSet Packages { get; } = new(new PackageComparer()); + [JsonInclude] + [JsonDisallowNull] + internal ConcurrentHashSet Packages { get; private set; } = new(new PackageComparer()); - [JsonProperty(Required = Required.DisallowNull)] - internal ConcurrentHashSet Activations = new(); + [JsonInclude] + [JsonDisallowNull] + internal ConcurrentHashSet Activations { get; private set; } = new(); - [JsonProperty(Required = Required.DisallowNull)] - internal ConcurrentHashSet ChangedApps = new(); + [JsonInclude] + [JsonDisallowNull] + internal ConcurrentHashSet ChangedApps { get; private set; } = new(); - [JsonProperty(Required = Required.DisallowNull)] - internal ConcurrentHashSet ChangedPackages = new(); + [JsonInclude] + [JsonDisallowNull] + internal ConcurrentHashSet ChangedPackages { get; private set; } = new(); - [JsonProperty(Required = Required.DisallowNull)] - internal ConcurrentHashSet NewOwnedPackages = new(); + [JsonInclude] + [JsonDisallowNull] + internal ConcurrentHashSet NewOwnedPackages { get; private set; } = new(); - [JsonProperty(Required = Required.DisallowNull)] - internal ConcurrentHashSet SeenPackages = new(); + [JsonInclude] + [JsonDisallowNull] + internal ConcurrentHashSet SeenPackages { get; private set; } = new(); - [JsonProperty(Required = Required.DisallowNull)] - internal ConcurrentHashSet WaitlistedPlaytests = new(); + [JsonInclude] + [JsonDisallowNull] + internal ConcurrentHashSet WaitlistedPlaytests { get; private set; } = new(); [JsonConstructor] internal BotCache() { } @@ -44,6 +52,8 @@ internal BotCache(string filePath) : this() { FilePath = filePath; } + protected override Task Save() => Save(this); + internal static async Task CreateOrLoad(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException(nameof(filePath)); @@ -63,7 +73,7 @@ internal BotCache(string filePath) : this() { return null; } - botCache = JsonConvert.DeserializeObject(json); + botCache = json.ToJsonObject(); } catch (Exception e) { ASF.ArchiLogger.LogGenericException(e); diff --git a/FreePackages/Data/CardApps.cs b/FreePackages/Data/CardApps.cs index 7b569fd..2462281 100644 --- a/FreePackages/Data/CardApps.cs +++ b/FreePackages/Data/CardApps.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using ArchiSteamFarm.Core; using ArchiSteamFarm.Web.Responses; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace FreePackages { internal static class CardApps { @@ -46,7 +46,7 @@ private static async Task DoUpdate() { private sealed class Badges { [JsonExtensionData] - internal Dictionary Data = new(); + internal Dictionary Data = new(); } } } \ No newline at end of file diff --git a/FreePackages/Data/FilterConfig.cs b/FreePackages/Data/FilterConfig.cs index 3351ccb..7513858 100644 --- a/FreePackages/Data/FilterConfig.cs +++ b/FreePackages/Data/FilterConfig.cs @@ -1,59 +1,59 @@ using System; using System.Collections.Generic; -using Newtonsoft.Json; +using System.Text.Json.Serialization; namespace FreePackages { internal sealed class FilterConfig { - [JsonProperty(Required = Required.Default)] - internal bool ImportStoreFilters = false; + [JsonInclude] + internal bool ImportStoreFilters { get; set; } = false; - [JsonProperty(Required = Required.Default)] - internal HashSet Types = new(); + [JsonInclude] + internal HashSet Types { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal HashSet Categories = new(); + [JsonInclude] + internal HashSet Categories { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal HashSet Tags = new(); + [JsonInclude] + internal HashSet Tags { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal HashSet IgnoredTypes = new(); + [JsonInclude] + internal HashSet IgnoredTypes { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal HashSet IgnoredTags = new(); + [JsonInclude] + internal HashSet IgnoredTags { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal HashSet IgnoredCategories = new(); + [JsonInclude] + internal HashSet IgnoredCategories { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal HashSet IgnoredContentDescriptors = new(); + [JsonInclude] + internal HashSet IgnoredContentDescriptors { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal HashSet IgnoredAppIDs = new(); + [JsonInclude] + internal HashSet IgnoredAppIDs { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal bool IgnoreFreeWeekends = false; + [JsonInclude] + internal bool IgnoreFreeWeekends { get; set; } = false; - [JsonProperty(Required = Required.Default)] - internal uint MinReviewScore = 0; + [JsonInclude] + internal uint MinReviewScore { get; set; } = 0; - [JsonProperty(Required = Required.Default)] - internal HashSet Languages = new(); + [JsonInclude] + internal HashSet Languages { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal EPlaytestMode PlaytestMode = EPlaytestMode.None; + [JsonInclude] + internal EPlaytestMode PlaytestMode { get; set; } = EPlaytestMode.None; - [JsonProperty(Required = Required.Default)] - internal bool RequireAllTags = false; + [JsonInclude] + internal bool RequireAllTags { get; set; } = false; - [JsonProperty(Required = Required.Default)] - internal bool RequireAllCategories = false; + [JsonInclude] + internal bool RequireAllCategories { get; set; } = false; - [JsonProperty(Required = Required.Default)] - internal bool NoCostOnly = false; + [JsonInclude] + internal bool NoCostOnly { get; set; } = false; - [JsonProperty(Required = Required.Default)] - internal HashSet Systems = new(); + [JsonInclude] + internal HashSet Systems { get; set; } = new(); [JsonConstructor] internal FilterConfig() { } diff --git a/FreePackages/Data/FreeSubResponse.cs b/FreePackages/Data/FreeSubResponse.cs index 110cb15..43e4297 100644 --- a/FreePackages/Data/FreeSubResponse.cs +++ b/FreePackages/Data/FreeSubResponse.cs @@ -1,13 +1,15 @@ -using Newtonsoft.Json; +using System.Text.Json.Serialization; using SteamKit2; namespace FreePackages { public sealed class FreeSubResponse { - [JsonProperty(PropertyName = "Result")] - EResult Result; + [JsonInclude] + [JsonPropertyName("Result")] + public EResult Result { get; private init; } - [JsonProperty(PropertyName = "PurchaseResultDetail")] - EPurchaseResultDetail PurchaseResultDetail; + [JsonInclude] + [JsonPropertyName("PurchaseResultDetail")] + public EPurchaseResultDetail PurchaseResultDetail { get; private init; } public FreeSubResponse(EResult result, EPurchaseResultDetail purchaseResultDetail) { Result = result; diff --git a/FreePackages/Data/GlobalCache.cs b/FreePackages/Data/GlobalCache.cs index bd29791..1d744e8 100644 --- a/FreePackages/Data/GlobalCache.cs +++ b/FreePackages/Data/GlobalCache.cs @@ -1,24 +1,29 @@ using System; using System.IO; +using System.Text.Json.Serialization; using System.Threading.Tasks; using ArchiSteamFarm.Core; using ArchiSteamFarm.Helpers; +using ArchiSteamFarm.Helpers.Json; using ArchiSteamFarm.Localization; -using Newtonsoft.Json; namespace FreePackages { internal sealed class GlobalCache : SerializableFile { private static string SharedFilePath => Path.Combine(ArchiSteamFarm.SharedInfo.ConfigDirectory, $"{nameof(FreePackages)}.cache"); - [JsonProperty(Required = Required.DisallowNull)] - internal uint LastChangeNumber; + [JsonInclude] + [JsonRequired] + internal uint LastChangeNumber { get; private set; } public bool ShouldSerializeLastChangeNumber() => LastChangeNumber > 0; + [JsonConstructor] internal GlobalCache() { FilePath = SharedFilePath; } + protected override Task Save() => Save(this); + internal static async Task CreateOrLoad() { if (!File.Exists(SharedFilePath)) { return new GlobalCache(); @@ -34,7 +39,7 @@ internal GlobalCache() { return null; } - globalCache = JsonConvert.DeserializeObject(json); + globalCache = json.ToJsonObject(); } catch (Exception e) { ASF.ArchiLogger.LogGenericException(e); diff --git a/FreePackages/Data/Package.cs b/FreePackages/Data/Package.cs index 8f7fdd1..69ea6ec 100644 --- a/FreePackages/Data/Package.cs +++ b/FreePackages/Data/Package.cs @@ -1,15 +1,20 @@ using System; using System.Collections.Generic; -using Newtonsoft.Json; +using System.Text.Json.Serialization; namespace FreePackages { public sealed class Package { - [JsonProperty(Required = Required.DisallowNull)] - public EPackageType Type; - [JsonProperty(Required = Required.DisallowNull)] - public uint ID; - [JsonProperty(Required = Required.AllowNull)] - public ulong? StartTime = null; + [JsonInclude] + [JsonRequired] + public EPackageType Type { get; private init; } + + [JsonInclude] + [JsonRequired] + public uint ID { get; private init; } + + [JsonInclude] + [JsonRequired] + public ulong? StartTime { get; private init; } = null; [JsonConstructor] public Package(EPackageType type, uint id, ulong? startTime = null) { diff --git a/FreePackages/Data/PlaytestAccessResponse.cs b/FreePackages/Data/PlaytestAccessResponse.cs index 0d6d7fa..1b31dfe 100644 --- a/FreePackages/Data/PlaytestAccessResponse.cs +++ b/FreePackages/Data/PlaytestAccessResponse.cs @@ -1,13 +1,16 @@ - -using Newtonsoft.Json; +using System.Text.Json.Serialization; namespace FreePackages { internal sealed class PlaytestAccessResponse { - [JsonProperty(PropertyName = "granted", Required = Required.AllowNull)] - internal bool? Granted = null; + [JsonInclude] + [JsonPropertyName("granted")] + [JsonRequired] + internal bool? Granted { get; private init; } = null; - [JsonProperty(PropertyName = "success", Required = Required.Always)] - internal bool Success = false; + [JsonInclude] + [JsonPropertyName("success")] + [JsonRequired] + internal bool Success { get; private init; } = false; [JsonConstructor] internal PlaytestAccessResponse() {} diff --git a/FreePackages/Data/UserData.cs b/FreePackages/Data/UserData.cs index cb7d218..0affca6 100644 --- a/FreePackages/Data/UserData.cs +++ b/FreePackages/Data/UserData.cs @@ -1,41 +1,58 @@ using System; using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; namespace FreePackages { internal sealed class UserData { - [JsonProperty(PropertyName = "rgOwnedPackages", Required = Required.Always)] - internal HashSet OwnedPackages = new(); + [JsonInclude] + [JsonPropertyName("rgOwnedPackages")] + [JsonRequired] + internal HashSet OwnedPackages { get; private init; } = new(); - [JsonProperty(PropertyName = "rgOwnedApps", Required = Required.Always)] - internal HashSet OwnedApps = new(); + [JsonInclude] + [JsonPropertyName("rgOwnedApps")] + [JsonRequired] + internal HashSet OwnedApps { get; private init; } = new(); - [JsonProperty(PropertyName = "rgIgnoredApps", Required = Required.Always)] + [JsonInclude] + [JsonPropertyName("rgIgnoredApps")] + [JsonRequired] [JsonConverter(typeof(EmptyArrayOrDictionaryConverter))] - internal Dictionary IgnoredApps = new(); + internal Dictionary IgnoredApps { get; private init; } = new(); - [JsonProperty(PropertyName = "rgExcludedTags", Required = Required.Always)] - internal List ExcludedTags = new(); + [JsonInclude] + [JsonPropertyName("rgExcludedTags")] + [JsonRequired] + internal List ExcludedTags { get; private init; } = new(); - [JsonProperty(PropertyName = "rgExcludedContentDescriptorIDs", Required = Required.Always)] - internal HashSet ExcludedContentDescriptorIDs = new(); + [JsonInclude] + [JsonPropertyName("rgExcludedContentDescriptorIDs")] + [JsonRequired] + internal HashSet ExcludedContentDescriptorIDs { get; private init; } = new(); [JsonExtensionData] - internal Dictionary AdditionalData = new(); + [JsonInclude] + internal Dictionary AdditionalData { get; private init; } = new(); [JsonConstructor] internal UserData() {} } internal sealed class Tag { - [JsonProperty(PropertyName = "tagid", Required = Required.Always)] + [JsonInclude] + [JsonPropertyName("tagid")] + [JsonRequired] internal uint TagID = 0; - [JsonProperty(PropertyName = "name", Required = Required.Always)] + [JsonInclude] + [JsonPropertyName("name")] + [JsonRequired] internal string Name = ""; - [JsonProperty(PropertyName = "timestamp_added", Required = Required.Always)] + [JsonInclude] + [JsonPropertyName("timestamp_added")] + [JsonRequired] internal uint TimestampAdded = 0; [JsonConstructor] @@ -43,30 +60,26 @@ internal Tag() {} } // https://stackoverflow.com/questions/12221950/how-to-deserialize-object-that-can-be-an-array-or-a-dictionary-with-newtonsoft - public class EmptyArrayOrDictionaryConverter : JsonConverter { - public override bool CanConvert(Type objectType) { - return objectType.IsAssignableFrom(typeof(Dictionary)); - } + public class EmptyArrayOrDictionaryConverter : JsonConverter> { + public override Dictionary Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.StartObject) { + var dictionary = JsonSerializer.Deserialize>(ref reader, options); + if (dictionary == null) { + throw new JsonException(); + } - public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { - JToken token = JToken.Load(reader); - if (token.Type == JTokenType.Object) { - return token.ToObject(objectType, serializer); - } else if (token.Type == JTokenType.Array) { - if (!token.HasValues) { - // create empty dictionary - return Activator.CreateInstance(objectType); + return dictionary; + } else if (reader.TokenType == JsonTokenType.StartArray) { + reader.Read(); + if (reader.TokenType == JsonTokenType.EndArray) { + return new Dictionary(); } } - throw new JsonSerializationException("Object or empty array expected"); + throw new JsonException(); } - public override bool CanWrite { - get { return false; } - } - - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { + public override void Write(Utf8JsonWriter writer, Dictionary value, JsonSerializerOptions options) { throw new NotImplementedException(); } } diff --git a/FreePackages/FreePackages.cs b/FreePackages/FreePackages.cs index 3d10fc0..140dee4 100644 --- a/FreePackages/FreePackages.cs +++ b/FreePackages/FreePackages.cs @@ -5,9 +5,9 @@ using ArchiSteamFarm.Core; using ArchiSteamFarm.Steam; using ArchiSteamFarm.Plugins.Interfaces; -using Newtonsoft.Json.Linq; using SteamKit2; -using Newtonsoft.Json; +using System.Text.Json; +using ArchiSteamFarm.Helpers.Json; namespace FreePackages { [Export(typeof(IPlugin))] @@ -23,7 +23,7 @@ public Task OnLoaded() { public Task OnBotCommand(Bot bot, EAccess access, string message, string[] args, ulong steamID = 0) => Task.FromResult(Commands.Response(bot, access, steamID, message, args)); - public async Task OnASFInit(IReadOnlyDictionary? additionalConfigProperties = null) { + public async Task OnASFInit(IReadOnlyDictionary? additionalConfigProperties = null) { if (GlobalCache == null) { GlobalCache = await GlobalCache.CreateOrLoad().ConfigureAwait(false); } @@ -31,7 +31,7 @@ public async Task OnASFInit(IReadOnlyDictionary? additionalConfi CardApps.Update(); } - public async Task OnBotInitModules(Bot bot, IReadOnlyDictionary? additionalConfigProperties = null) { + public async Task OnBotInitModules(Bot bot, IReadOnlyDictionary? additionalConfigProperties = null) { if (additionalConfigProperties == null) { return; } @@ -40,35 +40,33 @@ public async Task OnBotInitModules(Bot bot, IReadOnlyDictionary? uint? packageLimit = null; List filterConfigs = new(); - foreach (KeyValuePair configProperty in additionalConfigProperties) { + foreach (KeyValuePair configProperty in additionalConfigProperties) { switch (configProperty.Key) { - case "EnableFreePackages" when configProperty.Value.Type == JTokenType.Boolean: { - if (configProperty.Value.ToObject()) { - isEnabled = true; - } + case "EnableFreePackages" when (configProperty.Value.ValueKind == JsonValueKind.True || configProperty.Value.ValueKind == JsonValueKind.False): { + isEnabled = configProperty.Value.GetBoolean(); bot.ArchiLogger.LogGenericInfo("Enable Free Packages : " + isEnabled.ToString()); break; } - case "FreePackagesPerHour" when configProperty.Value.Type == JTokenType.Integer: { - packageLimit = configProperty.Value.ToObject(); + case "FreePackagesPerHour" when configProperty.Value.ValueKind == JsonValueKind.Number: { + packageLimit = configProperty.Value.GetUInt32(); bot.ArchiLogger.LogGenericInfo("Free Packages Per Hour : " + packageLimit.ToString()); break; } case "FreePackagesFilter": { - FilterConfig? filter = configProperty.Value.ToObject(); + FilterConfig? filter = configProperty.Value.ToJsonObject(); if (filter != null) { - bot.ArchiLogger.LogGenericInfo("Free Packages Filter : " + JsonConvert.SerializeObject(filter)); + bot.ArchiLogger.LogGenericInfo("Free Packages Filter : " + JsonSerializer.Serialize(filter)); filterConfigs.Add(filter); } break; } case "FreePackagesFilters": { - List? filters = configProperty.Value.ToObject>(); + List? filters = configProperty.Value.ToJsonObject>(); if (filters != null) { - bot.ArchiLogger.LogGenericInfo("Free Packages Filters : " + JsonConvert.SerializeObject(filters)); + bot.ArchiLogger.LogGenericInfo("Free Packages Filters : " + JsonSerializer.Serialize(filters)); filterConfigs.AddRange(filters); } break; diff --git a/FreePackages/IPC/Requests/QueueLicensesRequest.cs b/FreePackages/IPC/Requests/QueueLicensesRequest.cs index 086a9e7..3e8507a 100644 --- a/FreePackages/IPC/Requests/QueueLicensesRequest.cs +++ b/FreePackages/IPC/Requests/QueueLicensesRequest.cs @@ -1,16 +1,16 @@ using System.Collections.Generic; -using Newtonsoft.Json; +using System.Text.Json.Serialization; namespace FreePackages.IPC { public sealed class QueueLicensesRequest { - [JsonProperty(Required = Required.Default)] - public HashSet? AppIDs = null; + [JsonInclude] + public HashSet? AppIDs { get; private init; } = null; - [JsonProperty(Required = Required.Default)] - public HashSet? PackageIDs = null; + [JsonInclude] + public HashSet? PackageIDs { get; private init; } = null; - [JsonProperty(Required = Required.Default)] - public bool UseFilter = true; + [JsonInclude] + public bool UseFilter { get; private init; } = true; [JsonConstructor] private QueueLicensesRequest() { } diff --git a/FreePackages/WebRequest.cs b/FreePackages/WebRequest.cs index 19d502d..bbdaade 100644 --- a/FreePackages/WebRequest.cs +++ b/FreePackages/WebRequest.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using ArchiSteamFarm.Core; using ArchiSteamFarm.Steam; using ArchiSteamFarm.Steam.Integration; using ArchiSteamFarm.Web.Responses; -using Newtonsoft.Json.Linq; using SteamKit2; namespace FreePackages { @@ -28,9 +28,9 @@ internal static class WebRequest { await AppDetailsSemaphore.WaitAsync().ConfigureAwait(false); try { Uri request = new(ArchiWebHandler.SteamStoreURL, String.Format("/api/appdetails/?appids={0}", appID)); - ObjectResponse? appDetailsResponse = await bot.ArchiWebHandler.UrlGetToJsonObjectWithSession(request).ConfigureAwait(false); + ObjectResponse? appDetailsResponse = await bot.ArchiWebHandler.UrlGetToJsonObjectWithSession(request).ConfigureAwait(false); - return appDetailsResponse?.Content?.Properties().First().Value.ToObject(); + return JsonSerializer.Deserialize(appDetailsResponse?.Content?[appID.ToString()]); } finally { Utilities.InBackground( async() => { From 6791ae751d95924265e95221b789c26d7da313cb Mon Sep 17 00:00:00 2001 From: Citrinate Date: Sat, 24 Feb 2024 20:07:36 -0500 Subject: [PATCH 02/10] Update Tests --- FreePackages.Tests/Apps.cs | 8 ++++---- FreePackages.Tests/Filters.cs | 14 +++++++------- FreePackages.Tests/Packages.cs | 6 +++--- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/FreePackages.Tests/Apps.cs b/FreePackages.Tests/Apps.cs index 5fb20e9..a7d3a76 100644 --- a/FreePackages.Tests/Apps.cs +++ b/FreePackages.Tests/Apps.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.IO; +using ArchiSteamFarm.Helpers.Json; using Microsoft.IdentityModel.Tokens; using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; using SteamKit2; namespace FreePackages.Tests; @@ -15,13 +15,13 @@ public class Apps { [TestInitialize] public void InitializePackageFilter () { PackageFilter = new PackageFilter(new BotCache(), new List()); - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_empty.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_empty.json").ToJsonObject()); PackageFilter.Country = "FOO"; } [TestCleanup] public void CleanupPackageFilter() { - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_empty.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_empty.json").ToJsonObject()); PackageFilter.Country = "FOO"; } @@ -51,7 +51,7 @@ public void CanDetectAvailableAppByState() { [TestMethod] public void CanDetectRedeemableAppWithAppRequirement() { var app = new FilterableApp(KeyValue.LoadAsText("app_with_required_app.txt")); - var userData = JsonConvert.DeserializeObject(File.ReadAllText("userdata_empty.json")); + var userData = File.ReadAllText("userdata_empty.json").ToJsonObject(); userData.OwnedApps.Add(1086940); PackageFilter.UpdateUserData(userData); diff --git a/FreePackages.Tests/Filters.cs b/FreePackages.Tests/Filters.cs index 8cff176..b3dd87f 100644 --- a/FreePackages.Tests/Filters.cs +++ b/FreePackages.Tests/Filters.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.IO; +using ArchiSteamFarm.Helpers.Json; using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; using SteamKit2; namespace FreePackages.Tests; @@ -15,13 +15,13 @@ public class Filters { [TestInitialize] public void InitializePackageFilter () { PackageFilter = new PackageFilter(new BotCache(), new List()); - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_empty.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_empty.json").ToJsonObject()); Filter = new FilterConfig(); } [TestCleanup] public void CleanupPackageFilter() { - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_empty.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_empty.json").ToJsonObject()); Filter = new FilterConfig(); } @@ -308,15 +308,15 @@ public void CanFilterByStoreData() { Assert.IsFalse(PackageFilter.IsAppIgnoredByFilter(app, Filter)); - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_with_ignored_apps.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_with_ignored_apps.json").ToJsonObject()); Assert.IsTrue(PackageFilter.IsAppIgnoredByFilter(app, Filter)); - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_with_excluded_tags.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_with_excluded_tags.json").ToJsonObject()); Assert.IsTrue(PackageFilter.IsAppIgnoredByFilter(app, Filter)); - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_with_excluded_content_descriptors.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_with_excluded_content_descriptors.json").ToJsonObject()); Assert.IsTrue(PackageFilter.IsAppIgnoredByFilter(app, Filter)); } @@ -333,7 +333,7 @@ public void CanUseMultipleFilters() { filterB.Types.Add("Game"); var packageFilter = new PackageFilter(new BotCache(), new List() { filterA, filterB }); - packageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_empty.json"))); + packageFilter.UpdateUserData(File.ReadAllText("userdata_empty.json").ToJsonObject()); Assert.IsFalse(packageFilter.IsAppWantedByFilter(app, filterA)); Assert.IsTrue(packageFilter.IsAppIgnoredByFilter(app, filterA)); diff --git a/FreePackages.Tests/Packages.cs b/FreePackages.Tests/Packages.cs index ba613ba..7e158d6 100644 --- a/FreePackages.Tests/Packages.cs +++ b/FreePackages.Tests/Packages.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.IO; +using ArchiSteamFarm.Helpers.Json; using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; using SteamKit2; namespace FreePackages.Tests; @@ -14,13 +14,13 @@ public class Packages { [TestInitialize] public void InitializePackageFilter () { PackageFilter = new PackageFilter(new BotCache(), new List()); - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_empty.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_empty.json").ToJsonObject()); PackageFilter.Country = "FOO"; } [TestCleanup] public void CleanupPackageFilter() { - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_empty.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_empty.json").ToJsonObject()); PackageFilter.Country = "FOO"; } From 00c17623e46c5a397292eb03d42cee0819b40b57 Mon Sep 17 00:00:00 2001 From: Citrinate Date: Mon, 26 Feb 2024 10:15:03 -0500 Subject: [PATCH 03/10] Convert WishlistOnly feature to STJ --- FreePackages.Tests/Filters.cs | 4 ++-- FreePackages/Data/FilterConfig.cs | 4 ++-- FreePackages/Data/UserData.cs | 12 ++++++++---- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/FreePackages.Tests/Filters.cs b/FreePackages.Tests/Filters.cs index 89597aa..4ee2fd9 100644 --- a/FreePackages.Tests/Filters.cs +++ b/FreePackages.Tests/Filters.cs @@ -406,11 +406,11 @@ public void CanFilterByWishlist() { Assert.IsFalse(PackageFilter.IsAppWantedByFilter(app, Filter)); - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_with_wishlist_apps.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_with_wishlist_apps.json").ToJsonObject()); Assert.IsTrue(PackageFilter.IsAppWantedByFilter(app, Filter)); - PackageFilter.UpdateUserData(JsonConvert.DeserializeObject(File.ReadAllText("userdata_with_followed_apps.json"))); + PackageFilter.UpdateUserData(File.ReadAllText("userdata_with_followed_apps.json").ToJsonObject()); Assert.IsTrue(PackageFilter.IsAppWantedByFilter(app, Filter)); } diff --git a/FreePackages/Data/FilterConfig.cs b/FreePackages/Data/FilterConfig.cs index da33c9b..dd6febe 100644 --- a/FreePackages/Data/FilterConfig.cs +++ b/FreePackages/Data/FilterConfig.cs @@ -55,8 +55,8 @@ internal sealed class FilterConfig { [JsonInclude] internal HashSet Systems { get; set; } = new(); - [JsonProperty(Required = Required.Default)] - internal bool WishlistOnly = false; + [JsonInclude] + internal bool WishlistOnly { get; set; } = false; [JsonConstructor] internal FilterConfig() { } diff --git a/FreePackages/Data/UserData.cs b/FreePackages/Data/UserData.cs index 5b580be..e601f22 100644 --- a/FreePackages/Data/UserData.cs +++ b/FreePackages/Data/UserData.cs @@ -31,11 +31,15 @@ internal sealed class UserData { [JsonRequired] internal HashSet ExcludedContentDescriptorIDs { get; private init; } = new(); - [JsonProperty(PropertyName = "rgWishlist", Required = Required.Always)] - internal HashSet WishlistedApps = new(); + [JsonInclude] + [JsonPropertyName("rgWishlist")] + [JsonRequired] + internal HashSet WishlistedApps { get; private init; } = new(); - [JsonProperty(PropertyName = "rgFollowedApps", Required = Required.Always)] - internal HashSet FollowedApps = new(); + [JsonInclude] + [JsonPropertyName("rgFollowedApps")] + [JsonRequired] + internal HashSet FollowedApps { get; private init; } = new(); [JsonExtensionData] [JsonInclude] From af4c7253308d19683b9fa3b1f273bff908991912 Mon Sep 17 00:00:00 2001 From: Citrinate Date: Mon, 26 Feb 2024 10:15:25 -0500 Subject: [PATCH 04/10] Update README.md --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index eec77c5..6d36f0a 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ By default, the plugin will attempt to activate all free non-playtest packages. "RequireAllTags": false, "RequireAllCategories": false, "ImportStoreFilters": false, + "WishlistOnly": false, "IgnoreFreeWeekends": false, "NoCostOnly": false, "PlaytestMode": 0, @@ -351,6 +352,12 @@ All filter options are explained below: --- +#### WishlistOnly + +`bool` type with default value of `false`. If set to `true`, packages must contain an app your account has wishlisted or followed on the Steam storefront or they will not be added to your account. + +--- + #### IgnoreFreeWeekends `bool` type with default value of `false`. Free weekend packages will be ignored if set to `true`. From 75b46dc86bb1723d559944f5f3c4d78b95f3f4ef Mon Sep 17 00:00:00 2001 From: Citrinate Date: Mon, 26 Feb 2024 21:15:18 -0500 Subject: [PATCH 05/10] Update ArchiSteamFarm to 6.0.0.3 --- ArchiSteamFarm | 2 +- FreePackages/Data/CardApps.cs | 3 ++- FreePackages/Handlers/PackageHandler.cs | 1 - FreePackages/Handlers/PackageQueue.cs | 18 +----------------- FreePackages/IPC/Api/FreePackagesController.cs | 10 +--------- 5 files changed, 5 insertions(+), 29 deletions(-) diff --git a/ArchiSteamFarm b/ArchiSteamFarm index 7a13895..e4c20df 160000 --- a/ArchiSteamFarm +++ b/ArchiSteamFarm @@ -1 +1 @@ -Subproject commit 7a13895429f3161c0e32736cd3086c515e42464c +Subproject commit e4c20df4a896209636078c7acf33fbcaa8ad35bc diff --git a/FreePackages/Data/CardApps.cs b/FreePackages/Data/CardApps.cs index 2462281..f7b201a 100644 --- a/FreePackages/Data/CardApps.cs +++ b/FreePackages/Data/CardApps.cs @@ -46,7 +46,8 @@ private static async Task DoUpdate() { private sealed class Badges { [JsonExtensionData] - internal Dictionary Data = new(); + [JsonInclude] + internal Dictionary Data { get; private init; } = new(); } } } \ No newline at end of file diff --git a/FreePackages/Handlers/PackageHandler.cs b/FreePackages/Handlers/PackageHandler.cs index a9c8351..1b1117b 100644 --- a/FreePackages/Handlers/PackageHandler.cs +++ b/FreePackages/Handlers/PackageHandler.cs @@ -44,7 +44,6 @@ internal static async Task AddHandler(Bot bot, List filterConfigs, try { if (filterConfigs.Any(filterConfig => filterConfig.PlaytestMode != EPlaytestMode.None)) { // Only allow 1 bot to request playtests - // int numBotsThatIncludePlaytests = Handlers.Values.Where(x => x.PackageFilter.FilterConfig.PlaytestMode != EPlaytestMode.None).Count(); int numBotsThatIncludePlaytests = Handlers.Values.Where(x => x.PackageFilter.FilterConfigs.Any(filterConfig => filterConfig.PlaytestMode != EPlaytestMode.None)).Count(); if (numBotsThatIncludePlaytests > 0) { filterConfigs.ForEach(filterConfig => filterConfig.PlaytestMode = EPlaytestMode.None); diff --git a/FreePackages/Handlers/PackageQueue.cs b/FreePackages/Handlers/PackageQueue.cs index 147057a..557a495 100644 --- a/FreePackages/Handlers/PackageQueue.cs +++ b/FreePackages/Handlers/PackageQueue.cs @@ -2,12 +2,10 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Reflection; using System.Threading; using System.Threading.Tasks; using ArchiSteamFarm.Core; using ArchiSteamFarm.Steam; -using ArchiSteamFarm.Steam.Integration; using SteamKit2; namespace FreePackages { @@ -19,14 +17,6 @@ internal sealed class PackageQueue : IDisposable { private const int DelayBetweenActivationsSeconds = 5; private readonly uint ActivationsPerHour = 40; private const uint MaxActivationsPerHour = 50; // Steam's imposed limit - internal static MethodInfo? AddFreeLicense; - - static PackageQueue() { - AddFreeLicense = typeof(ArchiWebHandler).GetMethods(BindingFlags.NonPublic|BindingFlags.Public|BindingFlags.Instance).FirstOrDefault(x => x.Name == "AddFreeLicense"); - if (AddFreeLicense == null) { - ASF.ArchiLogger.LogGenericError("Couldn't find ArchiWebHandler.AddFreeLicense method"); - } - } internal PackageQueue(Bot bot, BotCache botCache, uint? packageLimit) { Bot = bot; @@ -201,16 +191,10 @@ private async Task ClaimFreeApp(uint appID) { } private async Task ClaimFreeSub(uint subID) { - if (AddFreeLicense == null) { - return EResult.Invalid; - } - EResult result; EPurchaseResultDetail purchaseResult; try { - var res = (Task<(EResult, EPurchaseResultDetail)>) AddFreeLicense.Invoke(Bot.ArchiWebHandler, new object[]{subID})!; - await res; - (result, purchaseResult) = res.Result; + (result, purchaseResult) = await Bot.Actions.AddFreeLicensePackage(subID).ConfigureAwait(false); } catch (Exception e) { Bot.ArchiLogger.LogGenericException(e); diff --git a/FreePackages/IPC/Api/FreePackagesController.cs b/FreePackages/IPC/Api/FreePackagesController.cs index d7cac1a..00a71c6 100644 --- a/FreePackages/IPC/Api/FreePackagesController.cs +++ b/FreePackages/IPC/Api/FreePackagesController.cs @@ -164,18 +164,10 @@ public async Task> RequestFreeSubLicense(string bo return BadRequest(new GenericResponse(false, Strings.BotNotConnected)); } - if (PackageQueue.AddFreeLicense == null) { - return BadRequest(new GenericResponse(false, "Couldn't find ArchiWebHandler.AddFreeLicense method")); - } - EResult result; EPurchaseResultDetail purchaseResult; try { - var res = (Task<(EResult, EPurchaseResultDetail)>) PackageQueue.AddFreeLicense.Invoke(bot.ArchiWebHandler, new object[]{subID})!; - await res; - var a = res.Result; - - (result, purchaseResult) = res.Result; + (result, purchaseResult) = await bot.Actions.AddFreeLicensePackage(subID).ConfigureAwait(false); } catch (Exception e) { bot.ArchiLogger.LogGenericWarningException(e); From d942100b2b42e1b1a6fa15aa5ee918dbc047f5e5 Mon Sep 17 00:00:00 2001 From: Citrinate Date: Tue, 27 Feb 2024 18:41:08 -0500 Subject: [PATCH 06/10] Fix playtest status --- FreePackages/Data/PlaytestAccessResponse.cs | 4 ++-- FreePackages/Handlers/PackageQueue.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/FreePackages/Data/PlaytestAccessResponse.cs b/FreePackages/Data/PlaytestAccessResponse.cs index 1b31dfe..57a7594 100644 --- a/FreePackages/Data/PlaytestAccessResponse.cs +++ b/FreePackages/Data/PlaytestAccessResponse.cs @@ -5,12 +5,12 @@ internal sealed class PlaytestAccessResponse { [JsonInclude] [JsonPropertyName("granted")] [JsonRequired] - internal bool? Granted { get; private init; } = null; + internal int? Granted { get; private init; } = null; [JsonInclude] [JsonPropertyName("success")] [JsonRequired] - internal bool Success { get; private init; } = false; + internal int Success { get; private init; } = 0; [JsonConstructor] internal PlaytestAccessResponse() {} diff --git a/FreePackages/Handlers/PackageQueue.cs b/FreePackages/Handlers/PackageQueue.cs index 557a495..cf3d996 100644 --- a/FreePackages/Handlers/PackageQueue.cs +++ b/FreePackages/Handlers/PackageQueue.cs @@ -228,7 +228,7 @@ private async Task ClaimPlaytest(uint appID) { return EResult.Invalid; } - if (!response.Success) { + if (response.Success != 1) { // Not sure if/when this happens Bot.ArchiLogger.LogGenericInfo(string.Format("ID: playtest/{0} | Status: Failed", appID)); From 3d2505785b14112e07d115093ef30496079a76f9 Mon Sep 17 00:00:00 2001 From: Citrinate Date: Wed, 28 Feb 2024 14:45:39 -0500 Subject: [PATCH 07/10] Prepare PauseFreePackagesWhilePlaying feature for ASF6 --- FreePackages/FreePackages.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/FreePackages/FreePackages.cs b/FreePackages/FreePackages.cs index 72609de..9a11bb4 100644 --- a/FreePackages/FreePackages.cs +++ b/FreePackages/FreePackages.cs @@ -49,10 +49,8 @@ public async Task OnBotInitModules(Bot bot, IReadOnlyDictionary()) { - pauseWhilePlaying = true; - } + case "PauseFreePackagesWhilePlaying" when (configProperty.Value.ValueKind == JsonValueKind.True || configProperty.Value.ValueKind == JsonValueKind.False): { + pauseWhilePlaying = configProperty.Value.GetBoolean(); bot.ArchiLogger.LogGenericInfo("Pause Free Packages While Playing : " + isEnabled.ToString()); break; } From 86af6c949cb20b128e523b16bce2d7424c9b9a05 Mon Sep 17 00:00:00 2001 From: Citrinate Date: Fri, 1 Mar 2024 09:08:35 -0500 Subject: [PATCH 08/10] Version bump --- FreePackages/FreePackages.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FreePackages/FreePackages.csproj b/FreePackages/FreePackages.csproj index 4ff6adb..7e255ad 100644 --- a/FreePackages/FreePackages.csproj +++ b/FreePackages/FreePackages.csproj @@ -2,7 +2,7 @@ Citrinate - 1.4.1 + 1.4.2 enable latest net8.0 From 82d48ed222bfc9b3fa40651e80747b2c9ab92e34 Mon Sep 17 00:00:00 2001 From: Citrinate Date: Sun, 3 Mar 2024 10:56:04 -0500 Subject: [PATCH 09/10] Added support for ASFEnhance features --- FreePackages/AdapterBridge.cs | 57 +++++++++++++++++++++++++++++++++++ FreePackages/Commands.cs | 3 ++ FreePackages/FreePackages.cs | 20 +++++++++++- 3 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 FreePackages/AdapterBridge.cs diff --git a/FreePackages/AdapterBridge.cs b/FreePackages/AdapterBridge.cs new file mode 100644 index 0000000..09950d4 --- /dev/null +++ b/FreePackages/AdapterBridge.cs @@ -0,0 +1,57 @@ +using System; +using System.Reflection; +using ArchiSteamFarm.Core; + +// ASFEnhanced Adapter https://github.com/chr233/ASFEnhanceAdapterDemoPlugin + +namespace FreePackages; +internal static class AdapterBridge +{ + /// + /// 注册子模块 + /// + /// 插件名称 + /// 插件唯一标识符 + /// 命令前缀 + /// 自动更新仓库 + /// 命令处理函数 + /// + public static bool InitAdapter(string pluginName, string pluginId, string? cmdPrefix, string? repoName, MethodInfo? cmdHandler) + { + try + { + var adapterEndpoint = Assembly.Load("ASFEnhance").GetType("ASFEnhance._Adapter_.Endpoint"); + var registerModule = adapterEndpoint?.GetMethod("RegisterModule", BindingFlags.Static | BindingFlags.Public); + var pluinVersion = Assembly.GetExecutingAssembly().GetName().Version; + + if (registerModule != null && adapterEndpoint != null) + { + var result = registerModule?.Invoke(null, new object?[] { pluginName, pluginId, cmdPrefix, repoName, pluinVersion, cmdHandler }); + + if (result is string str) + { + if (str == pluginName) + { + return true; + } + else + { + ASF.ArchiLogger.LogGenericWarning(str); + } + } + } + } +#if DEBUG + catch (Exception ex) + { + ASF.ArchiLogger.LogGenericException(ex, "Community with ASFEnhance failed"); + } +#else + catch (Exception) + { + ASF.ArchiLogger.LogGenericDebug("Community with ASFEnhance failed"); + } +#endif + return false; + } +} diff --git a/FreePackages/Commands.cs b/FreePackages/Commands.cs index b4ef86d..52d32ec 100644 --- a/FreePackages/Commands.cs +++ b/FreePackages/Commands.cs @@ -22,6 +22,9 @@ internal static class Commands { switch (args.Length) { case 1: switch (args[0].ToUpperInvariant()) { + case "FREEPACKAGES" when access >= EAccess.FamilySharing: + return String.Format("{0} {1}", nameof(FreePackages), (typeof(FreePackages).Assembly.GetName().Version ?? new Version("0")).ToString()); + case "CLEARFREEPACKAGESQUEUE": return ResponseClearQueue(bot, access); diff --git a/FreePackages/FreePackages.cs b/FreePackages/FreePackages.cs index 9a11bb4..30756d0 100644 --- a/FreePackages/FreePackages.cs +++ b/FreePackages/FreePackages.cs @@ -8,6 +8,7 @@ using SteamKit2; using System.Text.Json; using ArchiSteamFarm.Helpers.Json; +using System.Reflection; namespace FreePackages { [Export(typeof(IPlugin))] @@ -15,13 +16,30 @@ public sealed class FreePackages : IASF, IBotModules, ISteamPICSChanges, IBotSte public string Name => nameof(FreePackages); public Version Version => typeof(FreePackages).Assembly.GetName().Version ?? new Version("0"); internal static GlobalCache? GlobalCache; + private bool ASFEnhanceEnabled = false; public Task OnLoaded() { ASF.ArchiLogger.LogGenericInfo("Free Packages ASF Plugin by Citrinate"); + + // ASFEnhanced Adapter https://github.com/chr233/ASFEnhanceAdapterDemoPlugin + var flag = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + var handler = typeof(Commands).GetMethod(nameof(Commands.Response), flag); + const string pluginId = nameof(FreePackages); + const string cmdPrefix = "FREEPACKAGES"; + const string repoName = "Citrinate/FreePackages"; + var registered = AdapterBridge.InitAdapter(Name, pluginId, cmdPrefix, repoName, handler); + ASFEnhanceEnabled = registered; + return Task.CompletedTask; } - public Task OnBotCommand(Bot bot, EAccess access, string message, string[] args, ulong steamID = 0) => Task.FromResult(Commands.Response(bot, access, steamID, message, args)); + public Task OnBotCommand(Bot bot, EAccess access, string message, string[] args, ulong steamID = 0) { + if (ASFEnhanceEnabled) { + return Task.FromResult(null); + } + + return Task.FromResult(Commands.Response(bot, access, steamID, message, args)); + } public async Task OnASFInit(IReadOnlyDictionary? additionalConfigProperties = null) { if (GlobalCache == null) { From acd1595c8b5d491dc189eee8a5f43980cc59990b Mon Sep 17 00:00:00 2001 From: Citrinate Date: Sun, 3 Mar 2024 12:03:12 -0500 Subject: [PATCH 10/10] Formatting --- FreePackages/AdapterBridge.cs | 69 +++++++++++------------------------ 1 file changed, 22 insertions(+), 47 deletions(-) diff --git a/FreePackages/AdapterBridge.cs b/FreePackages/AdapterBridge.cs index 09950d4..78f3840 100644 --- a/FreePackages/AdapterBridge.cs +++ b/FreePackages/AdapterBridge.cs @@ -5,53 +5,28 @@ // ASFEnhanced Adapter https://github.com/chr233/ASFEnhanceAdapterDemoPlugin namespace FreePackages; -internal static class AdapterBridge -{ - /// - /// 注册子模块 - /// - /// 插件名称 - /// 插件唯一标识符 - /// 命令前缀 - /// 自动更新仓库 - /// 命令处理函数 - /// - public static bool InitAdapter(string pluginName, string pluginId, string? cmdPrefix, string? repoName, MethodInfo? cmdHandler) - { - try - { - var adapterEndpoint = Assembly.Load("ASFEnhance").GetType("ASFEnhance._Adapter_.Endpoint"); - var registerModule = adapterEndpoint?.GetMethod("RegisterModule", BindingFlags.Static | BindingFlags.Public); - var pluinVersion = Assembly.GetExecutingAssembly().GetName().Version; +internal static class AdapterBridge { + public static bool InitAdapter(string pluginName, string pluginId, string? cmdPrefix, string? repoName, MethodInfo? cmdHandler) { + try { + var adapterEndpoint = Assembly.Load("ASFEnhance").GetType("ASFEnhance._Adapter_.Endpoint"); + var registerModule = adapterEndpoint?.GetMethod("RegisterModule", BindingFlags.Static | BindingFlags.Public); + var pluinVersion = Assembly.GetExecutingAssembly().GetName().Version; - if (registerModule != null && adapterEndpoint != null) - { - var result = registerModule?.Invoke(null, new object?[] { pluginName, pluginId, cmdPrefix, repoName, pluinVersion, cmdHandler }); + if (registerModule != null && adapterEndpoint != null) { + var result = registerModule?.Invoke(null, new object?[] { pluginName, pluginId, cmdPrefix, repoName, pluinVersion, cmdHandler }); - if (result is string str) - { - if (str == pluginName) - { - return true; - } - else - { - ASF.ArchiLogger.LogGenericWarning(str); - } - } - } - } -#if DEBUG - catch (Exception ex) - { - ASF.ArchiLogger.LogGenericException(ex, "Community with ASFEnhance failed"); - } -#else - catch (Exception) - { - ASF.ArchiLogger.LogGenericDebug("Community with ASFEnhance failed"); - } -#endif - return false; - } + if (result is string str) { + if (str == pluginName) { + return true; + } else { + ASF.ArchiLogger.LogGenericWarning(str); + } + } + } + } catch (Exception ex) { + ASF.ArchiLogger.LogGenericException(ex, "Community with ASFEnhance failed"); + } + + return false; + } }