108 lines
2.9 KiB
C#
108 lines
2.9 KiB
C#
using ChatRoomContract;
|
|
using NLog;
|
|
using Bogus;
|
|
|
|
namespace Participant;
|
|
|
|
internal class Participant
|
|
{
|
|
/// <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 rnd = new Random();
|
|
|
|
var name = faker.Name.FullName();
|
|
int clientId = chatRoom.RegisterClient(name);
|
|
log.Info($"Registered with client id {clientId}");
|
|
|
|
while (true)
|
|
{
|
|
int strikes = chatRoom.GetStrikes(clientId);
|
|
Console.Title = $"Participant | {name} | {clientId} | {strikes} Strikes";
|
|
|
|
var message = string.Join(" ", faker.Lorem.Words(5));
|
|
bool needsToBeCensored = rnd.Next(0, 100) > 50;
|
|
if (chatRoom.SendMessage(clientId, message, needsToBeCensored))
|
|
{
|
|
log.Info("Sent message");
|
|
}
|
|
else
|
|
{
|
|
log.Info("Failed to send message, blocked");
|
|
var blockedUntil = chatRoom.GetBlockedUntil(clientId);
|
|
var now = DateTime.UtcNow;
|
|
if (blockedUntil != null && blockedUntil > now)
|
|
{
|
|
var delta = blockedUntil.Value - now;
|
|
log.Info($"Waiting {delta.TotalSeconds:F3}s until block expires");
|
|
Thread.Sleep((int)delta.TotalMilliseconds);
|
|
}
|
|
}
|
|
|
|
Thread.Sleep(2 * 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 Participant();
|
|
self.Run();
|
|
}
|
|
}
|