Client library reviewed.
All checks were successful
Pack and Push NuGet Package / publish (push) Successful in 43s

This commit is contained in:
2025-07-05 03:29:44 +02:00
parent 311b70cbb4
commit 904b244e76
13 changed files with 239 additions and 53 deletions

View File

@ -22,14 +22,14 @@ jobs:
uses: actions/checkout@v3
- name: Restore dependencies
run: dotnet restore ./code/MessengerApi.Contracts/MessengerApi.Contracts.csproj
run: dotnet restore ./code/MessengerApi.Client/MessengerApi.Client.csproj
- name: Build project
run: dotnet build ./code/MessengerApi.Contracts/MessengerApi.Contracts.csproj -c Release
run: dotnet build ./code/MessengerApi.Client/MessengerApi.Client.csproj -c Release
- name: Pack NuGet Package
run: |
dotnet pack ./code/MessengerApi.Contracts/MessengerApi.Contracts.csproj -c Release -o out
dotnet pack ./code/MessengerApi.Client/MessengerApi.Client.csproj -c Release -o out
- name: Push to Gitea NuGet Registry
run: |

View File

@ -1,12 +1,5 @@
<Project>
<ItemGroup>
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="9.0.6" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.6" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.6" />
<PackageVersion Include="portaloggy" Version="1.0.2" />
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.6" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="7.1.0" />
</ItemGroup>
</Project>

7
README.md Normal file
View File

