Skip to content

Commit

Permalink
fix: socket server for net6.0+
Browse files Browse the repository at this point in the history
  • Loading branch information
XeroxDev committed Feb 26, 2024
1 parent f62b660 commit 4328b96
Show file tree
Hide file tree
Showing 25 changed files with 278 additions and 178 deletions.
21 changes: 8 additions & 13 deletions YTMDesktopCompanion.Example/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,16 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#region
#region Setup

using System.Reflection;
using System.Text.Json;
// Set YOUR version (or fetch them from anywhere)
using Newtonsoft.Json;
using XeroxDev.YTMDesktop.Companion;
using XeroxDev.YTMDesktop.Companion.Settings;

#endregion

#region Setup

// Set YOUR version (or fetch them from anywhere)
var version = "1.0.0";

// Check if file ".token" exists (i store it for this in the temp folder)
// Check if file ".token" exists
var tokenPath = Path.Combine(Path.GetTempPath(), "ytmd-csharp-lib-test.token");
if (!File.Exists(tokenPath))
{
Expand Down Expand Up @@ -75,7 +70,7 @@
return;
}

Console.WriteLine(JsonSerializer.Serialize(metadata));
Console.WriteLine(JsonConvert.SerializeObject(metadata, Formatting.Indented));

// Example Rest Client usage

Expand Down Expand Up @@ -111,7 +106,7 @@

// Get the current state and print it
var state = await restClient.GetState();
Console.WriteLine(JsonSerializer.Serialize(state));
Console.WriteLine(JsonConvert.SerializeObject(state, Formatting.Indented));

// Pause current track
await restClient.Pause();
Expand All @@ -131,8 +126,8 @@
// Register events
socketClient.OnError += (sender, args) => Console.WriteLine($"Error: {args.Message}");
socketClient.OnConnectionChange += (sender, args) => Console.WriteLine($"Connection changed: {args}");
socketClient.OnStateChange += (sender, args) => Console.WriteLine(JsonSerializer.Serialize(args));
socketClient.OnPlaylistCreated += (sender, args) => Console.WriteLine(JsonSerializer.Serialize(args));
socketClient.OnStateChange += (sender, args) => Console.WriteLine(JsonConvert.SerializeObject(args, Formatting.Indented));
socketClient.OnPlaylistCreated += (sender, args) => Console.WriteLine(JsonConvert.SerializeObject(args, Formatting.Indented));
socketClient.OnPlaylistDeleted += (sender, args) => Console.WriteLine($"Playlist deleted: {args}");

// Connect to the server
Expand Down
14 changes: 11 additions & 3 deletions YTMDesktopCompanion.net472/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.HttpListener" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
Expand Down Expand Up @@ -211,7 +211,7 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ObjectModel" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
Expand Down Expand Up @@ -319,7 +319,7 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-8.0.0.2" newVersion="8.0.0.2" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.RegularExpressions" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
Expand Down Expand Up @@ -373,6 +373,14 @@
<assemblyIdentity name="System.Xml.XPath.XDocument" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
10 changes: 4 additions & 6 deletions YTMDesktopCompanion.net472/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@

using System;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
using XeroxDev.YTMDesktop.Companion;
using XeroxDev.YTMDesktop.Companion.Settings;
Expand Down Expand Up @@ -90,7 +88,7 @@ private static async Task Test()
return;
}

Console.WriteLine(JsonSerializer.Serialize(metadata));
Console.WriteLine(metadata.ToString());

// Example Rest Client usage

Expand Down Expand Up @@ -126,7 +124,7 @@ private static async Task Test()

// Get the current state and print it
var state = await restClient.GetState();
Console.WriteLine(JsonSerializer.Serialize(state));
Console.WriteLine(state.ToString());

// Pause current track
await restClient.Pause();
Expand All @@ -146,8 +144,8 @@ private static async Task Test()
// Register events
socketClient.OnError += (sender, args) => Console.WriteLine($"Error: {args.Message}");
socketClient.OnConnectionChange += (sender, args) => Console.WriteLine($"Connection changed: {args}");
socketClient.OnStateChange += (sender, args) => Console.WriteLine(JsonSerializer.Serialize(args));
socketClient.OnPlaylistCreated += (sender, args) => Console.WriteLine(JsonSerializer.Serialize(args));
socketClient.OnStateChange += (sender, args) => Console.WriteLine(args.ToString());
socketClient.OnPlaylistCreated += (sender, args) => Console.WriteLine(args.ToString());
socketClient.OnPlaylistDeleted += (sender, args) => Console.WriteLine($"Playlist deleted: {args}");

