Initial commit carried over from private repo. This is V2.
This commit is contained in:
60
code/MessengerApi/Handlers/Endpoint/SendEndpointHandler.cs
Normal file
60
code/MessengerApi/Handlers/Endpoint/SendEndpointHandler.cs
Normal file
@ -0,0 +1,60 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user