@ -0,0 +1,7 @@
# messengerapi.Client
[!["send me a tip"](https://img.shields.io/badge/give%20me%20a%20-tip-FFD200)](https://paypal.me/emsicz) [!["see my github"](https://img.shields.io/badge/see%20my%20-github-1F2328)](https://github.com/masiton?tab=repositories)
Messenger API consumer library. Instead of crafting HTTP requests and parsing responses, you can use this wrapper to consume the API in a strongly-typed fashion in .NET.
![example](./assets/example.jpeg)

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\MessengerApi.Client\MessengerApi.Client.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,59 @@
using MessengerApi.Model;
using MessengerApi.Model.Messages;
namespace MessengerApi.Example
{
internal class Program
{
static void Main(string[] args)
{
var client1 = new Client(
new Credentials(
"aab8f7e9-ad13-4bf8-bb2e-0cd93d81adc0",
"http://localhost:5259"));
var client2 = new Client(
new Credentials(
"8f73f683-7cb3-40df-998e-6e604aef0e53",
"http://localhost:5259"));
var user1 = Guid.Parse("f696442b-e8dc-4074-b34f-94bcece8e74b");
var user2 = Guid.Parse("15d97720-f5b7-47aa-9c1a-71f98b0b9248");
var messageId = client1.SendMessage(new OutboxMessage
{
ToUserId = user2,
PayloadType = "TEST",
Payload = "TEST"
});
var state = client1.Verify(messageId);
if (state.IsDelivered != false)
{
throw new Exception();
}
var peeking = client2.Peek();
if (peeking != 1)
{
throw new Exception();
}
var receive = client2.GetMessages();
if (receive.Count() != 1)
{
throw new Exception();
}
state = client1.Verify(messageId);
if (state.IsDelivered != true)
{
throw new Exception();
}
}
}
}

View File

@ -3,13 +3,10 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35312.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MessengerApi.Contracts", "MessengerApi.Contracts\MessengerApi.Contracts.csproj", "{833ED77F-A4E9-4FB3-BB84-4E55898B726A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MessengerApi.SubscriptionClient", "MessengerApi.SubscriptionClient\MessengerApi.SubscriptionClient.csproj", "{127D24B0-47F3-40E9-9136-899AFF206F19}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MessengerApi.QueryClient", "MessengerApi.QueryClient\MessengerApi.QueryClient.csproj", "{6441673B-2621-4E2C-A9A0-971E83C3F80A}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8EC462FD-D22E-90A8-E5CE-7E832BA40C5D}"
ProjectSection(SolutionItems) = preProject
..\Directory.Packages.props = ..\Directory.Packages.props
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
ProjectSection(SolutionItems) = preProject
@ -18,24 +15,24 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".gitea", ".gitea", "{C3305381-7A52-4E26-9527-1697692DDD5A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MessengerApi.Client", "MessengerApi.Client\MessengerApi.Client.csproj", "{67EE7DA2-D248-E323-15E8-30F464EB556E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MessengerApi.Client.Example", "MessengerApi.Client.Example\MessengerApi.Client.Example.csproj", "{43F1DDF3-153B-70C6-E626-2031C5D71926}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{833ED77F-A4E9-4FB3-BB84-4E55898B726A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{833ED77F-A4E9-4FB3-BB84-4E55898B726A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{833ED77F-A4E9-4FB3-BB84-4E55898B726A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{833ED77F-A4E9-4FB3-BB84-4E55898B726A}.Release|Any CPU.Build.0 = Release|Any CPU
{127D24B0-47F3-40E9-9136-899AFF206F19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{127D24B0-47F3-40E9-9136-899AFF206F19}.Debug|Any CPU.Build.0 = Debug|Any CPU
{127D24B0-47F3-40E9-9136-899AFF206F19}.Release|Any CPU.ActiveCfg = Release|Any CPU
{127D24B0-47F3-40E9-9136-899AFF206F19}.Release|Any CPU.Build.0 = Release|Any CPU
{6441673B-2621-4E2C-A9A0-971E83C3F80A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6441673B-2621-4E2C-A9A0-971E83C3F80A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6441673B-2621-4E2C-A9A0-971E83C3F80A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6441673B-2621-4E2C-A9A0-971E83C3F80A}.Release|Any CPU.Build.0 = Release|Any CPU
{67EE7DA2-D248-E323-15E8-30F464EB556E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{67EE7DA2-D248-E323-15E8-30F464EB556E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{67EE7DA2-D248-E323-15E8-30F464EB556E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{67EE7DA2-D248-E323-15E8-30F464EB556E}.Release|Any CPU.Build.0 = Release|Any CPU
{43F1DDF3-153B-70C6-E626-2031C5D71926}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{43F1DDF3-153B-70C6-E626-2031C5D71926}.Debug|Any CPU.Build.0 = Debug|Any CPU
{43F1DDF3-153B-70C6-E626-2031C5D71926}.Release|Any CPU.ActiveCfg = Release|Any CPU
{43F1DDF3-153B-70C6-E626-2031C5D71926}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -1,13 +1,16 @@
using portaloggy;
using MessengerApi.Model;
using MessengerApi.Model.Messages;
using portaloggy;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace MessengerApi.Contracts
namespace MessengerApi
{
/// <summary>
/// Exists for mocking reason. This is implemented by <see cref="MessengerClient"/>.
/// Exists for mocking reason. This is implemented by <see cref="Client"/>.
/// </summary>
public interface IMessengerClient
public interface IClient
{
/// <summary>
/// Receives pending messages from the messenger API.
@ -20,38 +23,51 @@ namespace MessengerApi.Contracts
/// </summary>
void AckMessage(InboxMessage message);
/// <summary>
/// Acknowledges message reception to the server.
/// </summary>
/// <param name="messageId"></param>
void AckMessage(Guid messageId);
/// <summary>
/// Sends a message.
/// </summary>
/// <param name="credentials">Credentials to the API.</param>
void SendMessage(OutboxMessage outboxMessage);
Guid SendMessage(OutboxMessage outboxMessage);
/// <summary>
/// Returns user ids for allowed message recipients.
/// </summary>
Contact[] GetYellowPages();
/// <summary>
/// Returns number of pending messages, waiting for delivery.
/// </summary>
int Peek();
/// <summary>
/// Gets delivery state of a message.
/// </summary>
State Verify(Guid messageId);
}
public class MessengerClient : IMessengerClient
public class Client : IClient
{
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
private DateTime _lastReceivedUtc;
private Credentials _credentials;
public MessengerClient(Credentials credentials, HttpClient httpClient = null, ILogger logger = null)
public Client(Credentials credentials, HttpClient httpClient = null, ILogger logger = null)
{
_credentials = credentials;
_httpClient = httpClient ?? new HttpClient();
_logger = logger ?? new ConsoleLogger();
_lastReceivedUtc = DateTime.MinValue.ToUniversalTime();
}
public IEnumerable<InboxMessage> GetMessages()
{
var since = Uri.EscapeDataString(this._lastReceivedUtc.ToString("o"));
var url = $"{_credentials.ApiUrl}/receive?sinceUtc={since}";
var url = $"{_credentials.ApiUrl}/receive";
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _credentials.ApiKey);
@ -85,11 +101,6 @@ namespace MessengerApi.Contracts
foreach (var item in json["messages"].AsArray())
{
if (item["id"].GetValue<int>() == -1)
{
continue;
}
messages.Add(new InboxMessage
{
Id = item["id"].GetValue<Guid>(),
@ -99,13 +110,12 @@ namespace MessengerApi.Contracts
});
}
_lastReceivedUtc = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(10));
_logger.Debug($"Received {messages.Count} messages and last check timestamp is set to {_lastReceivedUtc.ToString("s")}.");
_logger.Debug($"Received {messages.Count} messages.");
return messages.ToArray();
}
public void SendMessage(OutboxMessage outboxMessage)
public Guid SendMessage(OutboxMessage outboxMessage)
{
var body = new JsonObject();
@ -133,6 +143,7 @@ namespace MessengerApi.Contracts
var url = $"{_credentials.ApiUrl}/send";
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = content;
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _credentials.ApiKey);
_logger.Debug($"Sending query to {url} with content {body.ToString()} to obtain messages.");
@ -144,6 +155,10 @@ namespace MessengerApi.Contracts
_logger.Error(response.ReasonPhrase);
throw new HttpRequestException("Can't send.", null, response.StatusCode);
}
var responseString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var guid = JsonSerializer.Deserialize<Guid>(responseString);
return guid;
}
public Contact[] GetYellowPages()
@ -180,7 +195,90 @@ namespace MessengerApi.Contracts
public void AckMessage(InboxMessage message)
{
this.AckMessage(message.Id);
}
public void AckMessage(Guid messageId)
{
var body = new JsonObject
{
{ "messageId", JsonValue.Create<Guid>(messageId) }
};
var content = new StringContent(body.ToString(), Encoding.UTF8, "application/json");
var url = $"{_credentials.ApiUrl}/ack";
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _credentials.ApiKey);
_logger.Debug($"Sending query to {url} with content {body.ToString()} to obtain messages.");
var response = _httpClient.Send(request);
if (!response.IsSuccessStatusCode)
{
_logger.Error(response.ReasonPhrase);
throw new HttpRequestException("Can't send.", null, response.StatusCode);
}
}
public int Peek()
{
var url = $"{_credentials.ApiUrl}/peek";
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _credentials.ApiKey);
_logger.Debug($"Sending query to {url} with content {request.ToString()} to obtain messages.");
var response = _httpClient.Send(request);
if (!response.IsSuccessStatusCode)
{
_logger.Error(response.ReasonPhrase);
throw new HttpRequestException("Can't receive.", null, response.StatusCode);
}
var responseContent = response.Content
.ReadAsStringAsync()
.GetAwaiter()
.GetResult();
if (!string.IsNullOrWhiteSpace(responseContent))
{
_logger.Debug($"Received response of {responseContent}.");
return int.Parse(responseContent);
}
throw new InvalidOperationException("Unreadable response.");
}
public State Verify(Guid messageId)
{
var url = $"{_credentials.ApiUrl}/verify?messageId={messageId}";
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _credentials.ApiKey);
_logger.Debug($"Sending query to {url} to get message state.");
var response = _httpClient.Send(request);
if (!response.IsSuccessStatusCode)
{
_logger.Error(response.ReasonPhrase);
throw new HttpRequestException("Can't receive.", null, response.StatusCode);
}
var responseContent = response.Content
.ReadAsStringAsync()
.GetAwaiter()
.GetResult();
if (!string.IsNullOrWhiteSpace(responseContent))
{
return JsonSerializer.Deserialize<State>(responseContent);
}
throw new InvalidOperationException("Unreadable response.");
}
}
}

