-
Notifications
You must be signed in to change notification settings - Fork 3
fix: handle more streamlabels event variations #289
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
40ac844
Fixes StreamLabels.Underlying message
PedroCavaleiro 1fbc547
Fixes StreamLabelsMessageData
PedroCavaleiro 6acb2c2
Merge pull request #1 from PedroCavaleiro/fix-deserialziation
PedroCavaleiro 4be9f88
Makes the property CloudbotCounterDeaths nullable
PedroCavaleiro 8facada
Improves Streamlabs message deserialization
PedroCavaleiro 936fe7e
chore: cleanup
meenzen 1cad1f6
chore: add tests
meenzen 2eb478c
chore: cleanup
meenzen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
src/Streamlabs.SocketClient/Converters/FlexibleObjectConverter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
| using Streamlabs.SocketClient.InternalExtensions; | ||
|
|
||
| namespace Streamlabs.SocketClient.Converters; | ||
|
|
||
| /// <summary> | ||
| /// Provides a flexible JSON converter for <typeparamref name="T"/> that handles mixed input types. | ||
| /// This converter can deserialize <typeparamref name="T"/> from a standard JSON object, | ||
| /// an escaped JSON string (double-encoded), or gracefully handle plain non-JSON strings by returning null. | ||
| /// </summary> | ||
| /// <typeparam name="T">The reference type to deserialize into.</typeparam> | ||
| public class FlexibleObjectConverter<T> : JsonConverter<T> | ||
| where T : class | ||
| { | ||
| public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => | ||
| reader.TokenType switch | ||
| { | ||
| JsonTokenType.StartObject => JsonSerializer.Deserialize<T>(ref reader, options), | ||
| JsonTokenType.StartArray => JsonSerializer.Deserialize<T>(ref reader, options), | ||
| JsonTokenType.String => DeserializeString(ref reader, options), | ||
| _ => null, | ||
| }; | ||
|
|
||
| public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) => | ||
| JsonSerializer.Serialize(writer, value, options); | ||
|
|
||
| private static T? DeserializeString(ref Utf8JsonReader reader, JsonSerializerOptions options) | ||
| { | ||
| string? value = reader.GetString(); | ||
| if (value is null) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| if (!value.IsJsonObjectOrArray()) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| return JsonSerializer.Deserialize<T>(value.Trim(), options); | ||
| } | ||
| catch (JsonException) | ||
| { | ||
| return null; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
src/Streamlabs.SocketClient/Messages/DataTypes/DonationGoal.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| using System.Text.Json.Serialization; | ||
|
|
||
| namespace Streamlabs.SocketClient.Messages.DataTypes; | ||
|
|
||
| public sealed record DonationGoal { | ||
| [JsonPropertyName("title")] | ||
| public required string Title { get; init; } | ||
|
|
||
| [JsonPropertyName("currentAmount")] | ||
| public required string CurrentAmount { get; init; } | ||
|
|
||
| [JsonPropertyName("goalAmount")] | ||
| public required string GoalAmount { get; init; } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
100 changes: 100 additions & 0 deletions
100
test/Streamlabs.SocketClient.Tests/Converters/FlexibleObjectConverterTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
| using Streamlabs.SocketClient.Converters; | ||
|
|
||
| namespace Streamlabs.SocketClient.Tests.Converters; | ||
|
|
||
| [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods")] | ||
| public class FlexibleObjectConverterTests | ||
| { | ||
| private sealed class SampleClass | ||
| { | ||
| [JsonConverter(typeof(FlexibleObjectConverter<SamplePayload>))] | ||
| public SamplePayload? Payload { get; set; } | ||
| } | ||
|
|
||
| private sealed class SamplePayload | ||
| { | ||
| public string? Name { get; set; } | ||
| public int Count { get; set; } | ||
| } | ||
|
|
||
| [Test] | ||
| public async Task Read_ObjectToken_Deserializes() | ||
| { | ||
| // Arrange | ||
| var json = """{"Payload":{"Name":"Alpha","Count":3}}"""; | ||
|
|
||
| // Act | ||
| var result = JsonSerializer.Deserialize<SampleClass>(json); | ||
|
|
||
| // Assert | ||
| await Assert.That(result).IsNotNull(); | ||
| await Assert.That(result!.Payload).IsNotNull(); | ||
| await Assert.That(result.Payload!.Name).IsEqualTo("Alpha"); | ||
| await Assert.That(result.Payload.Count).IsEqualTo(3); | ||
| } | ||
|
|
||
| [Test] | ||
| public async Task Read_EscapedJsonString_Deserializes() | ||
| { | ||
| // Arrange | ||
| var json = """{"Payload":"{\"Name\":\"Beta\",\"Count\":7}"}"""; | ||
|
|
||
| // Act | ||
| var result = JsonSerializer.Deserialize<SampleClass>(json); | ||
|
|
||
| // Assert | ||
| await Assert.That(result).IsNotNull(); | ||
| await Assert.That(result!.Payload).IsNotNull(); | ||
| await Assert.That(result.Payload!.Name).IsEqualTo("Beta"); | ||
| await Assert.That(result.Payload.Count).IsEqualTo(7); | ||
| } | ||
|
|
||
| [Test] | ||
| public async Task Read_PlainString_ReturnsNull() | ||
| { | ||
| // Arrange | ||
| var json = """{"Payload":"just a plain string"}"""; | ||
|
|
||
| // Act | ||
| var result = JsonSerializer.Deserialize<SampleClass>(json); | ||
|
|
||
| // Assert | ||
| await Assert.That(result).IsNotNull(); | ||
| await Assert.That(result!.Payload).IsNull(); | ||
| } | ||
|
|
||
| [Test] | ||
| public async Task Read_MalformedJsonString_ReturnsNull() | ||
| { | ||
| // Arrange | ||
| var json = """{"Payload":"{not valid json}"}"""; | ||
|
|
||
| // Act | ||
| var result = JsonSerializer.Deserialize<SampleClass>(json); | ||
|
|
||
| // Assert | ||
| await Assert.That(result).IsNotNull(); | ||
| await Assert.That(result!.Payload).IsNull(); | ||
| } | ||
|
|
||
| [Test] | ||
| public async Task Write_SerializesNormally() | ||
| { | ||
| // Arrange | ||
| SampleClass sample = new() | ||
| { | ||
| Payload = new SamplePayload { Name = "Gamma", Count = 42 }, | ||
| }; | ||
|
|
||
| // Act | ||
| var json = JsonSerializer.Serialize(sample); | ||
|
|
||
| // Assert | ||
| await Assert.That(json).Contains("\"Payload\""); | ||
| await Assert.That(json).Contains("\"Name\":\"Gamma\""); | ||
| await Assert.That(json).Contains("\"Count\":42"); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Inconsistent exception handling between
StartObject/StartArrayandDeserializeString.DeserializeStringsilently returnsnullon anyJsonException, but theStartObjectandStartArraybranches propagate exceptions to the caller. Two realistic failure modes:FlexibleObjectConverter<TopDonator>(not a collection).JsonSerializer.Deserialize<TopDonator>(ref reader, options)on an array token would throw aJsonExceptionthat crashes the whole message deserialization.requiredfields on the target type.For the same resilience as
DeserializeString, wrap the object/array branches consistently:🛡️ Proposed fix — consistent exception handling
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.TokenType switch { - JsonTokenType.StartObject => JsonSerializer.Deserialize<T>(ref reader, options), - JsonTokenType.StartArray => JsonSerializer.Deserialize<T>(ref reader, options), + JsonTokenType.StartObject => TryDeserializeToken(ref reader, options), + JsonTokenType.StartArray => TryDeserializeToken(ref reader, options), JsonTokenType.String => DeserializeString(ref reader, options), _ => null, }; +private static T? TryDeserializeToken(ref Utf8JsonReader reader, JsonSerializerOptions options) +{ + try + { + return JsonSerializer.Deserialize<T>(ref reader, options); + } + catch (JsonException) + { + return null; + } +}🤖 Prompt for AI Agents