// Connect to the server
Expand Down
28 changes: 0 additions & 28 deletions YTMDesktopCompanion.net472/YTMDesktopCompanion.net472.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -34,38 +34,11 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.8.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="mscorlib" />
<Reference Include="System"/>
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Core"/>
<Reference Include="System.Data"/>
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Text.Encodings.Web, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Encodings.Web.8.0.0\lib\net462\System.Text.Encodings.Web.dll</HintPath>
</Reference>
<Reference Include="System.Text.Json, Version=8.0.0.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Json.8.0.2\lib\net462\System.Text.Json.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Xml"/>
</ItemGroup>
<ItemGroup>
Expand All @@ -80,7 +53,6 @@
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Expand Down
12 changes: 0 additions & 12 deletions YTMDesktopCompanion.net472/packages.config

This file was deleted.

19 changes: 7 additions & 12 deletions YTMDesktopCompanion.net6/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,13 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#region
#region Setup

using System.Reflection;
using System.Text.Json;
// Set YOUR version (or fetch them from anywhere)
using Newtonsoft.Json;
using XeroxDev.YTMDesktop.Companion;
using XeroxDev.YTMDesktop.Companion.Settings;

#endregion

#region Setup

// Set YOUR version (or fetch them from anywhere)
var version = "1.0.0";

// Check if file ".token" exists
Expand Down Expand Up @@ -75,7 +70,7 @@
return;
}

Console.WriteLine(JsonSerializer.Serialize(metadata));
Console.WriteLine(JsonConvert.SerializeObject(metadata, Formatting.Indented));

// Example Rest Client usage

Expand Down Expand Up @@ -111,7 +106,7 @@

// Get the current state and print it
var state = await restClient.GetState();
Console.WriteLine(JsonSerializer.Serialize(state));
Console.WriteLine(JsonConvert.SerializeObject(state, Formatting.Indented));

// Pause current track
await restClient.Pause();
Expand All @@ -131,8 +126,8 @@
// Register events
socketClient.OnError += (sender, args) => Console.WriteLine($"Error: {args.Message}");
socketClient.OnConnectionChange += (sender, args) => Console.WriteLine($"Connection changed: {args}");
socketClient.OnStateChange += (sender, args) => Console.WriteLine(JsonSerializer.Serialize(args));
socketClient.OnPlaylistCreated += (sender, args) => Console.WriteLine(JsonSerializer.Serialize(args));
socketClient.OnStateChange += (sender, args) => Console.WriteLine(JsonConvert.SerializeObject(args, Formatting.Indented));
socketClient.OnPlaylistCreated += (sender, args) => Console.WriteLine(JsonConvert.SerializeObject(args, Formatting.Indented));
socketClient.OnPlaylistDeleted += (sender, args) => Console.WriteLine($"Playlist deleted: {args}");

// Connect to the server
Expand Down
10 changes: 5 additions & 5 deletions YTMDesktopCompanion/Clients/RestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@

