1
0
tinklu-paslaugos/Lab3/Moderator/Moderator.cs
2024-11-16 16:44:29 +02:00

103 lines
2.5 KiB
C#

using ChatRoomContract;
using NLog;
using Bogus;
namespace Moderator;
internal class Moderator
{
/// <summary>
/// Logger for this class.
/// </summary>
Logger log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Configures logging subsystem.
/// </summary>
private void ConfigureLogging()
{
var config = new NLog.Config.LoggingConfiguration();
var console =
new NLog.Targets.ConsoleTarget("console")
{
Layout = @"${date:format=HH\:mm\:ss}|${level}| ${message} ${exception}"
};
config.AddTarget(console);
config.AddRuleForAllLevels(console);
LogManager.Configuration = config;
}
/// <summary>
/// Run with a given service
/// </summary>
/// <param name="chatRoom">Chat room service</param>
private void RunConnection(IChatRoomService chatRoom)
{
var faker = new Faker("en");
var name = faker.Name.FullName();
int clientId = chatRoom.RegisterClient(name);
log.Info($"Registered with client id {clientId}");
Console.Title = $"Moderator | {name} | {clientId}";
while (true)
{
var message = chatRoom.GetNewMessage();
if (message != null)
{
log.Info($"Checking message ({message.id}): {message.contents}");
Thread.Sleep(500);
if (message.needsToBeCensored)
{
chatRoom.RejectMessage(message.id);
}
else
{
chatRoom.ApproveMessage(message.id);
}
}
Thread.Sleep(1 * 1000);
}
}
/// <summary>
/// Main loop
/// </summary>
private void Run()
{
ConfigureLogging();
while (true)
{
var chatRoom = new ChatRoomClient(Config.CreateConnection(), Config.ExchangeName, Config.CreateClientQueueName(), Config.ServerQueueName);
try
{
RunConnection(chatRoom);
}
catch (Exception e)
{
//log whatever exception to console
log.Warn(e, "Unhandled exception caught. Will restart main loop.");
//prevent console spamming
Thread.Sleep(2000);
}
}
}
/// <summary>
/// Entry point
/// </summary>
static void Main()
{
var self = new Moderator();
self.Run();
}
}