60 lines
2.0 KiB
C#
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? timeToLiveInSeconds)
|
|
{
|
|
// 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,
|
|
TimeToLiveInSeconds = timeToLiveInSeconds ?? (this.configuration.DefaultMessageTimeToLiveInSeconds)
|
|
};
|
|
|
|
this.unitOfWork.Messages.Add(message);
|
|
return Task.FromResult(message);
|
|
}
|
|
}
|
|
} |