using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Newtonsoft.Json;
using XeroxDev.YTMDesktop.Companion.Constants;
using XeroxDev.YTMDesktop.Companion.Enums;
using XeroxDev.YTMDesktop.Companion.Exceptions;
Expand Down Expand Up @@ -158,7 +158,7 @@ private async Task<TResponse> SendGetRequest<TResponse>(string path, string toke
if (token != null) request.Headers.Add("Authorization", token);
try
{
request.Content = new StringContent(JsonSerializer.Serialize(body), System.Text.Encoding.UTF8, "application/json");
request.Content = new StringContent(JsonConvert.SerializeObject(body), System.Text.Encoding.UTF8, "application/json");
}
catch (Exception e)
{
Expand Down Expand Up @@ -190,7 +190,7 @@ private async Task<TResponse> SendRequest<TResponse>(HttpRequestMessage request)

if (!response.IsSuccessStatusCode)
{
var error = JsonSerializer.Deserialize<ErrorOutput>(content);
var error = JsonConvert.DeserializeObject<ErrorOutput>(content);
if (error == null)
{
throw new ApiException(new ErrorOutput
Expand All @@ -212,15 +212,15 @@ private async Task<TResponse> SendRequest<TResponse>(HttpRequestMessage request)
// Try parsing the response to ErrorOutput, if it's successful, throw an ApiException
try
{
var errorOutput = JsonSerializer.Deserialize<ErrorOutput>(content);
var errorOutput = JsonConvert.DeserializeObject<ErrorOutput>(content);
if (errorOutput?.Error != null && errorOutput.Message != null && errorOutput.StatusCode != null && errorOutput.Code != null) throw new ApiException(errorOutput);
}
catch (Exception e)
{
if (e is ApiException) throw;
}

return JsonSerializer.Deserialize<TResponse>(content);
return JsonConvert.DeserializeObject<TResponse>(content);
}

#region Commands
Expand Down
56 changes: 38 additions & 18 deletions YTMDesktopCompanion/Clients/SocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,13 @@
#region

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using H.Socket.IO;
using Newtonsoft.Json;
using SocketIOClient;
using SocketIOClient.Newtonsoft.Json;
using SocketIOClient.Transport;
using XeroxDev.YTMDesktop.Companion.Constants;
using XeroxDev.YTMDesktop.Companion.Enums;
using XeroxDev.YTMDesktop.Companion.Interfaces;
using XeroxDev.YTMDesktop.Companion.Models.Output;
Expand All @@ -34,15 +39,22 @@

namespace XeroxDev.YTMDesktop.Companion.Clients
{
/// <summary>
/// The socket client for the YTMDesktop Companion
/// </summary>
public class SocketClient : IGenericClient
{
private ConnectorSettings _settings;

/// <summary>
/// The socket client
/// </summary>
private SocketIoClient _client;
private SocketIO _client;

/// <summary>
/// The socket client for the YTMDesktop Companion
/// </summary>
/// <param name="settings">The settings for the socket client.</param>
public SocketClient(ConnectorSettings settings)
{
_settings = settings;
Expand Down Expand Up @@ -91,7 +103,7 @@ public void SetAuthToken(string token)
/// Useful for custom things that are not implemented in the library yet.
/// </summary>
/// <returns>The socket object</returns>
public SocketIoClient GetClient()
public SocketIO GetClient()
{
return _client;
}
Expand All @@ -113,21 +125,29 @@ public async Task Connect()

OnConnectionChange(this, ESocketState.Connecting);

_client = new SocketIoClient();

// _socket = new SocketIOClient.SocketIO($"http://{Settings.Host}:{Settings.Port}{Endpoints.Realtime}", new SocketIOOptions
// {
// Transport = TransportProtocol.WebSocket,
// Auth = Settings.Token
// });

_client.Connected += (sender, _) => OnConnectionChange(sender ?? this, ESocketState.Connected);
_client.Disconnected += (sender, _) => OnConnectionChange(sender ?? this, ESocketState.Disconnected);
_client.ExceptionOccurred += (sender, args) => OnError(sender ?? this, args.Exception);
_client.ErrorReceived += (sender, args) => OnError(sender ?? this, new Exception(args.ToString()));
_client.On<StateOutput>("state-update", data => OnStateChange(this, data));
_client.On<PlaylistOutput>("playlist-created", data => OnPlaylistCreated(this, data));
_client.On<string>("playlist-delete", data => OnPlaylistDeleted(this, data));
_client = new SocketIO($"http://{Settings.Host}:{Settings.Port}{Endpoints.Realtime}", new SocketIOOptions
{
Transport = TransportProtocol.WebSocket,
Auth = new Dictionary<string, string> { { "token", Settings.Token } }
});
_client.JsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
});

_client.OnConnected += (sender, _) => OnConnectionChange(sender ?? this, ESocketState.Connected);
_client.OnDisconnected += (sender, _) => OnConnectionChange(sender ?? this, ESocketState.Disconnected);
_client.OnError += (sender, args) => OnError(sender ?? this, new Exception(args));
_client.OnReconnectError += (sender, args) => OnError(sender ?? this, args);
_client.OnReconnectFailed += (sender, args) => OnConnectionChange(sender ?? this, ESocketState.Disconnected);
_client.OnReconnected += (sender, _) => OnConnectionChange(sender ?? this, ESocketState.Connected);
_client.OnReconnectAttempt += (sender, args) => OnConnectionChange(sender ?? this, ESocketState.Connecting);
_client.On("state-update", data => OnStateChange(this, data.GetValue<StateOutput>()));
_client.On("playlist-created", data => OnPlaylistCreated(this, data.GetValue<PlaylistOutput>()));
_client.On("playlist-delete", data => OnPlaylistDeleted(this, data.GetValue<string>()));

await _client.ConnectAsync();
}
catch (Exception ex)
{
Expand Down
4 changes: 4 additions & 0 deletions YTMDesktopCompanion/CompanionConnector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ namespace XeroxDev.YTMDesktop.Companion
/// </summary>
public class CompanionConnector
{
/// <summary>
/// The companion connector. This class is the main class of the library. It contains the rest and socket client.<br />
/// </summary>
/// <param name="settings">The settings for the rest and socket clients.</param>
public CompanionConnector(ConnectorSettings settings)
{
RestClient = new RestClient(settings);
Expand Down

0 comments on commit 4328b96

Please sign in to comment.