Skip to content

Commit

Permalink
Added NLog and updated msg type for RocketMessage to changed
Browse files Browse the repository at this point in the history
  • Loading branch information
Antonio Zhu committed Dec 2, 2022
1 parent 016b038 commit 3f85f48
Show file tree
Hide file tree
Showing 18 changed files with 190 additions and 66 deletions.
6 changes: 5 additions & 1 deletion src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NLog" Version="5.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Rocket.Chat.Net\Rocket.Chat.Net.csproj" />
</ItemGroup>
Expand Down
5 changes: 2 additions & 3 deletions src/Rocket.Chat.Net.Bot/RocketChatBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using NLog;
using Rocket.Chat.Net.Bot.Interfaces;
using Rocket.Chat.Net.Bot.Models;
using Rocket.Chat.Net.Driver;
using Rocket.Chat.Net.Interfaces;
using Rocket.Chat.Net.Loggers;
using Rocket.Chat.Net.Models;

public class RocketChatBot : IDisposable
Expand All @@ -23,7 +22,7 @@ public class RocketChatBot : IDisposable
public RocketChatBot(IRocketChatDriver driver, ILogger logger)
{
Driver = driver;
_logger = logger ?? new DummyLogger();
_logger = logger ?? NLog.LogManager.CreateNullLogger();

Driver.MessageReceived += DriverOnMessageReceived;
Driver.DdpReconnect += DriverOnDdpReconnect;
Expand Down
25 changes: 25 additions & 0 deletions src/Rocket.Chat.Net.Example/HelloWorldResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Rocket.Chat.Net.Bot;
using Rocket.Chat.Net.Bot.Interfaces;
using Rocket.Chat.Net.Bot.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rocket.Chat.Net.Example
{
public class HelloWorldResponse : IBotResponse
{
public bool CanRespond(ResponseContext context)
{
return ! context.Message.IsFromMyself && context.Message.Message.ToLower().StartsWith("hello");
}

public IEnumerable<IMessageResponse> GetResponse(ResponseContext context, RocketChatBot caller)
{
var message = context.Message;
yield return new BasicResponse("Hello world!", context.Message.RoomId);
}
}
}
6 changes: 6 additions & 0 deletions src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="NLog, Version=5.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\..\packages\NLog.5.1.0\lib\net46\NLog.dll</HintPath>
</Reference>
<Reference Include="RestSharp, Version=105.2.3.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\RestSharp.105.2.3\lib\net45\RestSharp.dll</HintPath>
<Private>True</Private>
Expand All @@ -65,12 +68,14 @@
<Private>True</Private>
</Reference>
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.IO.4.3.0\lib\net462\System.IO.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.IO.Compression" />
<Reference Include="System.Linq, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Linq.4.3.0\lib\net463\System.Linq.dll</HintPath>
<Private>True</Private>
Expand Down Expand Up @@ -144,6 +149,7 @@
<ItemGroup>
<Compile Include="DriverExample.cs" />
<Compile Include="GiphyResponse.cs" />
<Compile Include="HelloWorldResponse.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Expand Down
21 changes: 17 additions & 4 deletions src/Rocket.Chat.Net/Driver/DdpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using WebSocket4Net;
using SuperSocket.ClientEngine;
using System.Security.Authentication;
using NLog;

public class DdpClient : IDdpClient
{
Expand Down Expand Up @@ -61,7 +62,15 @@ private void SocketOnClosed(object sender, EventArgs eventArgs)
_logger.Debug("CLOSE");
if (SessionId != null && !IsDisposed)
{
ConnectAsync(CancellationToken.None).Wait();
// TODO: Fix reconnect
try
{
ConnectAsync(CancellationToken.None).Wait();
}
catch (Exception ex)
{
_logger.Error(ex);
}
}
}

Expand All @@ -70,10 +79,14 @@ private void SocketOnError(object sender, ErrorEventArgs errorEventArgs)
_logger.Info("ERROR: " + errorEventArgs?.Exception?.Message);
}

private void SocketOnOpened(object sender, EventArgs eventArgs)
private async void SocketOnOpened(object sender, EventArgs eventArgs)
{
_logger.Debug("OPEN");
await SendConnectRequest().ConfigureAwait(false);
}

