Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Citrinate committed Dec 18, 2024
1 parent 0e16c6f commit 2e6ecdb
Show file tree
Hide file tree
Showing 11 changed files with 230 additions and 229 deletions.
4 changes: 2 additions & 2 deletions CS2Interface/CSClient/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ internal async Task<List<InventoryItem>> GetCasketContents(ulong casket_id) {
throw new ClientException(EClientExceptionType.BadRequest, Strings.CasketNotFound);
}

uint? items_count = casket.GetAttribute("items count")?.ToUInt32();
uint? items_count = casket.Attributes?.GetValueOrDefault("items count")?.ToUInt32();
if (items_count == null) {
throw new ClientException(EClientExceptionType.Failed, Strings.CasketContentsUndefined);
}
Expand Down Expand Up @@ -422,7 +422,7 @@ internal async Task<bool> AddItemToCasket(ulong casket_id, ulong item_id) {
throw new ClientException(EClientExceptionType.BadRequest, Strings.CasketNotFound);
}

uint? items_count = casket.GetAttribute("items count")?.ToUInt32();
uint? items_count = casket.Attributes?.GetValueOrDefault("items count")?.ToUInt32();
if (items_count == null) {
throw new ClientException(EClientExceptionType.Failed, Strings.CasketContentsUndefined);
} else if (items_count == 1000) {
Expand Down
14 changes: 14 additions & 0 deletions CS2Interface/GameData/GameObject.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace CS2Interface {
public abstract class GameObject {
protected static bool ShouldSerializeAdditionalProperties { get; private set; } = true;
protected static bool ShouldSerializeDefs { get; private set; } = true ;

internal static void SetSerializationProperties(bool should_serialize_additional_properties, bool should_serialize_defs) {
ShouldSerializeAdditionalProperties = should_serialize_additional_properties;
ShouldSerializeDefs = should_serialize_defs;
}

protected abstract bool SetDefs();
protected abstract bool SetAdditionalProperties();
}
}
57 changes: 55 additions & 2 deletions CS2Interface/Helpers/IAttribute.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ArchiSteamFarm.Core;
using SteamKit2;
using SteamKit2.GC.CSGO.Internal;

namespace CS2Interface {
public abstract partial class IAttribute {
Expand All @@ -9,12 +15,12 @@ public abstract partial class IAttribute {

internal abstract float ToSingle();

public override abstract string ToString();
public abstract override string ToString();
}

public sealed class Attribute<TObject> : IAttribute where TObject : notnull {
internal override string Name { get; }
internal override Type Type { get => typeof(TObject); }
internal override Type Type => typeof(TObject);
internal TObject Value;

public Attribute(string name, TObject value) {
Expand All @@ -26,4 +32,51 @@ public Attribute(string name, TObject value) {
internal override float ToSingle() => (float) Convert.ChangeType(Value, typeof(float));
public override string ToString() => (string) Convert.ChangeType(Value, typeof(string));
}

public static class AttributeParser {
public static Dictionary<string, IAttribute>? Parse(List<CSOEconItemAttribute>? attributes) {
Dictionary<string, IAttribute> parsedAttributes = new();

if (attributes == null || attributes.Count == 0) {
return parsedAttributes;
}

foreach (CSOEconItemAttribute attribute in attributes) {
KeyValue? attribute_def = GameData.ItemsGame.GetDef("attributes", attribute.def_index.ToString());
if (attribute_def == null) {
return null;
}

string? attribute_name = attribute_def["name"].Value;
if (attribute_name == null) {
ASF.ArchiLogger.LogGenericError(String.Format("Missing name for attribute: {0}", attribute.def_index.ToString()));

return null;
}

switch (attribute_def["attribute_type"].Value) {
case "uint32":
case null when attribute_def["stored_as_integer"].Value == "1":
parsedAttributes.Add(attribute_name, new Attribute<uint>(attribute_name, BitConverter.ToUInt32(attribute.value_bytes.ToArray(), 0)));
break;

case "float":
case null when attribute_def["stored_as_integer"].Value == "0":
parsedAttributes.Add(attribute_name, new Attribute<float>(attribute_name, BitConverter.ToSingle(attribute.value_bytes.ToArray())));
break;

case "string":
parsedAttributes.Add(attribute_name, new Attribute<string>(attribute_name, Encoding.UTF8.GetString(attribute.value_bytes, 2, attribute.value_bytes.Length - 2)));
break;

case "vector":
default:
ASF.ArchiLogger.LogGenericError(String.Format("Unknown attribute type: {0}, value: {1}", attribute_def["attribute_type"].Value, Convert.ToBase64String(attribute.value_bytes)));
return null;
}
}

return parsedAttributes;
}
}
}
22 changes: 0 additions & 22 deletions CS2Interface/Helpers/KVConverter.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
Expand Down Expand Up @@ -54,25 +53,4 @@ public static void ConvertKVObjectToJson (ref Utf8JsonWriter writer, KeyValue vd
writer.WriteStringValue(vdf.Value);
}
}

public sealed class ListKVConverter : JsonConverter<List<KeyValue>> {
public override List<KeyValue> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
throw new NotImplementedException();
}

public override void Write(Utf8JsonWriter writer, List<KeyValue> value, JsonSerializerOptions options) {
if (value == null) {
writer.WriteNullValue();
return;
}

writer.WriteStartArray();

foreach (KeyValue data in value) {
KVConverter.ConvertKVObjectToJson(ref writer, data);
}

writer.WriteEndArray();
}
}
}
28 changes: 28 additions & 0 deletions CS2Interface/Helpers/KeyValueExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System.Linq;
using SteamKit2;

namespace CS2Interface {
public static class KeyValueExtensions {
public static void Merge(this KeyValue into, KeyValue from) {
foreach (KeyValue child in from.Children) {
if (child.Name == null) {
continue;
}

KeyValue? matchingChild = into.Children.FirstOrDefault(c => c.Name == child.Name);
if (matchingChild == null) {
into[child.Name] = child.Clone();
} else {
matchingChild.Merge(child);
}
}
}

public static KeyValue Clone(this KeyValue original) {
KeyValue copy = new KeyValue(original.Name, original.Value);
copy.Merge(original);

return copy;
}
}
}
8 changes: 4 additions & 4 deletions CS2Interface/IPC/Api/CS2InterfaceController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public async Task<ActionResult<GenericResponse>> InspectItem(
}

var item = new InspectItem(inspect, s, a, d, m);
Item.SetSerializationProperties(!minimal, showDefs);
GameObject.SetSerializationProperties(!minimal, showDefs);

return Ok(new GenericResponse<InspectItem>(true, item));
}
Expand Down Expand Up @@ -195,8 +195,8 @@ public ActionResult<GenericResponse> Inventory(
return BadRequest(new GenericResponse(false, "Inventory not loaded yet"));
}

