1
0
tinklu-paslaugos/Lab1/ChatRoom/ChatRoomLogic.cs

114 lines
2.6 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 ChatRoomContract.Message? GetNewMessage()
{
foreach (var message in state.messages)
{
if (message.given) continue;
if (message.status != MessageStatus.WaitingApproval) continue;
message.given = true;
return new ChatRoomContract.Message{
id = message.id,
contents = message.contents,
needsToBeCensored = message.needsToBeCensored
};
}
return null;
}
public void BackgroundTask()
{
while (true)
{
}
}
}