public async Task SendConnectRequest()
{
_logger.Debug("Sending connection request");
const string ddpVersion = "1";
var request = new
Expand All @@ -87,7 +100,7 @@ private void SocketOnOpened(object sender, EventArgs eventArgs)
}
};

SendObjectAsync(request, CancellationToken.None).Wait();
await SendObjectAsync(request, CancellationToken.None).ConfigureAwait(false);
}

// TODO: Real time API implementieren
Expand Down Expand Up @@ -198,7 +211,7 @@ public async Task<string> SubscribeAndWaitAsync(string name, CancellationToken t
};

await SendObjectAsync(request, token).ConfigureAwait(false);
await WaitForIdOrReadyAsync(id, token).ConfigureAwait(false);
JObject result = await WaitForIdOrReadyAsync(id, token).ConfigureAwait(false);
return id;
}

Expand Down
15 changes: 7 additions & 8 deletions src/Rocket.Chat.Net/Driver/RocketChatDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,10 @@

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using NLog;
using Rocket.Chat.Net.Collections;
using Rocket.Chat.Net.Helpers;
using Rocket.Chat.Net.Interfaces;
using Rocket.Chat.Net.Loggers;
using Rocket.Chat.Net.Models;
using Rocket.Chat.Net.Models.Collections;
using Rocket.Chat.Net.Models.LoginOptions;
Expand All @@ -25,7 +24,7 @@

