Files
messengerapi/code/MessengerApi/Handlers/Endpoint/SendEndpointHandler.cs
masiton 4393977389
All checks were successful
Build and Push Docker Image / build (push) Successful in 1m3s
Build and Push Docker Image / docker (push) Successful in 43s
Initial commit carried over from private repo. This is V2.
2025-07-04 21:24:12 +02:00

60 lines
2.0 KiB
C#

using MessengerApi.Configuration.Model;
using MessengerApi.Contracts.Models.Scoped;
using MessengerApi.Db.Entities;
using MessengerApi.Models.Scoped;
namespace MessengerApi.Handlers.Endpoint
{
public class SendEndpointHandler
{
private readonly MessengerConfiguration configuration;
private readonly ILogger logger;
private readonly Timing timing;
private readonly Identity identity;
private readonly IUnitOfWork unitOfWork;
public SendEndpointHandler(
MessengerConfiguration configuration,
ILogger logger,
IUnitOfWork unitOfWork,
Timing timing,
Identity identity)
{
this.configuration = configuration;
this.logger = logger;
this.unitOfWork = unitOfWork;
this.timing = timing;
this.identity = identity;
}
public Task<Message> SendMessage(
Guid? toUserId,
string payload,
string payloadType,
int? payloadLifespanInSeconds)
{
// Authorize.
var targetRecipientId = toUserId.HasValue
? this.identity.UserRoutes.Single(x => x.From.Id == this.identity.User.Id && x.To.Id == toUserId.Value).To.Id
: this.identity.UserRoutes.Single().To.Id;
this.logger.Debug($"[{this.timing.Timestamp:s}] User {this.identity.User.Name} is authorized to send message to {targetRecipientId}.");
// Act.
var message = new Message
{
Id = Guid.NewGuid(),
CreatedUtc = this.timing.Timestamp,
FromId = this.identity.User.Id,
ToId = targetRecipientId,
Payload = payload,
PayloadType = payloadType,
PayloadLifespanInSeconds = payloadLifespanInSeconds ?? (this.configuration.DefaultMessageLifetimeInMinutes * 60)
};
this.unitOfWork.Messages.Add(message);
return Task.FromResult(message);
}
}
}