sharp-chat/SharpChat/PacketHandlers/PingHandler.cs

57 lines
2 KiB
C#

using SharpChat.Misuzu;
using SharpChat.Packet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SharpChat.PacketHandlers {
public class PingHandler : IChatPacketHandler {
private readonly MisuzuClient Misuzu;
private readonly object BumpAccess = new();
private readonly TimeSpan BumpInterval = TimeSpan.FromMinutes(1);
private DateTimeOffset LastBump = DateTimeOffset.MinValue;
public PingHandler(MisuzuClient msz) {
Misuzu = msz ?? throw new ArgumentNullException(nameof(msz));
}
public bool IsMatch(ChatPacketHandlerContext ctx) {
return ctx.CheckPacketId("0");
}
public void Handle(ChatPacketHandlerContext ctx) {
string[] parts = ctx.SplitText(2);
if(!int.TryParse(parts.FirstOrDefault(), out int pTime))
return;
ctx.Connection.BumpPing();
ctx.Connection.Send(new PongPacket(ctx.Connection.LastPing));
lock(BumpAccess) {
if(LastBump < DateTimeOffset.UtcNow - BumpInterval) {
(string, string)[] bumpList;
lock(ctx.Chat.UsersAccess) {
IEnumerable<ChatUser> filtered = ctx.Chat.Users.Where(u => u.Status == ChatUserStatus.Online);
lock(ctx.Chat.ConnectionsAccess)
filtered = filtered.Where(u => ctx.Chat.Connections.Any(c => c.User == u));
bumpList = filtered
.Select(u => (u.UserId.ToString(), ctx.Chat.GetRemoteAddresses(u).FirstOrDefault()?.ToString() ?? string.Empty))
.ToArray();
}
if(bumpList.Any())
Task.Run(async () => {
await Misuzu.BumpUsersOnlineAsync(bumpList);
}).Wait();
LastBump = DateTimeOffset.UtcNow;
}
}
}
}
}