public class RocketChatDriver : IRocketChatDriver
{
private const string MessageTopic = "stream-messages";
private const string MessageTopic = "stream-room-messages";
private const int MessageSubscriptionLimit = 10;

private readonly IStreamCollectionDatabase _collectionDatabase;
Expand All @@ -50,7 +49,7 @@ public class RocketChatDriver : IRocketChatDriver
public RocketChatDriver(string url, bool useSsl, ILogger logger = null, bool isBot = true, JsonSerializerSettings jsonSerializerSettings = null)
{
IsBot = isBot;
_logger = logger ?? new DummyLogger();
_logger = logger ?? NLog.LogManager.CreateNullLogger();
_collectionDatabase = new StreamCollectionDatabase();

_logger.Info("Creating client...");
Expand Down Expand Up @@ -119,13 +118,13 @@ private void HandleStreamingCollections(string type, JObject data)
private void HandleRocketMessage(string type, JObject data)
{
var o = data.ToObject<SubscriptionResult<JObject>>(JsonSerializer);
var isMessage = type == "added" && o.Collection == MessageTopic && o.Fields["args"] != null;
var isMessage = type == "changed" && o.Collection == MessageTopic && o.Fields["args"] != null;
if (!isMessage)
{
return;
}

var messageRaw = o.Fields["args"][1];
var messageRaw = o.Fields["args"][0];
var message = messageRaw.ToObject<RocketMessage>(JsonSerializer);
message.IsBotMentioned = message.Mentions.Any(x => x.Id == UserId);
message.IsFromMyself = message.CreatedBy.Id == UserId;
Expand Down Expand Up @@ -198,7 +197,7 @@ public async Task SubscribeToRoomAsync(string roomId = null)
foreach (string id in ids)
{
_logger.Info($"Subscribing to Room: #{id}");
Task task = new Task(() => _client.SubscribeAsync(MessageTopic, TimeoutToken, id, MessageSubscriptionLimit.ToString()));
Task task = new Task(() => _client.SubscribeAndWaitAsync(MessageTopic, TimeoutToken, id, false));
tasks.Add(task);
task.Start();
}
Expand Down Expand Up @@ -667,7 +666,7 @@ public TypedStreamCollection<RoomInfo> GetRoomInfoCollection()

public async Task<MethodResult<IEnumerable<RoomInfo>>> GetAvailableRoomInfoCollection()
{
JObject result = await _client.CallAsync("rooms/get", CancellationToken.None, new object[] { 0 }).ConfigureAwait(false);
JObject result = await _client.CallAsync("rooms/get", CancellationToken.None, 0).ConfigureAwait(false);
return result.ToObject<MethodResult<IEnumerable<RoomInfo>>>(JsonSerializer);
}

Expand Down
15 changes: 0 additions & 15 deletions src/Rocket.Chat.Net/Interfaces/ILogger.cs

This file was deleted.

27 changes: 0 additions & 27 deletions src/Rocket.Chat.Net/Loggers/DummyLogger.cs

This file was deleted.

10 changes: 10 additions & 0 deletions src/Rocket.Chat.Net/Rocket.Chat.Net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,20 @@
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Remove="Models\Collections\RoomCollection.cs" />
<Compile Remove="Models\Collections\StreamCollection.cs" />
<Compile Remove="Models\Collections\StreamCollectionEventArgs.cs" />
<Compile Remove="Models\Collections\TypedStreamCollection.cs" />
<Compile Remove="Models\Collections\TypedStreamCollectionEventArgs.cs" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="NLog" Version="5.1.0" />
<PackageReference Include="Otp.NET" Version="1.2.2" />
<PackageReference Include="WebSocket4Net" Version="0.15.2" />
<PackageReference Include="WebsocketSharp.Standard2" Version="2022.4.16.1520" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
<HintPath>..\..\packages\FluentAssertions.4.9.1\lib\net45\FluentAssertions.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NLog, Version=5.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\..\packages\NLog.5.1.0\lib\net46\NLog.dll</HintPath>
</Reference>
<Reference Include="NSubstitute, Version=1.10.0.0, Culture=neutral, PublicKeyToken=92dd2e9066daa5ca, processorArchitecture=MSIL">
<HintPath>..\..\packages\NSubstitute.1.10.0.0\lib\net45\NSubstitute.dll</HintPath>
<Private>True</Private>
Expand All @@ -56,6 +59,8 @@
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
Expand Down
2 changes: 1 addition & 1 deletion test/Rocket.Chat.Net.Bot.Tests/RocketChatBotFacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using System.Threading.Tasks;

using FluentAssertions;

using NLog;
using NSubstitute;
using NSubstitute.ExceptionExtensions;

Expand Down
1 change: 1 addition & 0 deletions test/Rocket.Chat.Net.Bot.Tests/packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<package id="coveralls.net" version="0.6.0" targetFramework="net45" />
<package id="FluentAssertions" version="4.9.1" targetFramework="net45" />
<package id="Microsoft.Net.Compilers" version="1.2.2" targetFramework="net45" developmentDependency="true" />
<package id="NLog" version="5.1.0" targetFramework="net48" />
<package id="NSubstitute" version="1.10.0.0" targetFramework="net45" />
<package id="OpenCover" version="4.6.519" targetFramework="net45" />
<package id="xunit" version="2.1.0" targetFramework="net45" />
Expand Down
4 changes: 2 additions & 2 deletions test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class DdpFacts : IDisposable
private static readonly Fixture AutoFixture = new Fixture();

private readonly XUnitLogger _helper;
private readonly IWebSocketWrapper _socket = Substitute.For<IWebSocketWrapper>();
private readonly WebSocket _socket = Substitute.For<WebSocket>();

private CancellationToken TimeoutToken => CreateTimeoutToken();

Expand Down Expand Up @@ -116,7 +116,7 @@ public void On_error_log()
var exception = new Exception(message);

// Act
_socket.Error += Raise.Event<EventHandler<ErrorEventArgs>>(new object(), new ErrorEventArgs(exception));
_socket.Error += Raise.Event<EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>>(new object(), new SuperSocket.ClientEngine.ErrorEventArgs(exception));

// Assert
logger.Received().Info($"ERROR: {message}");
Expand Down
2 changes: 1 addition & 1 deletion test/Rocket.Chat.Net.Tests/Driver/MessagingFacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using FluentAssertions;

using Newtonsoft.Json.Linq;

using NLog;
using NSubstitute;

using Ploeh.AutoFixture;
Expand Down
6 changes: 6 additions & 0 deletions test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Rocket.Chat.Net.Tests.Helpers
{
public interface ILogger
{
}
}
1 change: 1 addition & 0 deletions test/Rocket.Chat.Net.Tests/Helpers/XUnitLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System;

using Rocket.Chat.Net.Interfaces;
using NLog;

using Xunit.Abstractions;

Expand Down
Loading

0 comments on commit 3f85f48

Please sign in to comment.