List<InventoryItem> inventory = client.Inventory.Values.Where(x => x.IsValid()).ToList();
Item.SetSerializationProperties(!minimal, showDefs);
List<InventoryItem> inventory = client.Inventory.Values.Where(x => x.IsVisible()).ToList();
GameObject.SetSerializationProperties(!minimal, showDefs);

return Ok(new GenericResponse<List<InventoryItem>>(true, inventory));
}
Expand Down Expand Up @@ -237,7 +237,7 @@ public async Task<ActionResult<GenericResponse>> GetCrateContents(
return await HandleClientException(bot, e).ConfigureAwait(false);
}

Item.SetSerializationProperties(!minimal, showDefs);
GameObject.SetSerializationProperties(!minimal, showDefs);

return Ok(new GenericResponse<List<InventoryItem>>(true, contents));
}
Expand Down
7 changes: 2 additions & 5 deletions CS2Interface/Items/InspectItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,6 @@ internal InspectItem(CMsgGCCStrike15_v2_Client2GCEconPreviewDataBlockResponse it
d = param_d.ToString();
m = param_m.ToString();

SetAdditionalProperties();
}

new bool SetAdditionalProperties() {
DefIndex = ItemInfo.defindex;
PaintIndex = ItemInfo.paintindex;
StickerID = ItemInfo.stickers.FirstOrDefault()?.sticker_id;
Expand All @@ -36,7 +32,8 @@ internal InspectItem(CMsgGCCStrike15_v2_Client2GCEconPreviewDataBlockResponse it
Wear = (double) BitConverter.UInt32BitsToSingle(ItemInfo.paintwear);
}

return base.SetAdditionalProperties();
SetDefs();
SetAdditionalProperties();
}
}
}
Loading

0 comments on commit 2e6ecdb

Please sign in to comment.