96 lines
2.1 KiB
C#
96 lines
2.1 KiB
C#
using NLog;
|
|
|
|
namespace ChatRoom;
|
|
|
|
public class ChatRoomLogic
|
|
{
|
|
private Thread thread;
|
|
private ChatRoomState state = new ChatRoomState();
|
|
private Logger log = LogManager.GetCurrentClassLogger();
|
|
|
|
|
|
public ChatRoomLogic()
|
|
{
|
|
thread = new Thread(BackgroundTask);
|
|
thread.Start();
|
|
}
|
|
|
|
int NextId()
|
|
{
|
|
int id = state.lastUniqueId;
|
|
state.lastUniqueId++;
|
|
return id;
|
|
}
|
|
|
|
public int RegisterClient(string name)
|
|
{
|
|
lock (state.accessLock)
|
|
{
|
|
int clientId = NextId();
|
|
state.clients.Add(new Client
|
|
{
|
|
id = clientId,
|
|
name = name
|
|
});
|
|
log.Info($"Registered with client '{name}' with id {clientId}");
|
|
return clientId;
|
|
}
|
|
}
|
|
|
|
Client? FindClientById(int clientId)
|
|
{
|
|
foreach (var client in state.clients)
|
|
{
|
|
if (client.id == clientId)
|
|
{
|
|
return client;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public bool SendMessage(int clientId, string contents, bool needsToBeCensored)
|
|
{
|
|
lock (state.accessLock)
|
|
{
|
|
var client = FindClientById(clientId);
|
|
if (client == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (client.blockedUntil != null)
|
|
{
|
|
if (DateTime.UtcNow < client.blockedUntil)
|
|
{
|
|
return false;
|
|
}
|
|
else
|
|
{
|
|
client.blockedUntil = null;
|
|
}
|
|
}
|
|
|
|
state.messages.Add(new Message
|
|
{
|
|
id = NextId(),
|
|
clientId = clientId,
|
|
contents = contents,
|
|
needsToBeCensored = needsToBeCensored,
|
|
status = MessageStatus.WaitingApproval
|
|
});
|
|
log.Info($"Client '{client.name}' ({client.id}) sent message '{contents}'. Needs to censored: {needsToBeCensored}");
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public void BackgroundTask()
|
|
{
|
|
while (true)
|
|
{
|
|
|
|
}
|
|
}
|
|
}
|