sharp-chat/SharpChat/PacketHandlers/PingHandler.cs

61 lines
1.9 KiB
C#
Raw Normal View History

2023-02-16 21:16:06 +00:00
using SharpChat.Misuzu;
using SharpChat.Packet;
using System;
2024-05-20 16:16:32 +00:00
using System.Collections.Generic;
2023-02-16 21:16:06 +00:00
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-20 16:16:32 +00:00
List<(string, string)> bumpList = new();
2023-02-16 21:16:06 +00:00
2024-05-20 16:16:32 +00:00
foreach(UserInfo userInfo in ctx.Chat.Users.All) {
if(userInfo.Status != UserStatus.Online)
continue;
string[] remoteAddrs = ctx.Chat.Connections.GetUserRemoteAddresses(userInfo);
if(remoteAddrs.Length < 1)
continue;
bumpList.Add((userInfo.UserId.ToString(), remoteAddrs[0]));
}
if(bumpList.Count > 0)
2023-02-16 21:16:06 +00:00
Task.Run(async () => {
await Misuzu.BumpUsersOnlineAsync(bumpList);
}).Wait();
LastBump = DateTimeOffset.UtcNow;
}
} finally {
ctx.Chat.ContextAccess.Release();
2023-02-16 21:16:06 +00:00
}
}
}
}