sharp-chat/SharpChat/PacketHandlers/PingHandler.cs

52 lines
1.7 KiB
C#
Raw Normal View History

2023-02-16 21:16:06 +00:00
using SharpChat.Misuzu;
using SharpChat.Packet;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace SharpChat.PacketHandlers {
public class PingHandler : IPacketHandler {
2023-02-16 21:16:06 +00:00
private readonly MisuzuClient Misuzu;
private readonly TimeSpan BumpInterval = TimeSpan.FromMinutes(1);
private DateTimeOffset LastBump = DateTimeOffset.MinValue;
public PingHandler(MisuzuClient msz) {
Misuzu = msz;
2023-02-16 21:16:06 +00:00
}
public bool IsMatch(PacketHandlerContext ctx) {
2023-02-16 21:16:06 +00:00
return ctx.CheckPacketId("0");
}
public void Handle(PacketHandlerContext ctx) {
2023-02-16 21:16:06 +00:00
string[] parts = ctx.SplitText(2);
if(!int.TryParse(parts.FirstOrDefault(), out int pTime))
return;
2023-02-16 21:25:41 +00:00
ctx.Connection.BumpPing();
2024-05-10 17:28:52 +00:00
ctx.Connection.Send(new PongPacket());
2023-02-16 21:16:06 +00:00
ctx.Chat.ContextAccess.Wait();
try {
2023-02-16 21:16:06 +00:00
if(LastBump < DateTimeOffset.UtcNow - BumpInterval) {
2024-05-19 21:02:17 +00:00
(string, string)[] bumpList = ctx.Chat.Users.All
.Where(u => u.Status == UserStatus.Online && ctx.Chat.Connections.Any(c => c.User == u))
2023-02-19 22:27:08 +00:00
.Select(u => (u.UserId.ToString(), ctx.Chat.GetRemoteAddresses(u).FirstOrDefault()?.ToString() ?? string.Empty))
.ToArray();
2023-02-16 21:16:06 +00:00
if(bumpList.Any())
Task.Run(async () => {
await Misuzu.BumpUsersOnlineAsync(bumpList);
}).Wait();
LastBump = DateTimeOffset.UtcNow;
}
} finally {
ctx.Chat.ContextAccess.Release();
2023-02-16 21:16:06 +00:00
}
}
}
}