View File

@ -15,6 +15,10 @@
<RepositoryUrl>https://gitea.masita.net/mc/messengerapi-tools</RepositoryUrl>
<PackageTags>logging;log;logger</PackageTags>
<PackageLicenseExpression>mit-0</PackageLicenseExpression>
<Description>Messenger API consumer library for .NET.</Description>
<Copyright>mc @ 2024</Copyright>
<Authors>mc</Authors>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>

View File

@ -1,4 +1,4 @@
namespace MessengerApi.Contracts
namespace MessengerApi.Model
{
public class Contact
{

View File

@ -1,4 +1,4 @@
namespace MessengerApi.Contracts
namespace MessengerApi.Model
{
public class Credentials
{

View File

@ -1,4 +1,4 @@
namespace MessengerApi.Contracts
namespace MessengerApi.Model.Messages
{
/// <summary>
/// Message when received is inbox. For server apps, this is request-type of message. For clients, this is a response-type of message.

View File

@ -1,4 +1,4 @@
namespace MessengerApi.Contracts
namespace MessengerApi.Model.Messages
{
/// <summary>
/// Outbox type of message. A server-app will treat this as a response. A client app will treat this as a request.

View File

@ -0,0 +1,13 @@
using System.Text.Json.Serialization;
namespace MessengerApi.Model
{
public class State
{
[JsonPropertyName("isDelivered")]
public bool IsDelivered { get; set; }
[JsonPropertyName("isAcknowledged")]
public bool IsAcknowledged { get; set; }
}
}