From 6ada7192fe6e92c982fa27b590b19af0c5091eaa Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Fri, 18 Nov 2022 16:25:58 +0100 Subject: [PATCH 01/14] Updated to .NET 4.8 --- .../Rocket.Chat.Net.Portability.Android.csproj | 3 +-- .../Rocket.Chat.Net.Portability.Net45.csproj | 2 +- src/Rocket.Chat.Net.Example/App.config | 2 +- src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj | 2 +- .../Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj | 2 +- test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj | 2 +- test/Rocket.Chat.Net.Tests/app.config | 2 +- 7 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/Portability/Rocket.Chat.Net.Portability.Android/Rocket.Chat.Net.Portability.Android.csproj b/src/Portability/Rocket.Chat.Net.Portability.Android/Rocket.Chat.Net.Portability.Android.csproj index 7248848..21bf6d7 100644 --- a/src/Portability/Rocket.Chat.Net.Portability.Android/Rocket.Chat.Net.Portability.Android.csproj +++ b/src/Portability/Rocket.Chat.Net.Portability.Android/Rocket.Chat.Net.Portability.Android.csproj @@ -14,8 +14,7 @@ 512 Resources\Resource.Designer.cs Off - True - v6.0 + v13.0 diff --git a/src/Portability/Rocket.Chat.Net.Portability.Net45/Rocket.Chat.Net.Portability.Net45.csproj b/src/Portability/Rocket.Chat.Net.Portability.Net45/Rocket.Chat.Net.Portability.Net45.csproj index f78229a..8507366 100644 --- a/src/Portability/Rocket.Chat.Net.Portability.Net45/Rocket.Chat.Net.Portability.Net45.csproj +++ b/src/Portability/Rocket.Chat.Net.Portability.Net45/Rocket.Chat.Net.Portability.Net45.csproj @@ -9,7 +9,7 @@ Properties Rocket.Chat.Net.Portability Rocket.Chat.Net.Portability - v4.5 + v4.8 512 diff --git a/src/Rocket.Chat.Net.Example/App.config b/src/Rocket.Chat.Net.Example/App.config index d1428ad..4bfa005 100644 --- a/src/Rocket.Chat.Net.Example/App.config +++ b/src/Rocket.Chat.Net.Example/App.config @@ -1,6 +1,6 @@ - + diff --git a/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj b/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj index f2aa1ae..b6607c7 100644 --- a/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj +++ b/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj @@ -10,7 +10,7 @@ Properties Rocket.Chat.Net.Example Rocket.Chat.Net.Example - v4.5 + v4.8 512 true diff --git a/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj b/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj index 5c61db7..00d7f9f 100644 --- a/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj +++ b/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj @@ -9,7 +9,7 @@ Properties Rocket.Chat.Net.Bot.Tests Rocket.Chat.Net.Bot.Tests - v4.5 + v4.8 512 {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 10.0 diff --git a/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj b/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj index a485778..9f61fea 100644 --- a/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj +++ b/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj @@ -9,7 +9,7 @@ Properties Rocket.Chat.Net.Tests Rocket.Chat.Net.Tests - v4.5 + v4.8 512 {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 10.0 diff --git a/test/Rocket.Chat.Net.Tests/app.config b/test/Rocket.Chat.Net.Tests/app.config index 33002c6..8a5b1a4 100644 --- a/test/Rocket.Chat.Net.Tests/app.config +++ b/test/Rocket.Chat.Net.Tests/app.config @@ -8,4 +8,4 @@ - + From 0b43185e347628874af2189622502af49e5bb16a Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Wed, 23 Nov 2022 15:10:47 +0100 Subject: [PATCH 02/14] Ported to .NET Standard 2.0 --- Rocket.Chat.Net.sln | 59 +++---- .../Resources/Resource.Designer.cs | 59 +++++++ src/Rocket.Chat.Net.Example/Program.cs | 17 +- src/Rocket.Chat.Net/Driver/DdpClient.cs | 7 +- .../Driver/RocketChatDriver.cs | 2 +- .../Driver/WebSocketWrapper.cs | 11 +- src/Rocket.Chat.Net/Helpers/EncodingHelper.cs | 19 ++- .../Interfaces/IWebSocketWrapper.cs | 7 +- .../Properties/AssemblyInfo.cs | 40 ----- src/Rocket.Chat.Net/Rocket.Chat.Net.csproj | 146 ++---------------- .../Rocket.Chat.Net.v2.ncrunchproject | 26 ---- src/Rocket.Chat.Net/packages.config | 6 - 12 files changed, 141 insertions(+), 258 deletions(-) delete mode 100644 src/Rocket.Chat.Net/Properties/AssemblyInfo.cs delete mode 100644 src/Rocket.Chat.Net/Rocket.Chat.Net.v2.ncrunchproject delete mode 100644 src/Rocket.Chat.Net/packages.config diff --git a/Rocket.Chat.Net.sln b/Rocket.Chat.Net.sln index cb76239..d5a3d0e 100644 --- a/Rocket.Chat.Net.sln +++ b/Rocket.Chat.Net.sln @@ -1,10 +1,8 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25123.0 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32929.385 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Chat.Net", "src\Rocket.Chat.Net\Rocket.Chat.Net.csproj", "{A078AEB9-5502-441C-B44A-FF4BBE007551}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Chat.Net.Tests", "test\Rocket.Chat.Net.Tests\Rocket.Chat.Net.Tests.csproj", "{55BAE418-9468-4A62-A6FA-F92ECBEAD8A5}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Chat.Net.Example", "src\Rocket.Chat.Net.Example\Rocket.Chat.Net.Example.csproj", "{EFB12AE6-706D-42B5-B2CC-54D60C4DC02B}" @@ -38,6 +36,8 @@ Project("{FF286327-C783-4F7A-AB73-9BCBAD0D4460}") = "Rocket.Chat.Net.NuGet", "sr EndProject Project("{FF286327-C783-4F7A-AB73-9BCBAD0D4460}") = "Rocket.Chat.Net.Bot.NuGet", "src\NuGet\Rocket.Chat.Net.Bot.NuGet\Rocket.Chat.Net.Bot.NuGet.nuproj", "{65631767-93F5-4F5B-875A-AA5FE4F6A80D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Chat.Net", "src\Rocket.Chat.Net\Rocket.Chat.Net.csproj", "{7EA92634-49F8-416D-9DBC-661A83EA425C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -54,30 +54,6 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Debug|ARM.ActiveCfg = Debug|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Debug|ARM.Build.0 = Debug|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Debug|x64.ActiveCfg = Debug|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Debug|x64.Build.0 = Debug|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Debug|x86.ActiveCfg = Debug|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Debug|x86.Build.0 = Debug|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Mono-4.5|Any CPU.ActiveCfg = Mono-4.5|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Mono-4.5|Any CPU.Build.0 = Mono-4.5|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Mono-4.5|ARM.ActiveCfg = Mono-4.5|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Mono-4.5|ARM.Build.0 = Mono-4.5|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Mono-4.5|x64.ActiveCfg = Mono-4.5|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Mono-4.5|x64.Build.0 = Mono-4.5|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Mono-4.5|x86.ActiveCfg = Mono-4.5|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Mono-4.5|x86.Build.0 = Mono-4.5|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Release|Any CPU.Build.0 = Release|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Release|ARM.ActiveCfg = Release|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Release|ARM.Build.0 = Release|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Release|x64.ActiveCfg = Release|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Release|x64.Build.0 = Release|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Release|x86.ActiveCfg = Release|Any CPU - {A078AEB9-5502-441C-B44A-FF4BBE007551}.Release|x86.Build.0 = Release|Any CPU {55BAE418-9468-4A62-A6FA-F92ECBEAD8A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {55BAE418-9468-4A62-A6FA-F92ECBEAD8A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {55BAE418-9468-4A62-A6FA-F92ECBEAD8A5}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -342,6 +318,30 @@ Global {65631767-93F5-4F5B-875A-AA5FE4F6A80D}.Release|x64.Build.0 = Release|Any CPU {65631767-93F5-4F5B-875A-AA5FE4F6A80D}.Release|x86.ActiveCfg = Release|Any CPU {65631767-93F5-4F5B-875A-AA5FE4F6A80D}.Release|x86.Build.0 = Release|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Debug|ARM.ActiveCfg = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Debug|ARM.Build.0 = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Debug|x64.ActiveCfg = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Debug|x64.Build.0 = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Debug|x86.ActiveCfg = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Debug|x86.Build.0 = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Mono-4.5|Any CPU.ActiveCfg = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Mono-4.5|Any CPU.Build.0 = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Mono-4.5|ARM.ActiveCfg = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Mono-4.5|ARM.Build.0 = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Mono-4.5|x64.ActiveCfg = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Mono-4.5|x64.Build.0 = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Mono-4.5|x86.ActiveCfg = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Mono-4.5|x86.Build.0 = Debug|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|Any CPU.Build.0 = Release|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|ARM.ActiveCfg = Release|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|ARM.Build.0 = Release|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|x64.ActiveCfg = Release|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|x64.Build.0 = Release|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|x86.ActiveCfg = Release|Any CPU + {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -357,4 +357,7 @@ Global {094585D5-62DF-445D-A8B3-88CB137B0205} = {C8A58FB6-F539-4E62-93F8-28B51E56D033} {65631767-93F5-4F5B-875A-AA5FE4F6A80D} = {C8A58FB6-F539-4E62-93F8-28B51E56D033} EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6989C4B9-1911-47A5-BA34-36E48C21CE4A} + EndGlobalSection EndGlobal diff --git a/src/Portability/Rocket.Chat.Net.Portability.Android/Resources/Resource.Designer.cs b/src/Portability/Rocket.Chat.Net.Portability.Android/Resources/Resource.Designer.cs index e69de29..f1b0184 100644 --- a/src/Portability/Rocket.Chat.Net.Portability.Android/Resources/Resource.Designer.cs +++ b/src/Portability/Rocket.Chat.Net.Portability.Android/Resources/Resource.Designer.cs @@ -0,0 +1,59 @@ +#pragma warning disable 1591 +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +[assembly: global::Android.Runtime.ResourceDesignerAttribute("Rocket.Chat.Net.Portability.Resource", IsApplication=false)] + +namespace Rocket.Chat.Net.Portability +{ + + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "13.0.0.73")] + public partial class Resource + { + + static Resource() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + public partial class Attribute + { + + static Attribute() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private Attribute() + { + } + } + + public partial class String + { + + // aapt resource value: 0x7F010000 + public static int ApplicationName = 2130771968; + + // aapt resource value: 0x7F010001 + public static int Hello = 2130771969; + + static String() + { + global::Android.Runtime.ResourceIdManager.UpdateIdValues(); + } + + private String() + { + } + } + } +} +#pragma warning restore 1591 diff --git a/src/Rocket.Chat.Net.Example/Program.cs b/src/Rocket.Chat.Net.Example/Program.cs index 0c5b535..b671ff0 100644 --- a/src/Rocket.Chat.Net.Example/Program.cs +++ b/src/Rocket.Chat.Net.Example/Program.cs @@ -1,6 +1,7 @@ namespace Rocket.Chat.Net.Example { using System; + using System.Linq.Expressions; using System.Threading.Tasks; using Rocket.Chat.Net.Bot; @@ -19,10 +20,10 @@ public static void Main() private static async Task MainAsync() { - const string username = "m@silvenga.com"; - const string password = "silverlight"; - const string rocketServerUrl = "dev0:3000"; // just the host and port - const bool useSsl = false; // Basically use ws or wss. + const string username = "test@softbauware.de"; + const string password = "hallotheo123"; + const string rocketServerUrl = "softbauware.rocket.chat:443"; // just the host and port + const bool useSsl = true; // Basically use ws or wss. // Create the bot - an abstraction of the driver RocketChatBot bot = new RocketChatBot(rocketServerUrl, useSsl); @@ -36,7 +37,13 @@ private static async Task MainAsync() Email = username, Password = password }; - await bot.LoginAsync(loginOption); + try + { + await bot.LoginAsync(loginOption); + } + catch (Exception e) { + Console.Write(e); + } // Start listening for messages await bot.SubscribeAsync(); diff --git a/src/Rocket.Chat.Net/Driver/DdpClient.cs b/src/Rocket.Chat.Net/Driver/DdpClient.cs index 0b4b959..1c8988a 100644 --- a/src/Rocket.Chat.Net/Driver/DdpClient.cs +++ b/src/Rocket.Chat.Net/Driver/DdpClient.cs @@ -12,7 +12,7 @@ using Rocket.Chat.Net.Interfaces; using Rocket.Chat.Net.Models; - using Rocket.Chat.Net.Portability.Websockets; + using WebSocket4Net; public class DdpClient : IDdpClient { @@ -34,7 +34,7 @@ public DdpClient(string baseUrl, bool useSsl, ILogger logger) var protocol = useSsl ? "wss" : "ws"; Url = $"{protocol}://{baseUrl}/websocket"; - _socket = new WebSocketWrapper(new PortableWebSocket(Url)); + _socket = new WebSocketWrapper(new WebSocket(Url)); AttachEvents(); } @@ -88,11 +88,12 @@ private void SocketOnOpened(object sender, EventArgs eventArgs) SendObjectAsync(request, CancellationToken.None).Wait(); } + // TODO: Real time API implementieren private void SocketOnMessage(object sender, PortableMessageReceivedEventArgs messageEventArgs) { var json = messageEventArgs.Message; var data = JObject.Parse(json); - _logger.Debug($"RECIEVED: {JsonConvert.SerializeObject(data, Formatting.Indented)}"); + _logger.Debug($"RECEIVED: {JsonConvert.SerializeObject(data, Formatting.Indented)}"); var isRocketMessage = data?["msg"] != null; if (isRocketMessage) diff --git a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs index fc30fa4..ebb7d34 100644 --- a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs +++ b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs @@ -246,7 +246,7 @@ public async Task> LoginAsync(ILoginOption loginOption return await LoginWithUsernameAsync(usernameLogin.Username, usernameLogin.Password).ConfigureAwait(false); } var resumeLogin = loginOption as ResumeLoginOption; - if (resumeLogin != null) + if (resumeLogin != null) { return await LoginResumeAsync(resumeLogin.Token).ConfigureAwait(false); } diff --git a/src/Rocket.Chat.Net/Driver/WebSocketWrapper.cs b/src/Rocket.Chat.Net/Driver/WebSocketWrapper.cs index 7ca303e..7c88fc0 100644 --- a/src/Rocket.Chat.Net/Driver/WebSocketWrapper.cs +++ b/src/Rocket.Chat.Net/Driver/WebSocketWrapper.cs @@ -3,18 +3,19 @@ using System; using Rocket.Chat.Net.Interfaces; - using Rocket.Chat.Net.Portability.Websockets; + using WebSocket4Net; + using SuperSocket.ClientEngine; public class WebSocketWrapper : IWebSocketWrapper { - private readonly PortableWebSocket _socket; + private readonly WebSocket _socket; - public WebSocketWrapper(PortableWebSocket socket) + public WebSocketWrapper(WebSocket socket) { _socket = socket; } - public event EventHandler MessageReceived + public event EventHandler MessageReceived { add { _socket.MessageReceived += value; } remove { _socket.MessageReceived -= value; } @@ -26,7 +27,7 @@ public event EventHandler Closed remove { _socket.Closed -= value; } } - public event EventHandler Error + public event EventHandler Error { add { _socket.Error += value; } remove { _socket.Error -= value; } diff --git a/src/Rocket.Chat.Net/Helpers/EncodingHelper.cs b/src/Rocket.Chat.Net/Helpers/EncodingHelper.cs index 1ae950d..59e0725 100644 --- a/src/Rocket.Chat.Net/Helpers/EncodingHelper.cs +++ b/src/Rocket.Chat.Net/Helpers/EncodingHelper.cs @@ -2,8 +2,8 @@ { using System; using System.IO; - - using Rocket.Chat.Net.Portability.Crypto; + using System.Text; + using System.Security.Cryptography; public static class EncodingHelper { @@ -11,8 +11,19 @@ public static class EncodingHelper public static string Sha256Hash(string value) { - var portableCrypto = new ShaHelper(); - return portableCrypto.Sha256Hash(value); + var builder = new StringBuilder(); + var encoding = Encoding.UTF8; + + using (var hash = SHA256.Create()) + { + var result = hash.ComputeHash(encoding.GetBytes(value)); + foreach (var b in result) + { + builder.Append(b.ToString("x2")); + } + } + + return builder.ToString(); } public static string ConvertToBase64(Stream stream) diff --git a/src/Rocket.Chat.Net/Interfaces/IWebSocketWrapper.cs b/src/Rocket.Chat.Net/Interfaces/IWebSocketWrapper.cs index f213ce5..339aca6 100644 --- a/src/Rocket.Chat.Net/Interfaces/IWebSocketWrapper.cs +++ b/src/Rocket.Chat.Net/Interfaces/IWebSocketWrapper.cs @@ -2,13 +2,14 @@ { using System; - using Rocket.Chat.Net.Portability.Websockets; + using WebSocket4Net; + using SuperSocket.ClientEngine; public interface IWebSocketWrapper { - event EventHandler MessageReceived; + event EventHandler MessageReceived; event EventHandler Closed; - event EventHandler Error; + event EventHandler Error; event EventHandler Opened; void Open(); void Close(); diff --git a/src/Rocket.Chat.Net/Properties/AssemblyInfo.cs b/src/Rocket.Chat.Net/Properties/AssemblyInfo.cs deleted file mode 100644 index 7b86be7..0000000 --- a/src/Rocket.Chat.Net/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. - -[assembly: AssemblyTitle("Rocket.Chat.Net")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Rocket.Chat.Net")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. - -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM - -[assembly: Guid("a078aeb9-5502-441c-b44a-ff4bbe007551")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] - -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: AssemblyInformationalVersion("1.0.0.0")] \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj b/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj index c03558a..e51ea90 100644 --- a/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj +++ b/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj @@ -1,141 +1,13 @@ - - - - + + - Debug - AnyCPU - {A078AEB9-5502-441C-B44A-FF4BBE007551} - Library - Properties - Rocket.Chat.Net - Rocket.Chat.Net - v4.5 - 512 - - - Profile111 - {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + netstandard2.0 - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - bin\Mono-4.5\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - v4.5 - - - - ..\..\packages\Newtonsoft.Json.8.0.3\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - + - - {662ce701-056d-420a-b03b-4f2613eea044} - Rocket.Chat.Net.Portability - + + + - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - \ No newline at end of file + + diff --git a/src/Rocket.Chat.Net/Rocket.Chat.Net.v2.ncrunchproject b/src/Rocket.Chat.Net/Rocket.Chat.Net.v2.ncrunchproject deleted file mode 100644 index 30815b1..0000000 --- a/src/Rocket.Chat.Net/Rocket.Chat.Net.v2.ncrunchproject +++ /dev/null @@ -1,26 +0,0 @@ - - true - 1000 - false - false - false - true - false - false - false - false - false - true - true - false - true - true - true - 60000 - - - - AutoDetect - STA - x86 - \ No newline at end of file diff --git a/src/Rocket.Chat.Net/packages.config b/src/Rocket.Chat.Net/packages.config deleted file mode 100644 index 263bd3b..0000000 --- a/src/Rocket.Chat.Net/packages.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file From 30c1de3f6b15d1602a3e4e2a7ee62f62a75f8083 Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Wed, 23 Nov 2022 15:33:53 +0100 Subject: [PATCH 03/14] updated Rocket.Chat.Net --- src/Rocket.Chat.Net/Driver/DdpClient.cs | 6 +++-- .../Interfaces/ILoginOption.cs | 15 ++++++++++- .../Models/LoginOptions/EmailLoginOption.cs | 25 ++++++++++++++++++- .../Models/LoginOptions/LdapLoginOption.cs | 24 ++++++++++++++++++ .../Models/LoginOptions/ResumeLoginOption.cs | 24 ++++++++++++++++++ .../LoginOptions/UsernameLoginOption.cs | 25 ++++++++++++++++++- 6 files changed, 114 insertions(+), 5 deletions(-) diff --git a/src/Rocket.Chat.Net/Driver/DdpClient.cs b/src/Rocket.Chat.Net/Driver/DdpClient.cs index 1c8988a..5d905be 100644 --- a/src/Rocket.Chat.Net/Driver/DdpClient.cs +++ b/src/Rocket.Chat.Net/Driver/DdpClient.cs @@ -14,6 +14,8 @@ using Rocket.Chat.Net.Models; using WebSocket4Net; + using SuperSocket.ClientEngine; + public class DdpClient : IDdpClient { private readonly ILogger _logger; @@ -63,7 +65,7 @@ private void SocketOnClosed(object sender, EventArgs eventArgs) } } - private void SocketOnError(object sender, PortableErrorEventArgs errorEventArgs) + private void SocketOnError(object sender, ErrorEventArgs errorEventArgs) { _logger.Info("ERROR: " + errorEventArgs?.Exception?.Message); } @@ -89,7 +91,7 @@ private void SocketOnOpened(object sender, EventArgs eventArgs) } // TODO: Real time API implementieren - private void SocketOnMessage(object sender, PortableMessageReceivedEventArgs messageEventArgs) + private void SocketOnMessage(object sender, MessageReceivedEventArgs messageEventArgs) { var json = messageEventArgs.Message; var data = JObject.Parse(json); diff --git a/src/Rocket.Chat.Net/Interfaces/ILoginOption.cs b/src/Rocket.Chat.Net/Interfaces/ILoginOption.cs index 413ddd7..26f627b 100644 --- a/src/Rocket.Chat.Net/Interfaces/ILoginOption.cs +++ b/src/Rocket.Chat.Net/Interfaces/ILoginOption.cs @@ -1,6 +1,19 @@ -namespace Rocket.Chat.Net.Interfaces +using OtpNet; + +namespace Rocket.Chat.Net.Interfaces { public interface ILoginOption { + Totp TOTPSeed + { + get; + set; + } + + string TOTPToken + { + get; + set; + } } } \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Models/LoginOptions/EmailLoginOption.cs b/src/Rocket.Chat.Net/Models/LoginOptions/EmailLoginOption.cs index a6ee176..0ffcc19 100644 --- a/src/Rocket.Chat.Net/Models/LoginOptions/EmailLoginOption.cs +++ b/src/Rocket.Chat.Net/Models/LoginOptions/EmailLoginOption.cs @@ -1,9 +1,15 @@ namespace Rocket.Chat.Net.Models.LoginOptions { + using OtpNet; using Rocket.Chat.Net.Interfaces; - + using System.Runtime.CompilerServices; + public class EmailLoginOption : ILoginOption { + + private Totp totpSeed; + private string totpToken; + /// /// Email of the user to login as. Should be in the format of user@example.com. /// @@ -13,5 +19,22 @@ public class EmailLoginOption : ILoginOption /// Plaintext password of the user. /// public string Password { get; set; } + public Totp TOTPSeed { + get => totpSeed ; + set => totpSeed = value; + } + + public string TOTPToken { + get + { + if (this.totpSeed != null) + totpToken = totpSeed.ComputeTotp(); + return totpToken; + } + set + { + totpToken = value; + } + } } } \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Models/LoginOptions/LdapLoginOption.cs b/src/Rocket.Chat.Net/Models/LoginOptions/LdapLoginOption.cs index c9d0e2b..f40ab7f 100644 --- a/src/Rocket.Chat.Net/Models/LoginOptions/LdapLoginOption.cs +++ b/src/Rocket.Chat.Net/Models/LoginOptions/LdapLoginOption.cs @@ -1,5 +1,6 @@ namespace Rocket.Chat.Net.Models.LoginOptions { + using OtpNet; using System.Diagnostics.CodeAnalysis; using Rocket.Chat.Net.Interfaces; @@ -7,6 +8,9 @@ [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")] public class LdapLoginOption : ILoginOption { + private Totp totpSeed; + private string totpToken; + /// /// Username of the user to login as. Do not include the domain in which this user resides. /// @@ -16,5 +20,25 @@ public class LdapLoginOption : ILoginOption /// Plaintext password of the user. /// public string Password { get; set; } + + public Totp TOTPSeed + { + get => totpSeed; + set => totpSeed = value; + } + + public string TOTPToken + { + get + { + if (this.totpSeed != null) + totpToken = totpSeed.ComputeTotp(); + return totpToken; + } + set + { + totpToken = value; + } + } } } \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Models/LoginOptions/ResumeLoginOption.cs b/src/Rocket.Chat.Net/Models/LoginOptions/ResumeLoginOption.cs index 44e1a9a..ccb90a0 100644 --- a/src/Rocket.Chat.Net/Models/LoginOptions/ResumeLoginOption.cs +++ b/src/Rocket.Chat.Net/Models/LoginOptions/ResumeLoginOption.cs @@ -1,5 +1,6 @@ namespace Rocket.Chat.Net.Models.LoginOptions { + using OtpNet; using System.Diagnostics.CodeAnalysis; using Rocket.Chat.Net.Interfaces; @@ -7,9 +8,32 @@ [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")] public class ResumeLoginOption : ILoginOption { + private Totp totpSeed; + private string totpToken; + /// /// Active login token given from a successful, previous login. /// public string Token { get; set; } + + public Totp TOTPSeed + { + get => totpSeed; + set => totpSeed = value; + } + + public string TOTPToken + { + get + { + if (this.totpSeed != null) + totpToken = totpSeed.ComputeTotp(); + return totpToken; + } + set + { + totpToken = value; + } + } } } \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Models/LoginOptions/UsernameLoginOption.cs b/src/Rocket.Chat.Net/Models/LoginOptions/UsernameLoginOption.cs index 01cecd7..aad4fc0 100644 --- a/src/Rocket.Chat.Net/Models/LoginOptions/UsernameLoginOption.cs +++ b/src/Rocket.Chat.Net/Models/LoginOptions/UsernameLoginOption.cs @@ -1,12 +1,15 @@ namespace Rocket.Chat.Net.Models.LoginOptions { using System.Diagnostics.CodeAnalysis; - + using OtpNet; using Rocket.Chat.Net.Interfaces; [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")] public class UsernameLoginOption : ILoginOption { + private Totp totpSeed; + private string totpToken; + /// /// Username of the user to login as. This should not be a email address. /// @@ -16,5 +19,25 @@ public class UsernameLoginOption : ILoginOption /// Plaintext password of the user. /// public string Password { get; set; } + + public Totp TOTPSeed + { + get => totpSeed; + set => totpSeed = value; + } + + public string TOTPToken + { + get + { + if (this.totpSeed != null) + totpToken = totpSeed.ComputeTotp(); + return totpToken; + } + set + { + totpToken = value; + } + } } } \ No newline at end of file From e4587eee5b635356e6e306fd259fc1091d310c5b Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Fri, 25 Nov 2022 12:22:10 +0100 Subject: [PATCH 04/14] updated auth methods to use loginresults --- .../Properties/AssemblyInfo.cs | 28 ------ .../Rocket.Chat.Net.Bot.csproj | 86 ++----------------- .../Rocket.Chat.Net.Bot.v2.ncrunchproject | 26 ------ src/Rocket.Chat.Net.Bot/RocketChatBot.cs | 2 +- src/Rocket.Chat.Net.Bot/packages.config | 6 -- .../Driver/RocketChatDriver.cs | 41 +++++++-- .../Driver/IRocketClientManagement.cs | 9 +- .../Rocket.Chat.Net.Bot.Tests.csproj | 2 +- .../RocketChatBotFacts.cs | 9 +- test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs | 12 +-- .../Driver/RocketChatDriverFacts.cs | 2 +- .../Helpers/DummyLoginOption.cs | 3 + .../Rocket.Chat.Net.Tests.csproj | 8 +- test/Rocket.Chat.Net.Tests/packages.config | 3 +- 14 files changed, 69 insertions(+), 168 deletions(-) delete mode 100644 src/Rocket.Chat.Net.Bot/Properties/AssemblyInfo.cs delete mode 100644 src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.v2.ncrunchproject delete mode 100644 src/Rocket.Chat.Net.Bot/packages.config diff --git a/src/Rocket.Chat.Net.Bot/Properties/AssemblyInfo.cs b/src/Rocket.Chat.Net.Bot/Properties/AssemblyInfo.cs deleted file mode 100644 index 43c0476..0000000 --- a/src/Rocket.Chat.Net.Bot/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Rocket.Chat.Net.Bot")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Rocket.Chat.Net.Bot")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: AssemblyInformationalVersion("1.0.0.0")] \ No newline at end of file diff --git a/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.csproj b/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.csproj index 144e8cf..7bae097 100644 --- a/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.csproj +++ b/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.csproj @@ -1,83 +1,11 @@ - - - - + + - Debug - AnyCPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E} - Library - Properties - Rocket.Chat.Net.Bot - Rocket.Chat.Net.Bot - v4.5 - 512 - - - - Profile111 - {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + netstandard2.0 - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\packages\Newtonsoft.Json.8.0.3\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll - True - - - - - - - - - - - - - - - - - - - {a078aeb9-5502-441c-b44a-ff4bbe007551} - Rocket.Chat.Net - - + - + - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - \ No newline at end of file + + diff --git a/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.v2.ncrunchproject b/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.v2.ncrunchproject deleted file mode 100644 index 30815b1..0000000 --- a/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.v2.ncrunchproject +++ /dev/null @@ -1,26 +0,0 @@ - - true - 1000 - false - false - false - true - false - false - false - false - false - true - true - false - true - true - true - 60000 - - - - AutoDetect - STA - x86 - \ No newline at end of file diff --git a/src/Rocket.Chat.Net.Bot/RocketChatBot.cs b/src/Rocket.Chat.Net.Bot/RocketChatBot.cs index ffa35e6..84945e1 100644 --- a/src/Rocket.Chat.Net.Bot/RocketChatBot.cs +++ b/src/Rocket.Chat.Net.Bot/RocketChatBot.cs @@ -64,7 +64,7 @@ public async Task ResumeAsync() } _logger.Info($"Resuming session {LoginToken}."); - var result = await Driver.LoginResumeAsync(LoginToken).ConfigureAwait(false); + var result = await Driver.LoginResumeAsync(new Net.Models.LoginOptions.ResumeLoginOption() { Token = LoginToken }).ConfigureAwait(false); if (result.HasError) { throw new Exception($"Resume failed: {result.Error.Message}."); diff --git a/src/Rocket.Chat.Net.Bot/packages.config b/src/Rocket.Chat.Net.Bot/packages.config deleted file mode 100644 index 263bd3b..0000000 --- a/src/Rocket.Chat.Net.Bot/packages.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs index ebb7d34..6ab7b67 100644 --- a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs +++ b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs @@ -233,29 +233,32 @@ public async Task> LoginAsync(ILoginOption loginOption var ldapLogin = loginOption as LdapLoginOption; if (ldapLogin != null) { - return await LoginWithLdapAsync(ldapLogin.Username, ldapLogin.Password).ConfigureAwait(false); + return await LoginWithLdapAsync(ldapLogin).ConfigureAwait(false); } var emailLogin = loginOption as EmailLoginOption; if (emailLogin != null) { - return await LoginWithEmailAsync(emailLogin.Email, emailLogin.Password).ConfigureAwait(false); + return await LoginWithEmailAsync(emailLogin).ConfigureAwait(false); } var usernameLogin = loginOption as UsernameLoginOption; if (usernameLogin != null) { - return await LoginWithUsernameAsync(usernameLogin.Username, usernameLogin.Password).ConfigureAwait(false); + return await LoginWithUsernameAsync(usernameLogin).ConfigureAwait(false); } var resumeLogin = loginOption as ResumeLoginOption; if (resumeLogin != null) { - return await LoginResumeAsync(resumeLogin.Token).ConfigureAwait(false); + return await LoginResumeAsync(resumeLogin).ConfigureAwait(false); } throw new NotSupportedException($"The given login option `{loginOption.GetType()}` is not supported."); } - public async Task> LoginWithEmailAsync(string email, string password) + public async Task> LoginWithEmailAsync(EmailLoginOption login) { + string email = login.Email; + string password = login.Password; + _logger.Info($"Logging in with user {email} using an email..."); var passwordHash = EncodingHelper.Sha256Hash(password); var request = new @@ -274,8 +277,11 @@ public async Task> LoginWithEmailAsync(string email, s return await InternalLoginAsync(request).ConfigureAwait(false); } - public async Task> LoginWithUsernameAsync(string username, string password) + public async Task> LoginWithUsernameAsync(UsernameLoginOption login) { + string username = login.Username; + string password = login.Password; + _logger.Info($"Logging in with user {username} using a username..."); var passwordHash = EncodingHelper.Sha256Hash(password); var request = new @@ -294,8 +300,11 @@ public async Task> LoginWithUsernameAsync(string usern return await InternalLoginAsync(request).ConfigureAwait(false); } - public async Task> LoginWithLdapAsync(string username, string password) + public async Task> LoginWithLdapAsync(LdapLoginOption login) { + string username = login.Username; + string password = login.Password; + _logger.Info($"Logging in with user {username} using LDAP..."); var request = new { @@ -308,8 +317,10 @@ public async Task> LoginWithLdapAsync(string username, return await InternalLoginAsync(request).ConfigureAwait(false); } - public async Task> LoginResumeAsync(string sessionToken) + public async Task> LoginResumeAsync(ResumeLoginOption login) { + string sessionToken = login.Token; + _logger.Info($"Resuming session {sessionToken}"); var request = new { @@ -348,6 +359,20 @@ private async Task> InternalLoginAsync(object request) return result; } + /// + /// This method will retry the request with a totp code additionally sent to the server. + /// https://developer.rocket.chat/reference/api/realtime-api/2fa + /// + /// + /// + /// + private async Task> InternalTotpAsync(MethodResult errorResponse, object originalRequest, string totpCode) + { + var data = await _client.CallAsync("callWithTwoFactorRequired ", TimeoutToken, originalRequest).ConfigureAwait(false); + var result = data.ToObject>(JsonSerializer); + return result; + } + private async Task SetDriverUserInfoAsync(string userId) { UserId = userId; diff --git a/src/Rocket.Chat.Net/Interfaces/Driver/IRocketClientManagement.cs b/src/Rocket.Chat.Net/Interfaces/Driver/IRocketClientManagement.cs index 25ccfac..7ec3542 100644 --- a/src/Rocket.Chat.Net/Interfaces/Driver/IRocketClientManagement.cs +++ b/src/Rocket.Chat.Net/Interfaces/Driver/IRocketClientManagement.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using Rocket.Chat.Net.Models; + using Rocket.Chat.Net.Models.LoginOptions; using Rocket.Chat.Net.Models.MethodResults; public interface IRocketClientManagement @@ -19,7 +20,7 @@ public interface IRocketClientManagement /// Email to use /// Plaintext password to use (will be SHA-256 before sending) /// - Task> LoginWithEmailAsync(string email, string password); + Task> LoginWithEmailAsync(EmailLoginOption login); /// /// Login with LDAP @@ -27,7 +28,7 @@ public interface IRocketClientManagement /// Email/Username to use /// Plaintext password to use /// - Task> LoginWithLdapAsync(string username, string password); + Task> LoginWithLdapAsync(LdapLoginOption login); /// /// Login with username @@ -35,14 +36,14 @@ public interface IRocketClientManagement /// Username to use /// Plaintext password to use (will be SHA-256 before sending) /// - Task> LoginWithUsernameAsync(string username, string password); + Task> LoginWithUsernameAsync(UsernameLoginOption login); /// /// Resume a login session /// /// Active token given from a previous login /// - Task> LoginResumeAsync(string sessionToken); + Task> LoginResumeAsync(ResumeLoginOption login); /// /// Login with a ILogin object diff --git a/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj b/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj index 00d7f9f..20c4dbb 100644 --- a/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj +++ b/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj @@ -90,7 +90,7 @@ - {a6ff1f57-0837-4f1a-9248-1cce8477295e} + {0c2862be-2cfb-4890-b154-4b4e7753e11f} Rocket.Chat.Net.Bot diff --git a/test/Rocket.Chat.Net.Bot.Tests/RocketChatBotFacts.cs b/test/Rocket.Chat.Net.Bot.Tests/RocketChatBotFacts.cs index 7ce640e..1059e95 100644 --- a/test/Rocket.Chat.Net.Bot.Tests/RocketChatBotFacts.cs +++ b/test/Rocket.Chat.Net.Bot.Tests/RocketChatBotFacts.cs @@ -16,6 +16,7 @@ using Rocket.Chat.Net.Bot.Models; using Rocket.Chat.Net.Interfaces; using Rocket.Chat.Net.Models; + using Rocket.Chat.Net.Models.LoginOptions; using Rocket.Chat.Net.Models.MethodResults; using Xunit; @@ -134,7 +135,7 @@ public async Task On_successful_resume_set_login_token() var resumeResult = AutoFixture.Build>() .With(x => x.Error, null) .Create(); - _driverMock.LoginResumeAsync(loginResult.Result.Token) + _driverMock.LoginResumeAsync(new ResumeLoginOption() { Token = loginResult.Result.Token }) .Returns(Task.FromResult(resumeResult)); var bot = new RocketChatBot(_driverMock, _loggerMock); @@ -158,7 +159,7 @@ public async Task On_unsuccessful_resume_throw() var resumeResult = AutoFixture.Build>() .Create(); - _driverMock.LoginResumeAsync(loginResult.Result.Token) + _driverMock.LoginResumeAsync(new ResumeLoginOption() { Token = loginResult.Result.Token }) .Returns(Task.FromResult(resumeResult)); var bot = new RocketChatBot(_driverMock, _loggerMock); @@ -316,7 +317,7 @@ public async Task On_disconnect_and_if_logged_in_resume_old_session() var resumeResult = AutoFixture.Build>() .With(x => x.Error, null) .Create(); - _driverMock.LoginResumeAsync(loginResult.Result.Token) + _driverMock.LoginResumeAsync(new ResumeLoginOption() { Token = loginResult.Result.Token }) .Returns(Task.FromResult(resumeResult)); var bot = new RocketChatBot(_driverMock, _loggerMock); @@ -327,7 +328,7 @@ public async Task On_disconnect_and_if_logged_in_resume_old_session() Thread.Sleep(200); // Assert - await _driverMock.Received().LoginResumeAsync(Arg.Any()); + await _driverMock.Received().LoginResumeAsync(new ResumeLoginOption() { Token = Arg.Any() }); } } diff --git a/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs b/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs index 346cb2d..c90453a 100644 --- a/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs @@ -15,7 +15,7 @@ using Rocket.Chat.Net.Interfaces; using Rocket.Chat.Net.Portability.Websockets; using Rocket.Chat.Net.Tests.Helpers; - + using WebSocket4Net; using Xunit; using Xunit.Abstractions; @@ -47,7 +47,7 @@ public void Connecting_should_set_session() var jsonMessage = new PortableMessageReceivedEventArgs(JsonConvert.SerializeObject(message)); // Act - _socket.MessageReceived += Raise.Event>(new object(), jsonMessage); + _socket.MessageReceived += Raise.Event>(new object(), jsonMessage); // Assert client.SessionId.Should().Be(sessionId); @@ -68,7 +68,7 @@ public void Can_unsubscribe() // Act var task = client.UnsubscribeAsync(subId, TimeoutToken); - _socket.MessageReceived += Raise.Event>(new object(), jsonMessage); + _socket.MessageReceived += Raise.Event>(new object(), jsonMessage); Action action = async () => await task; @@ -96,9 +96,9 @@ public void Can_reconnect() })); // Act - _socket.MessageReceived += Raise.Event>(new object(), firstMessage); + _socket.MessageReceived += Raise.Event>(new object(), firstMessage); _socket.Closed += Raise.Event(); - _socket.MessageReceived += Raise.Event>(new object(), secondMessage); + _socket.MessageReceived += Raise.Event>(new object(), secondMessage); // Assert _socket.Received().Open(); @@ -116,7 +116,7 @@ public void On_error_log() var exception = new Exception(message); // Act - _socket.Error += Raise.Event>(new object(), new PortableErrorEventArgs(exception)); + _socket.Error += Raise.Event>(new object(), new ErrorEventArgs(exception)); // Assert logger.Received().Info($"ERROR: {message}"); diff --git a/test/Rocket.Chat.Net.Tests/Driver/RocketChatDriverFacts.cs b/test/Rocket.Chat.Net.Tests/Driver/RocketChatDriverFacts.cs index ca862a3..6b3b9ad 100644 --- a/test/Rocket.Chat.Net.Tests/Driver/RocketChatDriverFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Driver/RocketChatDriverFacts.cs @@ -116,7 +116,7 @@ public async Task Login_with_email() .Returns(Task.FromResult(collection)); // Act - await _driver.LoginWithEmailAsync(email, password); + await _driver.LoginWithEmailAsync(new Net.Models.LoginOptions.EmailLoginOption { Email = email, Password = password }); // Assert await _mockClient.ReceivedWithAnyArgs().CallAsync("login", CancellationToken, payload); diff --git a/test/Rocket.Chat.Net.Tests/Helpers/DummyLoginOption.cs b/test/Rocket.Chat.Net.Tests/Helpers/DummyLoginOption.cs index 3e2c1a6..cfd747b 100644 --- a/test/Rocket.Chat.Net.Tests/Helpers/DummyLoginOption.cs +++ b/test/Rocket.Chat.Net.Tests/Helpers/DummyLoginOption.cs @@ -1,8 +1,11 @@ namespace Rocket.Chat.Net.Tests.Helpers { + using OtpNet; using Rocket.Chat.Net.Interfaces; public class DummyLoginOption : ILoginOption { + public Totp TOTPSeed { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } + public string TOTPToken { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } } \ No newline at end of file diff --git a/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj b/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj index 9f61fea..adae783 100644 --- a/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj +++ b/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj @@ -58,14 +58,16 @@ True - - ..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll - True + + ..\..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll ..\..\packages\NSubstitute.1.10.0.0\lib\net45\NSubstitute.dll True + + ..\..\packages\Otp.NET.1.2.2\lib\net45\Otp.NET.dll + ..\..\packages\PCLCrypto.2.0.147\lib\net45\PCLCrypto.dll True diff --git a/test/Rocket.Chat.Net.Tests/packages.config b/test/Rocket.Chat.Net.Tests/packages.config index 1fff570..647a6dc 100644 --- a/test/Rocket.Chat.Net.Tests/packages.config +++ b/test/Rocket.Chat.Net.Tests/packages.config @@ -4,9 +4,10 @@ - + + From 5df44c43c0de7ff4d56af0dd5dca77e9dfcc1fc0 Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Mon, 28 Nov 2022 13:51:13 +0100 Subject: [PATCH 05/14] removed wrapper --- Rocket.Chat.Net.sln | 52 ++++++------ .../Rocket.Chat.Net.Example.csproj | 84 ++++++++++++++++++- src/Rocket.Chat.Net.Example/packages.config | 20 ++++- src/Rocket.Chat.Net/Driver/DdpClient.cs | 6 +- .../Helpers/DummyLoginOption.cs | 24 +++++- 5 files changed, 150 insertions(+), 36 deletions(-) diff --git a/Rocket.Chat.Net.sln b/Rocket.Chat.Net.sln index d5a3d0e..d93c809 100644 --- a/Rocket.Chat.Net.sln +++ b/Rocket.Chat.Net.sln @@ -14,8 +14,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{7B016A .nuget\packages.config = .nuget\packages.config EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Chat.Net.Bot", "src\Rocket.Chat.Net.Bot\Rocket.Chat.Net.Bot.csproj", "{A6FF1F57-0837-4F1A-9248-1CCE8477295E}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Chat.Net.Bot.Tests", "test\Rocket.Chat.Net.Bot.Tests\Rocket.Chat.Net.Bot.Tests.csproj", "{A271F00E-6B4A-4149-9770-57A50E81A3ED}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Chat.Net.Portability", "src\Portability\Rocket.Chat.Net.Portability\Rocket.Chat.Net.Portability.csproj", "{662CE701-056D-420A-B03B-4F2613EEA044}" @@ -38,6 +36,8 @@ Project("{FF286327-C783-4F7A-AB73-9BCBAD0D4460}") = "Rocket.Chat.Net.Bot.NuGet", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Chat.Net", "src\Rocket.Chat.Net\Rocket.Chat.Net.csproj", "{7EA92634-49F8-416D-9DBC-661A83EA425C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Chat.Net.Bot", "src\Rocket.Chat.Net.Bot\Rocket.Chat.Net.Bot.csproj", "{0C2862BE-2CFB-4890-B154-4B4E7753E11F}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -102,30 +102,6 @@ Global {EFB12AE6-706D-42B5-B2CC-54D60C4DC02B}.Release|x64.Build.0 = Release|Any CPU {EFB12AE6-706D-42B5-B2CC-54D60C4DC02B}.Release|x86.ActiveCfg = Release|Any CPU {EFB12AE6-706D-42B5-B2CC-54D60C4DC02B}.Release|x86.Build.0 = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Debug|ARM.ActiveCfg = Debug|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Debug|ARM.Build.0 = Debug|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Debug|x64.ActiveCfg = Debug|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Debug|x64.Build.0 = Debug|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Debug|x86.ActiveCfg = Debug|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Debug|x86.Build.0 = Debug|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Mono-4.5|Any CPU.ActiveCfg = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Mono-4.5|Any CPU.Build.0 = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Mono-4.5|ARM.ActiveCfg = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Mono-4.5|ARM.Build.0 = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Mono-4.5|x64.ActiveCfg = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Mono-4.5|x64.Build.0 = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Mono-4.5|x86.ActiveCfg = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Mono-4.5|x86.Build.0 = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Release|Any CPU.Build.0 = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Release|ARM.ActiveCfg = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Release|ARM.Build.0 = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Release|x64.ActiveCfg = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Release|x64.Build.0 = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Release|x86.ActiveCfg = Release|Any CPU - {A6FF1F57-0837-4F1A-9248-1CCE8477295E}.Release|x86.Build.0 = Release|Any CPU {A271F00E-6B4A-4149-9770-57A50E81A3ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A271F00E-6B4A-4149-9770-57A50E81A3ED}.Debug|Any CPU.Build.0 = Debug|Any CPU {A271F00E-6B4A-4149-9770-57A50E81A3ED}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -342,6 +318,30 @@ Global {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|x64.Build.0 = Release|Any CPU {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|x86.ActiveCfg = Release|Any CPU {7EA92634-49F8-416D-9DBC-661A83EA425C}.Release|x86.Build.0 = Release|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Debug|ARM.ActiveCfg = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Debug|ARM.Build.0 = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Debug|x64.ActiveCfg = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Debug|x64.Build.0 = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Debug|x86.ActiveCfg = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Debug|x86.Build.0 = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Mono-4.5|Any CPU.ActiveCfg = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Mono-4.5|Any CPU.Build.0 = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Mono-4.5|ARM.ActiveCfg = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Mono-4.5|ARM.Build.0 = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Mono-4.5|x64.ActiveCfg = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Mono-4.5|x64.Build.0 = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Mono-4.5|x86.ActiveCfg = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Mono-4.5|x86.Build.0 = Debug|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Release|Any CPU.Build.0 = Release|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Release|ARM.ActiveCfg = Release|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Release|ARM.Build.0 = Release|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Release|x64.ActiveCfg = Release|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Release|x64.Build.0 = Release|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Release|x86.ActiveCfg = Release|Any CPU + {0C2862BE-2CFB-4890-B154-4B4E7753E11F}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj b/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj index b6607c7..b662280 100644 --- a/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj +++ b/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj @@ -48,22 +48,98 @@ v4.5 - - ..\..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll - True + + ..\..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll ..\..\packages\RestSharp.105.2.3\lib\net45\RestSharp.dll True + + ..\..\packages\SuperSocket.ClientEngine.Core.0.10.0\lib\net45\SuperSocket.ClientEngine.dll + + + ..\..\packages\System.Collections.Specialized.4.3.0\lib\net46\System.Collections.Specialized.dll + True + True + + + + ..\..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + True + True + + + ..\..\packages\System.Linq.4.3.0\lib\net463\System.Linq.dll + True + True + + + ..\..\packages\System.Net.NameResolution.4.3.0\lib\net46\System.Net.NameResolution.dll + True + True + + + ..\..\packages\System.Net.Security.4.3.0\lib\net46\System.Net.Security.dll + True + True + + + ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll + True + True + + + ..\..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + True + True + + + ..\..\packages\System.Runtime.Extensions.4.3.0\lib\net462\System.Runtime.Extensions.dll + True + True + + + ..\..\packages\System.Runtime.InteropServices.4.3.0\lib\net463\System.Runtime.InteropServices.dll + True + True + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + True + True + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + True + True + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + True + True + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + True + True + + + ..\..\packages\System.Text.RegularExpressions.4.3.0\lib\net463\System.Text.RegularExpressions.dll + True + True + + + ..\..\packages\WebSocket4Net.0.15.2\lib\net45\WebSocket4Net.dll + @@ -81,7 +157,7 @@ Rocket.Chat.Net.Portability.Net45 - {a6ff1f57-0837-4f1a-9248-1cce8477295e} + {0c2862be-2cfb-4890-b154-4b4e7753e11f} Rocket.Chat.Net.Bot diff --git a/src/Rocket.Chat.Net.Example/packages.config b/src/Rocket.Chat.Net.Example/packages.config index 5b899f3..ba90b54 100644 --- a/src/Rocket.Chat.Net.Example/packages.config +++ b/src/Rocket.Chat.Net.Example/packages.config @@ -1,6 +1,24 @@  - + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Driver/DdpClient.cs b/src/Rocket.Chat.Net/Driver/DdpClient.cs index 5d905be..74ec7a1 100644 --- a/src/Rocket.Chat.Net/Driver/DdpClient.cs +++ b/src/Rocket.Chat.Net/Driver/DdpClient.cs @@ -19,7 +19,7 @@ public class DdpClient : IDdpClient { private readonly ILogger _logger; - private readonly IWebSocketWrapper _socket; + private readonly WebSocket _socket; private readonly ConcurrentDictionary _messages = new ConcurrentDictionary(); public string Url { get; } @@ -36,11 +36,11 @@ public DdpClient(string baseUrl, bool useSsl, ILogger logger) var protocol = useSsl ? "wss" : "ws"; Url = $"{protocol}://{baseUrl}/websocket"; - _socket = new WebSocketWrapper(new WebSocket(Url)); + _socket = new WebSocket(Url); AttachEvents(); } - public DdpClient(IWebSocketWrapper socket, ILogger logger) + public DdpClient(WebSocket socket, ILogger logger) { _logger = logger; diff --git a/test/Rocket.Chat.Net.Tests/Helpers/DummyLoginOption.cs b/test/Rocket.Chat.Net.Tests/Helpers/DummyLoginOption.cs index cfd747b..8f0f867 100644 --- a/test/Rocket.Chat.Net.Tests/Helpers/DummyLoginOption.cs +++ b/test/Rocket.Chat.Net.Tests/Helpers/DummyLoginOption.cs @@ -5,7 +5,27 @@ public class DummyLoginOption : ILoginOption { - public Totp TOTPSeed { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } - public string TOTPToken { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } + public Totp TOTPSeed + { + get + { + throw new System.NotImplementedException(); + } + set + { + throw new System.NotImplementedException(); + } + } + public string TOTPToken + { + get + { + throw new System.NotImplementedException(); + } + set + { + throw new System.NotImplementedException(); + } + } } } \ No newline at end of file From 43bf3ff5c7e62c9ad241bd96c7fe2ea3d93998a2 Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Mon, 28 Nov 2022 15:19:41 +0100 Subject: [PATCH 06/14] fixed ssl handshake error --- src/Rocket.Chat.Net/Driver/DdpClient.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Rocket.Chat.Net/Driver/DdpClient.cs b/src/Rocket.Chat.Net/Driver/DdpClient.cs index 74ec7a1..dd4d958 100644 --- a/src/Rocket.Chat.Net/Driver/DdpClient.cs +++ b/src/Rocket.Chat.Net/Driver/DdpClient.cs @@ -13,8 +13,8 @@ using Rocket.Chat.Net.Interfaces; using Rocket.Chat.Net.Models; using WebSocket4Net; - using SuperSocket.ClientEngine; + using System.Security.Authentication; public class DdpClient : IDdpClient { @@ -36,7 +36,7 @@ public DdpClient(string baseUrl, bool useSsl, ILogger logger) var protocol = useSsl ? "wss" : "ws"; Url = $"{protocol}://{baseUrl}/websocket"; - _socket = new WebSocket(Url); + _socket = new WebSocket(Url, sslProtocols : SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls); AttachEvents(); } From 016b038ae695d4b8e55ee4e6cd97136a23a344c4 Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Wed, 30 Nov 2022 14:55:55 +0100 Subject: [PATCH 07/14] Added room retrieval at subscription --- src/Rocket.Chat.Net.Example/Program.cs | 10 +++-- .../Driver/RocketChatDriver.cs | 40 ++++++++++++++++++- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/Rocket.Chat.Net.Example/Program.cs b/src/Rocket.Chat.Net.Example/Program.cs index b671ff0..abe9e0c 100644 --- a/src/Rocket.Chat.Net.Example/Program.cs +++ b/src/Rocket.Chat.Net.Example/Program.cs @@ -32,17 +32,19 @@ private static async Task MainAsync() await bot.ConnectAsync(); // Login - ILoginOption loginOption = new EmailLoginOption + ILoginOption loginOption = new UsernameLoginOption() { - Email = username, + Username = username, Password = password }; try { await bot.LoginAsync(loginOption); + Console.WriteLine("Logged in!"); } - catch (Exception e) { - Console.Write(e); + catch (Exception e) + { + Console.WriteLine(e); } // Start listening for messages diff --git a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs index 6ab7b67..1db476c 100644 --- a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs +++ b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs @@ -2,6 +2,7 @@ { using System; using System.Collections.Generic; + using System.ComponentModel.Design; using System.IO; using System.Linq; using System.Threading; @@ -180,8 +181,30 @@ public async Task SubscribeToRoomListAsync() public async Task SubscribeToRoomAsync(string roomId = null) { - _logger.Info($"Subscribing to Room: #{roomId ?? "ALLROOMS"}"); - await _client.SubscribeAsync(MessageTopic, TimeoutToken, roomId, MessageSubscriptionLimit.ToString()).ConfigureAwait(false); + List ids = new List(); + + // Subscribe to all rooms when roomId is null + if (roomId == null) + { + var methodResult = await GetAvailableRoomInfoCollection().ConfigureAwait(false); + ids.AddRange(methodResult.Result.Select(roomInfo => roomInfo.Id)); + } else + // Subsribe to given roomId + { + ids.Add(roomId); + } + + List tasks = new List(); + foreach (string id in ids) + { + _logger.Info($"Subscribing to Room: #{id}"); + Task task = new Task(() => _client.SubscribeAsync(MessageTopic, TimeoutToken, id, MessageSubscriptionLimit.ToString())); + tasks.Add(task); + task.Start(); + } + + await Task.WhenAll(tasks).ConfigureAwait(false); + } public async Task SubscribeToRoomInformationAsync(string roomName, RoomType type) @@ -642,6 +665,19 @@ public TypedStreamCollection GetRoomInfoCollection() return typedCollection; } + public async Task>> GetAvailableRoomInfoCollection() + { + JObject result = await _client.CallAsync("rooms/get", CancellationToken.None, new object[] { 0 }).ConfigureAwait(false); + return result.ToObject>>(JsonSerializer); + } + + public async Task> GetAvailableRoomsCollection() + { + JObject result = await _client.CallAsync("rooms/get", CancellationToken.None, new object[] { 0 }).ConfigureAwait(false); + MethodResult> roomMethodResult = result.ToObject>>(JsonSerializer); + throw new NotImplementedException(); + } + public void Dispose() { _client.Dispose(); From 1ca3335fc0ace8198ebc9a76dde6c0ee54d494f9 Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Fri, 2 Dec 2022 15:06:38 +0100 Subject: [PATCH 08/14] Added NLog and updated msg type for RocketMessage to changed --- .../Rocket.Chat.Net.Bot.csproj | 6 +- src/Rocket.Chat.Net.Bot/RocketChatBot.cs | 5 +- .../HelloWorldResponse.cs | 25 ++++++ .../Rocket.Chat.Net.Example.csproj | 6 ++ src/Rocket.Chat.Net.Example/packages.config | 1 + src/Rocket.Chat.Net/Driver/DdpClient.cs | 21 ++++- .../Driver/RocketChatDriver.cs | 15 ++-- src/Rocket.Chat.Net/Interfaces/ILogger.cs | 15 ---- src/Rocket.Chat.Net/Loggers/DummyLogger.cs | 27 ------ src/Rocket.Chat.Net/Rocket.Chat.Net.csproj | 10 +++ .../Rocket.Chat.Net.Bot.Tests.csproj | 5 ++ .../RocketChatBotFacts.cs | 2 +- .../Rocket.Chat.Net.Bot.Tests/packages.config | 1 + test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs | 4 +- .../Driver/MessagingFacts.cs | 2 +- test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs | 6 ++ .../Helpers/XUnitLogger.cs | 1 + .../Rocket.Chat.Net.Tests.csproj | 85 ++++++++++++++++++- test/Rocket.Chat.Net.Tests/packages.config | 20 ++++- 19 files changed, 191 insertions(+), 66 deletions(-) create mode 100644 src/Rocket.Chat.Net.Example/HelloWorldResponse.cs delete mode 100644 src/Rocket.Chat.Net/Interfaces/ILogger.cs delete mode 100644 src/Rocket.Chat.Net/Loggers/DummyLogger.cs create mode 100644 test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs diff --git a/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.csproj b/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.csproj index 7bae097..a393af5 100644 --- a/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.csproj +++ b/src/Rocket.Chat.Net.Bot/Rocket.Chat.Net.Bot.csproj @@ -1,9 +1,13 @@ - + netstandard2.0 + + + + diff --git a/src/Rocket.Chat.Net.Bot/RocketChatBot.cs b/src/Rocket.Chat.Net.Bot/RocketChatBot.cs index 84945e1..b7a888f 100644 --- a/src/Rocket.Chat.Net.Bot/RocketChatBot.cs +++ b/src/Rocket.Chat.Net.Bot/RocketChatBot.cs @@ -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 @@ -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; diff --git a/src/Rocket.Chat.Net.Example/HelloWorldResponse.cs b/src/Rocket.Chat.Net.Example/HelloWorldResponse.cs new file mode 100644 index 0000000..4ab171e --- /dev/null +++ b/src/Rocket.Chat.Net.Example/HelloWorldResponse.cs @@ -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 GetResponse(ResponseContext context, RocketChatBot caller) + { + var message = context.Message; + yield return new BasicResponse("Hello world!", context.Message.RoomId); + } + } +} diff --git a/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj b/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj index b662280..d910d6f 100644 --- a/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj +++ b/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj @@ -51,6 +51,9 @@ ..\..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\NLog.5.1.0\lib\net46\NLog.dll + ..\..\packages\RestSharp.105.2.3\lib\net45\RestSharp.dll True @@ -65,12 +68,14 @@ True + ..\..\packages\System.IO.4.3.0\lib\net462\System.IO.dll True True + ..\..\packages\System.Linq.4.3.0\lib\net463\System.Linq.dll True @@ -144,6 +149,7 @@ + diff --git a/src/Rocket.Chat.Net.Example/packages.config b/src/Rocket.Chat.Net.Example/packages.config index ba90b54..ea358ee 100644 --- a/src/Rocket.Chat.Net.Example/packages.config +++ b/src/Rocket.Chat.Net.Example/packages.config @@ -2,6 +2,7 @@ + diff --git a/src/Rocket.Chat.Net/Driver/DdpClient.cs b/src/Rocket.Chat.Net/Driver/DdpClient.cs index dd4d958..e79a24a 100644 --- a/src/Rocket.Chat.Net/Driver/DdpClient.cs +++ b/src/Rocket.Chat.Net/Driver/DdpClient.cs @@ -15,6 +15,7 @@ using WebSocket4Net; using SuperSocket.ClientEngine; using System.Security.Authentication; + using NLog; public class DdpClient : IDdpClient { @@ -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); + } } } @@ -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 @@ -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 @@ -198,7 +211,7 @@ public async Task 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; } diff --git a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs index 1db476c..a29a268 100644 --- a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs +++ b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs @@ -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; @@ -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; @@ -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..."); @@ -119,13 +118,13 @@ private void HandleStreamingCollections(string type, JObject data) private void HandleRocketMessage(string type, JObject data) { var o = data.ToObject>(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(JsonSerializer); message.IsBotMentioned = message.Mentions.Any(x => x.Id == UserId); message.IsFromMyself = message.CreatedBy.Id == UserId; @@ -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(); } @@ -667,7 +666,7 @@ public TypedStreamCollection GetRoomInfoCollection() public async Task>> 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>>(JsonSerializer); } diff --git a/src/Rocket.Chat.Net/Interfaces/ILogger.cs b/src/Rocket.Chat.Net/Interfaces/ILogger.cs deleted file mode 100644 index eaf2aa8..0000000 --- a/src/Rocket.Chat.Net/Interfaces/ILogger.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Rocket.Chat.Net.Interfaces -{ - public interface ILogger - { - void Debug(string message); - - void Info(string message); - - void Warn(string message); - - void Error(string message); - - void Fatal(string message); - } -} \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Loggers/DummyLogger.cs b/src/Rocket.Chat.Net/Loggers/DummyLogger.cs deleted file mode 100644 index 6a6c56d..0000000 --- a/src/Rocket.Chat.Net/Loggers/DummyLogger.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Rocket.Chat.Net.Loggers -{ - using Rocket.Chat.Net.Interfaces; - - public class DummyLogger : ILogger - { - public void Debug(string message) - { - } - - public void Info(string message) - { - } - - public void Warn(string message) - { - } - - public void Error(string message) - { - } - - public void Fatal(string message) - { - } - } -} \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj b/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj index e51ea90..986703d 100644 --- a/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj +++ b/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj @@ -4,10 +4,20 @@ netstandard2.0 + + + + + + + + + + diff --git a/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj b/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj index 20c4dbb..66d9750 100644 --- a/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj +++ b/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj @@ -47,6 +47,9 @@ ..\..\packages\FluentAssertions.4.9.1\lib\net45\FluentAssertions.Core.dll True + + ..\..\packages\NLog.5.1.0\lib\net46\NLog.dll + ..\..\packages\NSubstitute.1.10.0.0\lib\net45\NSubstitute.dll True @@ -56,6 +59,8 @@ True + + diff --git a/test/Rocket.Chat.Net.Bot.Tests/RocketChatBotFacts.cs b/test/Rocket.Chat.Net.Bot.Tests/RocketChatBotFacts.cs index 1059e95..e0cd2ff 100644 --- a/test/Rocket.Chat.Net.Bot.Tests/RocketChatBotFacts.cs +++ b/test/Rocket.Chat.Net.Bot.Tests/RocketChatBotFacts.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using FluentAssertions; - + using NLog; using NSubstitute; using NSubstitute.ExceptionExtensions; diff --git a/test/Rocket.Chat.Net.Bot.Tests/packages.config b/test/Rocket.Chat.Net.Bot.Tests/packages.config index 042c86a..210b858 100644 --- a/test/Rocket.Chat.Net.Bot.Tests/packages.config +++ b/test/Rocket.Chat.Net.Bot.Tests/packages.config @@ -4,6 +4,7 @@ + diff --git a/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs b/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs index c90453a..56d4ef6 100644 --- a/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs @@ -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(); + private readonly WebSocket _socket = Substitute.For(); private CancellationToken TimeoutToken => CreateTimeoutToken(); @@ -116,7 +116,7 @@ public void On_error_log() var exception = new Exception(message); // Act - _socket.Error += Raise.Event>(new object(), new ErrorEventArgs(exception)); + _socket.Error += Raise.Event>(new object(), new SuperSocket.ClientEngine.ErrorEventArgs(exception)); // Assert logger.Received().Info($"ERROR: {message}"); diff --git a/test/Rocket.Chat.Net.Tests/Driver/MessagingFacts.cs b/test/Rocket.Chat.Net.Tests/Driver/MessagingFacts.cs index c094b48..08f0df1 100644 --- a/test/Rocket.Chat.Net.Tests/Driver/MessagingFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Driver/MessagingFacts.cs @@ -3,7 +3,7 @@ using FluentAssertions; using Newtonsoft.Json.Linq; - + using NLog; using NSubstitute; using Ploeh.AutoFixture; diff --git a/test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs b/test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs new file mode 100644 index 0000000..6209474 --- /dev/null +++ b/test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs @@ -0,0 +1,6 @@ +namespace Rocket.Chat.Net.Tests.Helpers +{ + public interface ILogger + { + } +} \ No newline at end of file diff --git a/test/Rocket.Chat.Net.Tests/Helpers/XUnitLogger.cs b/test/Rocket.Chat.Net.Tests/Helpers/XUnitLogger.cs index 2f723f9..604a83b 100644 --- a/test/Rocket.Chat.Net.Tests/Helpers/XUnitLogger.cs +++ b/test/Rocket.Chat.Net.Tests/Helpers/XUnitLogger.cs @@ -3,6 +3,7 @@ using System; using Rocket.Chat.Net.Interfaces; + using NLog; using Xunit.Abstractions; diff --git a/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj b/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj index adae783..5be1538 100644 --- a/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj +++ b/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj @@ -61,6 +61,9 @@ ..\..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\NLog.5.1.0\lib\net46\NLog.dll + ..\..\packages\NSubstitute.1.10.0.0\lib\net45\NSubstitute.dll True @@ -92,16 +95,91 @@ ..\..\packages\AutoFixture.3.47.8\lib\net40\Ploeh.AutoFixture.dll True + + ..\..\packages\SuperSocket.ClientEngine.Core.0.10.0\lib\net45\SuperSocket.ClientEngine.dll + + + ..\..\packages\System.Collections.Specialized.4.3.0\lib\net46\System.Collections.Specialized.dll + True + True + + + + + ..\..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + True + True + + + + ..\..\packages\System.Linq.4.3.0\lib\net463\System.Linq.dll + True + True + + + ..\..\packages\System.Net.NameResolution.4.3.0\lib\net46\System.Net.NameResolution.dll + True + True + + + ..\..\packages\System.Net.Security.4.3.0\lib\net46\System.Net.Security.dll + True + True + + + ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll + True + True + + + ..\..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + True + True + + + ..\..\packages\System.Runtime.Extensions.4.3.0\lib\net462\System.Runtime.Extensions.dll + True + True + + + ..\..\packages\System.Runtime.InteropServices.4.3.0\lib\net463\System.Runtime.InteropServices.dll + True + True + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + True + True + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + True + True + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + True + True + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + True + True + + + ..\..\packages\System.Text.RegularExpressions.4.3.0\lib\net463\System.Text.RegularExpressions.dll + True + True + ..\..\packages\Validation.2.2.8\lib\dotnet\Validation.dll True - - ..\..\packages\WebSocket4Net.0.14.1\lib\net45\WebSocket4Net.dll - True + + ..\..\packages\WebSocket4Net.0.15.2\lib\net45\WebSocket4Net.dll ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll @@ -133,6 +211,7 @@ + diff --git a/test/Rocket.Chat.Net.Tests/packages.config b/test/Rocket.Chat.Net.Tests/packages.config index 647a6dc..5341ad5 100644 --- a/test/Rocket.Chat.Net.Tests/packages.config +++ b/test/Rocket.Chat.Net.Tests/packages.config @@ -5,6 +5,7 @@ + @@ -13,8 +14,25 @@ + + + + + + + + + + + + + + + + + - + From bfee073f4e972e23a2b25bfe3d0967f6e9f3b943 Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Wed, 7 Dec 2022 16:51:56 +0100 Subject: [PATCH 09/14] Added rest client which will be needed for Attachments --- src/Rocket.Chat.Net/Driver/RestClient.cs | 119 ++++++++++++++++++ .../Driver/RocketChatDriver.cs | 9 ++ .../Driver/IRocketRestClientManagement.cs | 12 ++ src/Rocket.Chat.Net/Interfaces/IRestClient.cs | 18 +++ .../Interfaces/IRocketChatDriver.cs | 1 + src/Rocket.Chat.Net/Rocket.Chat.Net.csproj | 1 + 6 files changed, 160 insertions(+) create mode 100644 src/Rocket.Chat.Net/Driver/RestClient.cs create mode 100644 src/Rocket.Chat.Net/Interfaces/Driver/IRocketRestClientManagement.cs create mode 100644 src/Rocket.Chat.Net/Interfaces/IRestClient.cs diff --git a/src/Rocket.Chat.Net/Driver/RestClient.cs b/src/Rocket.Chat.Net/Driver/RestClient.cs new file mode 100644 index 0000000..a42c6be --- /dev/null +++ b/src/Rocket.Chat.Net/Driver/RestClient.cs @@ -0,0 +1,119 @@ +using Newtonsoft.Json.Linq; +using Rocket.Chat.Net.Interfaces; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +using RestSharp; +using NLog; +using WebSocketSharp; +using RestSharp.Authenticators; +using NLog.LayoutRenderers.Wrappers; + +namespace Rocket.Chat.Net.Driver +{ + public class RestClient : IRestClient + { + public RestSharp.RestClient _client; + private IAuthenticator _authenticator; + private bool _isLoggedIn; + ILogger _logger; + + public RestClient(string instanceUrl, ILogger logger) + { + _logger = logger; + _client = new RestSharp.RestClient(instanceUrl + "/api/v1/"); + } + + private bool disposedValue; + + public string Url => throw new NotImplementedException(); + + public bool IsDisposed => throw new NotImplementedException(); + + public bool IsLoggedIn { get => _isLoggedIn; } + + /// + /// + /// + /// HTTP method, such as GET, POST, PUT etc. + /// + /// + /// + /// + public async Task CallAsync(string method, string path, CancellationToken token, params object[] args) + { + var request = new RestRequest(path, (Method) Enum.Parse(typeof(Method), method)); + JObject data = JObject.FromObject(args); + if (data != null) + { + request.AddBody(data); + } + var response = await _client.ExecuteAsync(request).ConfigureAwait(false); + return JObject.FromObject(response.Content); + } + + protected virtual void Dispose(bool disposing) + { + if (!disposedValue) + { + if (disposing) + { + // TODO: Verwalteten Zustand (verwaltete Objekte) bereinigen + _client.Dispose(); + } + + // TODO: Nicht verwaltete Ressourcen (nicht verwaltete Objekte) freigeben und Finalizer überschreiben + // TODO: Große Felder auf NULL setzen + disposedValue = true; + } + } + + // // TODO: Finalizer nur überschreiben, wenn "Dispose(bool disposing)" Code für die Freigabe nicht verwalteter Ressourcen enthält + // ~RestClient() + // { + // // Ändern Sie diesen Code nicht. Fügen Sie Bereinigungscode in der Methode "Dispose(bool disposing)" ein. + // Dispose(disposing: false); + // } + + public void Dispose() + { + // Ändern Sie diesen Code nicht. Fügen Sie Bereinigungscode in der Methode "Dispose(bool disposing)" ein. + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + public async Task LoginAsync(object args) + { + JObject response = await CallAsync("POST", "login", CancellationToken.None, args).ConfigureAwait(false); + if (response["status"].ToObject() == "success") + { + string authToken = response["status"]["authToken"].ToObject(); + string userId = response["status"]["userId"].ToObject(); + _client.Authenticator = new RocketAuthenticator(userId, authToken); + _isLoggedIn = true; + } + } + } + + public class RocketAuthenticator : IAuthenticator + { + private string authToken; + private string userId; + + public RocketAuthenticator(string userId, string authToken) + { + this.authToken = authToken; + this.userId = userId; + } + + public ValueTask Authenticate(RestSharp.RestClient client, RestRequest request) + { + request.AddHeader("X-Auth-Token", authToken); + request.AddHeader("X-User-Id", userId); + return new ValueTask(); + } + } +} diff --git a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs index a29a268..b740c94 100644 --- a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs +++ b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs @@ -30,6 +30,7 @@ public class RocketChatDriver : IRocketChatDriver private readonly IStreamCollectionDatabase _collectionDatabase; private readonly ILogger _logger; private readonly IDdpClient _client; + private readonly IRestClient _restClient; public event MessageReceived MessageReceived; public event DdpReconnect DdpReconnect; @@ -57,6 +58,8 @@ public RocketChatDriver(string url, bool useSsl, ILogger logger = null, bool isB _client.DataReceivedRaw += ClientOnDataReceivedRaw; _client.DdpReconnect += OnDdpReconnect; SetJsonOptions(jsonSerializerSettings); + + _restClient = new RestClient(url, logger); } public RocketChatDriver(ILogger logger, IDdpClient client, IStreamCollectionDatabase collectionDatabaseDatabase, bool isBot = true, @@ -250,6 +253,7 @@ public async Task PingAsync() await _client.PingAsync(TimeoutToken).ConfigureAwait(false); } + // TODO: Reuse login option for REST? public async Task> LoginAsync(ILoginOption loginOption) { var ldapLogin = loginOption as LdapLoginOption; @@ -695,5 +699,10 @@ private CancellationToken CreateTimeoutToken() return source.Token; } + + public async Task LoginRestApi(object args) + { + await _restClient.LoginAsync(args).ConfigureAwait(false); + } } } \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Interfaces/Driver/IRocketRestClientManagement.cs b/src/Rocket.Chat.Net/Interfaces/Driver/IRocketRestClientManagement.cs new file mode 100644 index 0000000..35ad805 --- /dev/null +++ b/src/Rocket.Chat.Net/Interfaces/Driver/IRocketRestClientManagement.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace Rocket.Chat.Net.Interfaces.Driver +{ + public interface IRocketRestClientManagement + { + Task LoginRestApi(object loginArgs); + } +} diff --git a/src/Rocket.Chat.Net/Interfaces/IRestClient.cs b/src/Rocket.Chat.Net/Interfaces/IRestClient.cs new file mode 100644 index 0000000..19cfece --- /dev/null +++ b/src/Rocket.Chat.Net/Interfaces/IRestClient.cs @@ -0,0 +1,18 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using System.Threading; + +namespace Rocket.Chat.Net.Interfaces +{ + public interface IRestClient : IDisposable + { + string Url { get; } + bool IsDisposed { get; } + Task CallAsync(string method, string path, CancellationToken token, params object[] args); + Task LoginAsync(object args); + + } +} diff --git a/src/Rocket.Chat.Net/Interfaces/IRocketChatDriver.cs b/src/Rocket.Chat.Net/Interfaces/IRocketChatDriver.cs index 1ec9d42..cb68c9c 100644 --- a/src/Rocket.Chat.Net/Interfaces/IRocketChatDriver.cs +++ b/src/Rocket.Chat.Net/Interfaces/IRocketChatDriver.cs @@ -5,6 +5,7 @@ using Rocket.Chat.Net.Interfaces.Driver; public interface IRocketChatDriver : IDisposable, + IRocketRestClientManagement, IRocketClientManagement, IRocketUserManagement, IRocketMessagingManagement, diff --git a/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj b/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj index 986703d..8736b3f 100644 --- a/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj +++ b/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj @@ -16,6 +16,7 @@ + From a02cdccd50974d891f39e990fbcdc3039ca58b3a Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Thu, 8 Dec 2022 16:57:00 +0100 Subject: [PATCH 10/14] removed XUnitLogger --- test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs | 9 ++- .../Driver/RocketChatDriverFacts.cs | 6 +- .../Helpers/DriverFactsBase.cs | 13 ++-- test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs | 6 -- .../Helpers/XUnitLogger.cs | 59 ------------------- .../Integration/DdpFacts.cs | 7 ++- .../Integration/LoginFacts.cs | 14 ++--- .../Integration/MessagingFacts.cs | 13 ++-- .../Integration/RoomFacts.cs | 3 +- .../Integration/SandboxFacts.cs | 12 ++-- .../Rocket.Chat.Net.Tests.csproj | 2 - 11 files changed, 42 insertions(+), 102 deletions(-) delete mode 100644 test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs delete mode 100644 test/Rocket.Chat.Net.Tests/Helpers/XUnitLogger.cs diff --git a/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs b/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs index 56d4ef6..fdea2a7 100644 --- a/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs @@ -6,7 +6,7 @@ using FluentAssertions; using Newtonsoft.Json; - + using NLog; using NSubstitute; using Ploeh.AutoFixture; @@ -14,7 +14,6 @@ using Rocket.Chat.Net.Driver; using Rocket.Chat.Net.Interfaces; using Rocket.Chat.Net.Portability.Websockets; - using Rocket.Chat.Net.Tests.Helpers; using WebSocket4Net; using Xunit; using Xunit.Abstractions; @@ -23,14 +22,14 @@ public class DdpFacts : IDisposable { private static readonly Fixture AutoFixture = new Fixture(); - private readonly XUnitLogger _helper; + private readonly ILogger _helper; private readonly WebSocket _socket = Substitute.For(); private CancellationToken TimeoutToken => CreateTimeoutToken(); public DdpFacts(ITestOutputHelper helper) { - _helper = new XUnitLogger(helper); + _helper = NLog.LogManager.GetCurrentClassLogger(); } [Fact] @@ -133,7 +132,7 @@ private CancellationToken CreateTimeoutToken() public void Dispose() { - _helper.Dispose(); + } } } \ No newline at end of file diff --git a/test/Rocket.Chat.Net.Tests/Driver/RocketChatDriverFacts.cs b/test/Rocket.Chat.Net.Tests/Driver/RocketChatDriverFacts.cs index 6b3b9ad..7b151db 100644 --- a/test/Rocket.Chat.Net.Tests/Driver/RocketChatDriverFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Driver/RocketChatDriverFacts.cs @@ -9,18 +9,20 @@ using Newtonsoft.Json.Linq; using NSubstitute; + using NLog; using Ploeh.AutoFixture; using Rocket.Chat.Net.Collections; using Rocket.Chat.Net.Driver; - using Rocket.Chat.Net.Helpers; + using Rocket.Chat.Net.Interfaces; using Rocket.Chat.Net.Models; using Rocket.Chat.Net.Models.MethodResults; - using Rocket.Chat.Net.Tests.Helpers; using Xunit; + using Rocket.Chat.Net.Helpers; + using Rocket.Chat.Net.Tests.Helpers; public class RocketChatDriverFacts { diff --git a/test/Rocket.Chat.Net.Tests/Helpers/DriverFactsBase.cs b/test/Rocket.Chat.Net.Tests/Helpers/DriverFactsBase.cs index 5bf2080..046f702 100644 --- a/test/Rocket.Chat.Net.Tests/Helpers/DriverFactsBase.cs +++ b/test/Rocket.Chat.Net.Tests/Helpers/DriverFactsBase.cs @@ -8,29 +8,31 @@ using Newtonsoft.Json; + using NLog; + using Ploeh.AutoFixture; using Rocket.Chat.Net.Driver; using Rocket.Chat.Net.Interfaces; - + using Rocket.Chat.Net.Models.LoginOptions; using Xunit.Abstractions; public class DriverFactsBase : IDisposable { protected static readonly Fixture AutoFixture = new Fixture(); protected readonly IRocketChatDriver RocketChatDriver; - protected readonly XUnitLogger XUnitLogger; + protected readonly ILogger _logger; protected DriverFactsBase(ITestOutputHelper helper) { - XUnitLogger = new XUnitLogger(helper); - RocketChatDriver = new RocketChatDriver(Constants.RocketServer, false, XUnitLogger, jsonSerializerSettings: new JsonSerializerSettings()); + _logger = NLog.LogManager.GetCurrentClassLogger(); + RocketChatDriver = new RocketChatDriver(Constants.RocketServer, false, _logger, jsonSerializerSettings: new JsonSerializerSettings()); } protected async Task DefaultAccountLoginAsync() { await RocketChatDriver.ConnectAsync(); - var result = await RocketChatDriver.LoginWithEmailAsync(Constants.OneEmail, Constants.OnePassword); + var result = await RocketChatDriver.LoginWithEmailAsync(new EmailLoginOption() { Email = Constants.OneEmail, Password = Constants.OnePassword }); result.HasError.Should().BeFalse(); } @@ -48,7 +50,6 @@ protected async Task CleanupRoomsAsync() public virtual void Dispose() { RocketChatDriver.Dispose(); - XUnitLogger.Dispose(); } } } \ No newline at end of file diff --git a/test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs b/test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs deleted file mode 100644 index 6209474..0000000 --- a/test/Rocket.Chat.Net.Tests/Helpers/ILogger.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Rocket.Chat.Net.Tests.Helpers -{ - public interface ILogger - { - } -} \ No newline at end of file diff --git a/test/Rocket.Chat.Net.Tests/Helpers/XUnitLogger.cs b/test/Rocket.Chat.Net.Tests/Helpers/XUnitLogger.cs deleted file mode 100644 index 604a83b..0000000 --- a/test/Rocket.Chat.Net.Tests/Helpers/XUnitLogger.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace Rocket.Chat.Net.Tests.Helpers -{ - using System; - - using Rocket.Chat.Net.Interfaces; - using NLog; - - using Xunit.Abstractions; - - public class XUnitLogger : ILogger, IDisposable - { - private readonly ITestOutputHelper _helper; - - public bool IsDisposed { get; set; } - - public XUnitLogger(ITestOutputHelper helper) - { - _helper = helper; - } - - public void Debug(string message) - { - if (IsDisposed) - { - return; - } - _helper.WriteLine(message); - } - - public void Info(string message) - { - if (IsDisposed) - { - return; - } - _helper.WriteLine(message); - } - - public void Warn(string message) - { - _helper.WriteLine(message); - } - - public void Error(string message) - { - _helper.WriteLine(message); - } - - public void Fatal(string message) - { - _helper.WriteLine(message); - } - - public void Dispose() - { - IsDisposed = true; - } - } -} \ No newline at end of file diff --git a/test/Rocket.Chat.Net.Tests/Integration/DdpFacts.cs b/test/Rocket.Chat.Net.Tests/Integration/DdpFacts.cs index f882c21..97a07f8 100644 --- a/test/Rocket.Chat.Net.Tests/Integration/DdpFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Integration/DdpFacts.cs @@ -7,19 +7,21 @@ using Rocket.Chat.Net.Driver; using Rocket.Chat.Net.Tests.Helpers; + using NLog; + using Xunit; using Xunit.Abstractions; [Trait("Category", "Driver")] public class DdpFacts : IDisposable { - private readonly XUnitLogger _helper; + private readonly ILogger _helper; private CancellationToken TimeoutToken => CreateTimeoutToken(); public DdpFacts(ITestOutputHelper helper) { - _helper = new XUnitLogger(helper); + _helper = NLog.LogManager.GetCurrentClassLogger(); } [Fact] @@ -45,7 +47,6 @@ private CancellationToken CreateTimeoutToken() public void Dispose() { - _helper.Dispose(); } } } \ No newline at end of file diff --git a/test/Rocket.Chat.Net.Tests/Integration/LoginFacts.cs b/test/Rocket.Chat.Net.Tests/Integration/LoginFacts.cs index 43dd1a2..52dc772 100644 --- a/test/Rocket.Chat.Net.Tests/Integration/LoginFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Integration/LoginFacts.cs @@ -6,7 +6,7 @@ using FluentAssertions; using Ploeh.AutoFixture; - + using Rocket.Chat.Net.Models.LoginOptions; using Rocket.Chat.Net.Tests.Helpers; using Xunit; @@ -34,7 +34,7 @@ public void Connecting_multiple_times_should_throw() public async Task Can_login_with_email() { // Act - var loginResult = await RocketChatDriver.LoginWithEmailAsync(Constants.OneEmail, Constants.OnePassword); + var loginResult = await RocketChatDriver.LoginWithEmailAsync(new EmailLoginOption() { Email = Constants.OneEmail, Password = Constants.OnePassword }); // Assert loginResult.Should().NotBeNull(); @@ -46,7 +46,7 @@ public async Task Can_login_with_email() public async Task Can_login_with_username() { // Act - var loginResult = await RocketChatDriver.LoginWithUsernameAsync(Constants.OneUsername, Constants.OnePassword); + var loginResult = await RocketChatDriver.LoginWithUsernameAsync(new UsernameLoginOption() { Username = Constants.OneUsername, Password = Constants.OnePassword }); // Assert loginResult.Should().NotBeNull(); @@ -57,10 +57,10 @@ public async Task Can_login_with_username() [Fact] public async Task Can_login_with_token() { - var tokenResult = await RocketChatDriver.LoginWithUsernameAsync(Constants.OneUsername, Constants.OnePassword); + var tokenResult = await RocketChatDriver.LoginWithUsernameAsync(new UsernameLoginOption() { Username = Constants.OneUsername, Password = Constants.OnePassword }); // Act - var loginResult = await RocketChatDriver.LoginResumeAsync(tokenResult.Result.Token); + var loginResult = await RocketChatDriver.LoginResumeAsync(new ResumeLoginOption() { Token = tokenResult.Result.Token }); // Assert loginResult.Should().NotBeNull(); @@ -73,7 +73,7 @@ public async Task Bad_login_should_have_error_data() { // Act var loginResult = - await RocketChatDriver.LoginWithUsernameAsync(Constants.OneUsername, AutoFixture.Create()); + await RocketChatDriver.LoginWithUsernameAsync(new UsernameLoginOption() { Username = Constants.OneUsername, Password = AutoFixture.Create() }); // Assert loginResult.Should().NotBeNull(); @@ -87,7 +87,7 @@ public async Task When_logging_in_with_a_non_existing_user_return_error() // Act var loginResult = await - RocketChatDriver.LoginWithUsernameAsync(AutoFixture.Create(), AutoFixture.Create()); + RocketChatDriver.LoginWithUsernameAsync(new UsernameLoginOption() { Username = Constants.OneUsername, Password = AutoFixture.Create() }); // Assert loginResult.Should().NotBeNull(); diff --git a/test/Rocket.Chat.Net.Tests/Integration/MessagingFacts.cs b/test/Rocket.Chat.Net.Tests/Integration/MessagingFacts.cs index 7134c9e..e3f2cf5 100644 --- a/test/Rocket.Chat.Net.Tests/Integration/MessagingFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Integration/MessagingFacts.cs @@ -12,10 +12,13 @@ using Rocket.Chat.Net.Driver; using Rocket.Chat.Net.Interfaces; using Rocket.Chat.Net.Models; - using Rocket.Chat.Net.Tests.Helpers; + + using NLog; using Xunit; using Xunit.Abstractions; + using Rocket.Chat.Net.Tests.Helpers; + using Rocket.Chat.Net.Models.LoginOptions; [Trait("Category", "Driver")] public class MessagingFacts : IDisposable @@ -478,7 +481,7 @@ public void Dispose() public class MessagingFixture : IDisposable { - private readonly XUnitLogger _logger; + private readonly ILogger _logger; public RocketChatDriverFixture Fixture { get; } public RocketChatDriverFixture Master { get; } public RocketChatDriverFixture Slave { get; } @@ -489,7 +492,7 @@ public class MessagingFixture : IDisposable public MessagingFixture(ITestOutputHelper helper, string roomName) { RoomName = roomName; - _logger = new XUnitLogger(helper); + _logger = NLog.LogManager.GetCurrentClassLogger(); Master = new RocketChatDriverFixture(_logger); Slave = new RocketChatDriverFixture(_logger); @@ -500,8 +503,6 @@ public MessagingFixture(ITestOutputHelper helper, string roomName) public void Dispose() { - _logger.Dispose(); - Fixture.Driver.EraseRoomAsync(RoomId).Wait(); Fixture.Dispose(); @@ -522,7 +523,7 @@ public RocketChatDriverFixture(ILogger helper) public async Task InitAsync(string username, string password) { await Driver.ConnectAsync(); - await Driver.LoginWithUsernameAsync(username, password); + await Driver.LoginWithUsernameAsync(new UsernameLoginOption() { Username = username, Password = password }); await Driver.SubscribeToRoomAsync(); } diff --git a/test/Rocket.Chat.Net.Tests/Integration/RoomFacts.cs b/test/Rocket.Chat.Net.Tests/Integration/RoomFacts.cs index 5b82160..23e1bd8 100644 --- a/test/Rocket.Chat.Net.Tests/Integration/RoomFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Integration/RoomFacts.cs @@ -11,6 +11,7 @@ using Rocket.Chat.Net.Driver; using Rocket.Chat.Net.Interfaces; using Rocket.Chat.Net.Models; + using Rocket.Chat.Net.Models.LoginOptions; using Rocket.Chat.Net.Tests.Helpers; using Xunit; @@ -237,7 +238,7 @@ private static async Task ComposeAsync() { var driver = new RocketChatDriver(Constants.RocketServer, false); await driver.ConnectAsync(); - await driver.LoginWithEmailAsync(Constants.OneEmail, Constants.OnePassword); + await driver.LoginWithEmailAsync(new EmailLoginOption() { Email = Constants.OneEmail, Password = Constants.OnePassword }); await driver.SubscribeToRoomListAsync(); return driver; diff --git a/test/Rocket.Chat.Net.Tests/Integration/SandboxFacts.cs b/test/Rocket.Chat.Net.Tests/Integration/SandboxFacts.cs index 12cf67d..d8a8a99 100644 --- a/test/Rocket.Chat.Net.Tests/Integration/SandboxFacts.cs +++ b/test/Rocket.Chat.Net.Tests/Integration/SandboxFacts.cs @@ -5,20 +5,23 @@ using Rocket.Chat.Net.Driver; using Rocket.Chat.Net.Tests.Helpers; + using NLog; + using Xunit; using Xunit.Abstractions; + using Rocket.Chat.Net.Models.LoginOptions; [Trait("Category", "Sandbox")] public class SandboxFacts : DriverFactsBase { // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable private readonly ITestOutputHelper _helper; - private readonly XUnitLogger _xUnitLogger; + private readonly ILogger _xUnitLogger; public SandboxFacts(ITestOutputHelper helper) : base(helper) { _helper = helper; - _xUnitLogger = new XUnitLogger(_helper); + _xUnitLogger = NLog.LogManager.GetCurrentClassLogger(); } [Fact(Skip = "skip")] @@ -31,7 +34,7 @@ public async Task Can_login() var driver = new RocketChatDriver(Constants.RocketServer, false, _xUnitLogger); await driver.ConnectAsync(); - var loginResult = await driver.LoginWithEmailAsync(Constants.OneEmail, Constants.OnePassword); + var loginResult = await driver.LoginWithEmailAsync(new EmailLoginOption() { Email = Constants.OneEmail, Password = Constants.OnePassword }); var roomId = await driver.GetRoomIdAsync("GENERAL"); @@ -56,7 +59,7 @@ public async Task Send_attachments() var driver = new RocketChatDriver(Constants.RocketServer, false, _xUnitLogger); await driver.ConnectAsync(); - await driver.LoginWithEmailAsync(userName, password); + await driver.LoginWithEmailAsync(new EmailLoginOption() { Email = Constants.OneEmail, Password = Constants.OnePassword }); var roomId = await driver.GetRoomIdAsync("GENERAL"); @@ -77,7 +80,6 @@ public async Task Clean_up_rooms() public override void Dispose() { - _xUnitLogger.Dispose(); } } } \ No newline at end of file diff --git a/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj b/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj index 5be1538..c9fc0e3 100644 --- a/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj +++ b/test/Rocket.Chat.Net.Tests/Rocket.Chat.Net.Tests.csproj @@ -211,7 +211,6 @@ - @@ -232,7 +231,6 @@ - From 0a51e8d1dbeda082e89efb460345ecb31ccc8bdd Mon Sep 17 00:00:00 2001 From: Antonio Zhu Date: Wed, 14 Dec 2022 16:05:29 +0100 Subject: [PATCH 11/14] Updated tests to work in VS2022 --- .../Resources/Resource.Designer.cs | 2 +- src/Rocket.Chat.Net.Example/App.config | 16 ++- src/Rocket.Chat.Net.Example/GiphyResponse.cs | 2 +- .../Rocket.Chat.Net.Example.csproj | 33 ++++- src/Rocket.Chat.Net.Example/packages.config | 11 +- src/Rocket.Chat.Net/Driver/RestClient.cs | 13 +- .../Driver/RocketChatDriver.cs | 8 ++ .../JsonConverters/RestApiConverter.cs | 39 ++++++ .../Models/RestResults/RestLoginResult.cs | 17 +++ .../Models/RestResults/RestResult.cs | 26 ++++ src/Rocket.Chat.Net/Rocket.Chat.Net.csproj | 1 + .../Rocket.Chat.Net.Bot.Tests.csproj | 34 +++++ test/Rocket.Chat.Net.Bot.Tests/app.config | 15 +++ .../Rocket.Chat.Net.Bot.Tests/packages.config | 11 ++ test/Rocket.Chat.Net.Tests/Driver/DdpFacts.cs | 2 +- .../Rocket.Chat.Net.Tests.csproj | 119 ++++++++++++++++-- test/Rocket.Chat.Net.Tests/app.config | 28 ++++- test/Rocket.Chat.Net.Tests/packages.config | 46 +++++-- 18 files changed, 388 insertions(+), 35 deletions(-) create mode 100644 src/Rocket.Chat.Net/JsonConverters/RestApiConverter.cs create mode 100644 src/Rocket.Chat.Net/Models/RestResults/RestLoginResult.cs create mode 100644 src/Rocket.Chat.Net/Models/RestResults/RestResult.cs create mode 100644 test/Rocket.Chat.Net.Bot.Tests/app.config diff --git a/src/Portability/Rocket.Chat.Net.Portability.Android/Resources/Resource.Designer.cs b/src/Portability/Rocket.Chat.Net.Portability.Android/Resources/Resource.Designer.cs index f1b0184..b8e8393 100644 --- a/src/Portability/Rocket.Chat.Net.Portability.Android/Resources/Resource.Designer.cs +++ b/src/Portability/Rocket.Chat.Net.Portability.Android/Resources/Resource.Designer.cs @@ -14,7 +14,7 @@ namespace Rocket.Chat.Net.Portability { - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "13.0.0.73")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "13.1.0.5")] public partial class Resource { diff --git a/src/Rocket.Chat.Net.Example/App.config b/src/Rocket.Chat.Net.Example/App.config index 4bfa005..94d1641 100644 --- a/src/Rocket.Chat.Net.Example/App.config +++ b/src/Rocket.Chat.Net.Example/App.config @@ -1,6 +1,18 @@ - + - + + + + + + + + + + + + + diff --git a/src/Rocket.Chat.Net.Example/GiphyResponse.cs b/src/Rocket.Chat.Net.Example/GiphyResponse.cs index 4910dcb..c50d667 100644 --- a/src/Rocket.Chat.Net.Example/GiphyResponse.cs +++ b/src/Rocket.Chat.Net.Example/GiphyResponse.cs @@ -38,7 +38,7 @@ public IEnumerable GetResponse(ResponseContext context, Rocket private string GetGiphy(string search) { - var request = new RestRequest("/v1/gifs/translate", Method.GET); + var request = new RestRequest("/v1/gifs/translate", Method.Get); request.AddQueryParameter("s", search); request.AddQueryParameter("rating", Rating); request.AddQueryParameter("api_key", GiphyApiKey); diff --git a/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj b/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj index d910d6f..0d57ed0 100644 --- a/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj +++ b/src/Rocket.Chat.Net.Example/Rocket.Chat.Net.Example.csproj @@ -48,20 +48,25 @@ v4.5 + + ..\..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll + ..\..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll ..\..\packages\NLog.5.1.0\lib\net46\NLog.dll - - ..\..\packages\RestSharp.105.2.3\lib\net45\RestSharp.dll - True + + ..\..\packages\RestSharp.108.0.3\lib\netstandard2.0\RestSharp.dll ..\..\packages\SuperSocket.ClientEngine.Core.0.10.0\lib\net45\SuperSocket.ClientEngine.dll + + ..\..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + ..\..\packages\System.Collections.Specialized.4.3.0\lib\net46\System.Collections.Specialized.dll True @@ -81,6 +86,9 @@ True True + + ..\..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll + ..\..\packages\System.Net.NameResolution.4.3.0\lib\net46\System.Net.NameResolution.dll True @@ -96,11 +104,18 @@ True True + + + ..\..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + ..\..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll True True + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll + ..\..\packages\System.Runtime.Extensions.4.3.0\lib\net462\System.Runtime.Extensions.dll True @@ -131,11 +146,23 @@ True True + + ..\..\packages\System.Text.Encodings.Web.5.0.0\lib\net461\System.Text.Encodings.Web.dll + + + ..\..\packages\System.Text.Json.5.0.1\lib\net461\System.Text.Json.dll + ..\..\packages\System.Text.RegularExpressions.4.3.0\lib\net463\System.Text.RegularExpressions.dll True True + + ..\..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + ..\..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll + diff --git a/src/Rocket.Chat.Net.Example/packages.config b/src/Rocket.Chat.Net.Example/packages.config index ea358ee..43a707c 100644 --- a/src/Rocket.Chat.Net.Example/packages.config +++ b/src/Rocket.Chat.Net.Example/packages.config @@ -1,25 +1,34 @@  + - + + + + + + + + + \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Driver/RestClient.cs b/src/Rocket.Chat.Net/Driver/RestClient.cs index a42c6be..17950a2 100644 --- a/src/Rocket.Chat.Net/Driver/RestClient.cs +++ b/src/Rocket.Chat.Net/Driver/RestClient.cs @@ -11,6 +11,7 @@ using WebSocketSharp; using RestSharp.Authenticators; using NLog.LayoutRenderers.Wrappers; +using Rocket.Chat.Net.Models.RestResults; namespace Rocket.Chat.Net.Driver { @@ -87,13 +88,17 @@ public void Dispose() public async Task LoginAsync(object args) { - JObject response = await CallAsync("POST", "login", CancellationToken.None, args).ConfigureAwait(false); - if (response["status"].ToObject() == "success") + var response = await CallAsync("POST", "login", CancellationToken.None, args).ConfigureAwait(false); + var result = response.ToObject>(); + if (result.Success) { - string authToken = response["status"]["authToken"].ToObject(); - string userId = response["status"]["userId"].ToObject(); + string authToken = result.Data.AuthToken; + string userId = result.Data.UserId; _client.Authenticator = new RocketAuthenticator(userId, authToken); _isLoggedIn = true; + } else + { + _logger.Error($"Login Error: {result.Error}"); } } } diff --git a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs index b740c94..6764452 100644 --- a/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs +++ b/src/Rocket.Chat.Net/Driver/RocketChatDriver.cs @@ -20,6 +20,7 @@ using Rocket.Chat.Net.Models.Collections; using Rocket.Chat.Net.Models.LoginOptions; using Rocket.Chat.Net.Models.MethodResults; + using Rocket.Chat.Net.Models.RestResults; using Rocket.Chat.Net.Models.SubscriptionResults; public class RocketChatDriver : IRocketChatDriver @@ -497,6 +498,13 @@ public async Task> SendCustomMessageAsync(Attachment return result.ToObject>(JsonSerializer); } + public async Task UploadFileToRoomAsync(string roomId, params object[] args) + { + var data = await _restClient.CallAsync("POST", $"rooms.upload/{roomId}", CancellationToken.None, args).ConfigureAwait(false); + return data.ToObject(JsonSerializer); + + } + public async Task UpdateMessageAsync(string messageId, string roomId, string newMessage) { _logger.Info($"Updating message {messageId}"); diff --git a/src/Rocket.Chat.Net/JsonConverters/RestApiConverter.cs b/src/Rocket.Chat.Net/JsonConverters/RestApiConverter.cs new file mode 100644 index 0000000..844cdd6 --- /dev/null +++ b/src/Rocket.Chat.Net/JsonConverters/RestApiConverter.cs @@ -0,0 +1,39 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Rocket.Chat.Net.JsonConverters +{ + public class RestApiConverter : JsonConverter + { + public override bool CanConvert(Type objectType) + { + if (objectType == typeof(string)) + return true; + else + return false; + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + var value = reader.Value; + if (value == null || String.IsNullOrWhiteSpace(value.ToString())) + { + return false; + } + + if ("success".Equals(value.ToString(), StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + return false; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new NotImplementedException(); + } + } +} diff --git a/src/Rocket.Chat.Net/Models/RestResults/RestLoginResult.cs b/src/Rocket.Chat.Net/Models/RestResults/RestLoginResult.cs new file mode 100644 index 0000000..c5e873a --- /dev/null +++ b/src/Rocket.Chat.Net/Models/RestResults/RestLoginResult.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Rocket.Chat.Net.Models.RestResults +{ + public class RestLoginResult + { + + public string UserId { get; set; } + + public string AuthToken { get; set; } + + public User Me { get; set; } + + } +} diff --git a/src/Rocket.Chat.Net/Models/RestResults/RestResult.cs b/src/Rocket.Chat.Net/Models/RestResults/RestResult.cs new file mode 100644 index 0000000..892cec1 --- /dev/null +++ b/src/Rocket.Chat.Net/Models/RestResults/RestResult.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using Newtonsoft.Json; +using Rocket.Chat.Net.JsonConverters; + +namespace Rocket.Chat.Net.Models.RestResults +{ + public class RestResult + { + [JsonProperty(PropertyName = "_id")] + public string Id { get; set; } + + [JsonConverter(typeof(RestApiConverter))] + public bool Success { get; set; } + + public string Error { get; set; } + } + + public class RestResult : RestResult + { + public T Data { get; set; } + } +} \ No newline at end of file diff --git a/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj b/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj index 8736b3f..7016b8c 100644 --- a/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj +++ b/src/Rocket.Chat.Net/Rocket.Chat.Net.csproj @@ -13,6 +13,7 @@ + diff --git a/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj b/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj index 66d9750..ba88493 100644 --- a/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj +++ b/test/Rocket.Chat.Net.Bot.Tests/Rocket.Chat.Net.Bot.Tests.csproj @@ -1,5 +1,6 @@  + Debug @@ -47,6 +48,9 @@ ..\..\packages\FluentAssertions.4.9.1\lib\net45\FluentAssertions.Core.dll True + + ..\..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll + ..\..\packages\NLog.5.1.0\lib\net46\NLog.dll @@ -58,9 +62,37 @@ ..\..\packages\AutoFixture.3.47.8\lib\net40\Ploeh.AutoFixture.dll True + + ..\..\packages\RestSharp.108.0.3\lib\netstandard2.0\RestSharp.dll + + + ..\..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + ..\..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll + + + + ..\..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll + + + ..\..\packages\System.Text.Encodings.Web.5.0.0\lib\net461\System.Text.Encodings.Web.dll + + + ..\..\packages\System.Text.Json.5.0.1\lib\net461\System.Text.Json.dll + + + ..\..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + ..\..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll + @@ -104,6 +136,7 @@ + @@ -131,6 +164,7 @@ This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. +