103 lines
3.6 KiB
C#
103 lines
3.6 KiB
C#
using MessengerBroker.Handlers;
|
|
using MessengerBroker.Model.Http;
|
|
using System.Runtime.CompilerServices;
|
|
|
|
namespace MessengerBroker
|
|
{
|
|
public class Program
|
|
{
|
|
public static void Main(string[] args)
|
|
{
|
|
var settings = (Settings)null;
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
var app = builder.Build();
|
|
|
|
app.MapGet("/users", async (HttpContext httpContext) =>
|
|
{
|
|
var authHandler = app.Services.GetService<AuthHandler>();
|
|
var brokerId = authHandler.Auth(httpContext);
|
|
|
|
if(brokerId == null)
|
|
{
|
|
return Results.Unauthorized();
|
|
}
|
|
|
|
var dataHandler = app.Services.GetService<DataHandler>();
|
|
var usersAndRoutes = await dataHandler.GetLocalUsersAndRoutes();
|
|
|
|
var response = new Users.UsersResponse
|
|
{
|
|
Users = usersAndRoutes.Item1.Select(x => new Users.UsersResponse.User
|
|
{
|
|
Id = x.Id,
|
|
Name = x.Name,
|
|
ApiKey = x.ApiKey,
|
|
CanReceive = x.CanReceive,
|
|
CanSend = x.CanSend,
|
|
IsEnabled = x.IsEnabled,
|
|
}).ToArray(),
|
|
UserRoutes = usersAndRoutes.Item2.Select(x => new Users.UsersResponse.UserRoute
|
|
{
|
|
Id = x.Id,
|
|
FromId = x.From.Id,
|
|
ToId = x.To.Id
|
|
}).ToArray()
|
|
};
|
|
|
|
return Results.Json(response);
|
|
});
|
|
|
|
app.MapGet("/sync", async (HttpContext httpContext, [AsParameters] Sync.SyncRequest request) =>
|
|
{
|
|
var authHandler = app.Services.GetService<AuthHandler>();
|
|
var brokerId = authHandler.Auth(httpContext);
|
|
|
|
if(brokerId == null)
|
|
{
|
|
return Results.Unauthorized();
|
|
}
|
|
else if(request.BrokerId != brokerId && request.BrokerId != settings.BrokerId)
|
|
{
|
|
return Results.Unauthorized();
|
|
}
|
|
|
|
var dataHandler = app.Services.GetService<DataHandler>();
|
|
var messages = await dataHandler.GetMessages(request.BrokerId, request.SinceUtc);
|
|
|
|
var response = new Sync.SyncResponse
|
|
{
|
|
Messages = messages.Select(x => new Sync.SyncResponse.Message
|
|
{
|
|
Id = x.Id,
|
|
CreatedUtc = x.CreatedUtc,
|
|
From = x.From.Id,
|
|
To = x.To.Id,
|
|
IsAcknowledged = x.IsAcknowledged,
|
|
IsDelivered = x.IsDelivered,
|
|
Payload = x.Payload,
|
|
PayloadId = x.PayloadId,
|
|
PayloadLifespanInSeconds = x.PayloadLifespanInSeconds,
|
|
PayloadTimestamp = x.PayloadTimestamp,
|
|
PayloadType = x.PayloadType
|
|
}).ToArray()
|
|
};
|
|
|
|
return Results.Json(response);
|
|
});
|
|
|
|
_ = Task.Run(async () =>
|
|
{
|
|
var cts = new CancellationTokenSource();
|
|
var handler = app.Services.GetService<MasterHandler>();
|
|
|
|
foreach(var master in settings.Masters)
|
|
{
|
|
_ = handler.BeginSyncingWithMaster(master, cts.Token);
|
|
}
|
|
});
|
|
|
|
app.Run();
|
|
}
|
|
}
|
|
}
|