Skip to content

Commit

Permalink
Added rest client which will be needed for Attachments
Browse files Browse the repository at this point in the history
  • Loading branch information
Antonio Zhu committed Dec 7, 2022
1 parent 1ca3335 commit bfee073
Show file tree
Hide file tree
Showing 6 changed files with 160 additions and 0 deletions.
119 changes: 119 additions & 0 deletions src/Rocket.Chat.Net/Driver/RestClient.cs
Original file line number Diff line number Diff line change
@@ -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; }

/// <summary>
///
/// </summary>
/// <param name="method">HTTP method, such as GET, POST, PUT etc.</param>
/// <param name="path"></param>
/// <param name="token"></param>
/// <param name="args"></param>
/// <returns></returns>
public async Task<JObject> 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<String>() == "success")
{
string authToken = response["status"]["authToken"].ToObject<String>();
string userId = response["status"]["userId"].ToObject<String>();
_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();
}
}
}
9 changes: 9 additions & 0 deletions src/Rocket.Chat.Net/Driver/RocketChatDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -250,6 +253,7 @@ public async Task PingAsync()
await _client.PingAsync(TimeoutToken).ConfigureAwait(false);
}

// TODO: Reuse login option for REST?
public async Task<MethodResult<LoginResult>> LoginAsync(ILoginOption loginOption)
{
var ldapLogin = loginOption as LdapLoginOption;
Expand Down Expand Up @@ -695,5 +699,10 @@ private CancellationToken CreateTimeoutToken()

return source.Token;
}

public async Task LoginRestApi(object args)
{
await _restClient.LoginAsync(args).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
18 changes: 18 additions & 0 deletions src/Rocket.Chat.Net/Interfaces/IRestClient.cs
Original file line number Diff line number Diff line change
@@ -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<JObject> CallAsync(string method, string path, CancellationToken token, params object[] args);
Task LoginAsync(object args);

}
}
1 change: 1 addition & 0 deletions src/Rocket.Chat.Net/Interfaces/IRocketChatDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Rocket.Chat.Net.Interfaces.Driver;

public interface IRocketChatDriver : IDisposable,
IRocketRestClientManagement,
IRocketClientManagement,
IRocketUserManagement,
IRocketMessagingManagement,
Expand Down
1 change: 1 addition & 0 deletions src/Rocket.Chat.Net/Rocket.Chat.Net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="NLog" Version="5.1.0" />
<PackageReference Include="Otp.NET" Version="1.2.2" />
<PackageReference Include="RestSharp" Version="108.0.3" />
<PackageReference Include="WebSocket4Net" Version="0.15.2" />
<PackageReference Include="WebsocketSharp.Standard2" Version="2022.4.16.1520" />
</ItemGroup>
Expand Down

0 comments on commit bfee073

Please sign in to comment.