sharp-chat/SharpChat/ConnectionInfo.cs

89 lines
2.4 KiB
C#
Raw Normal View History

2022-08-30 15:00:58 +00:00
using Fleck;
using System;
using System.Net;
namespace SharpChat {
public class ConnectionInfo : IDisposable {
2023-02-16 21:25:41 +00:00
public const int ID_LENGTH = 20;
2022-08-30 15:00:58 +00:00
#if DEBUG
public static TimeSpan SessionTimeOut { get; } = TimeSpan.FromMinutes(1);
#else
public static TimeSpan SessionTimeOut { get; } = TimeSpan.FromMinutes(5);
#endif
2023-02-16 21:25:41 +00:00
public IWebSocketConnection Socket { get; }
2022-08-30 15:00:58 +00:00
public string Id { get; }
2022-08-30 15:00:58 +00:00
public bool IsDisposed { get; private set; }
public DateTimeOffset LastPing { get; set; } = DateTimeOffset.Now;
public UserInfo? User { get; set; }
2022-08-30 15:00:58 +00:00
2023-02-07 15:01:56 +00:00
private int CloseCode { get; set; } = 1000;
public IPAddress RemoteAddress { get; }
public ushort RemotePort { get; }
2022-08-30 15:00:58 +00:00
public bool IsAlive => !IsDisposed && !HasTimedOut;
public bool IsAuthed => IsAlive && User is not null;
public ConnectionInfo(IWebSocketConnection sock) {
2023-02-16 21:25:41 +00:00
Socket = sock;
2023-02-10 07:06:07 +00:00
Id = RNG.SecureRandomString(ID_LENGTH);
2024-05-10 19:18:55 +00:00
if(!IPAddress.TryParse(sock.ConnectionInfo.ClientIpAddress, out IPAddress? addr))
throw new Exception("Unable to parse remote address?????");
if(IPAddress.IsLoopback(addr)
&& sock.ConnectionInfo.Headers.ContainsKey("X-Real-IP")
2024-05-10 19:18:55 +00:00
&& IPAddress.TryParse(sock.ConnectionInfo.Headers["X-Real-IP"], out IPAddress? realAddr))
addr = realAddr;
RemoteAddress = addr;
RemotePort = (ushort)sock.ConnectionInfo.ClientPort;
2022-08-30 15:00:58 +00:00
}
public void Send(IServerPacket packet) {
2023-02-16 21:25:41 +00:00
if(!Socket.IsAvailable)
2022-08-30 15:00:58 +00:00
return;
2024-05-10 15:24:43 +00:00
string data = packet.Pack();
if(!string.IsNullOrWhiteSpace(data))
Socket.Send(data);
2022-08-30 15:00:58 +00:00
}
2023-02-07 15:01:56 +00:00
public void BumpPing() {
LastPing = DateTimeOffset.Now;
}
2022-08-30 15:00:58 +00:00
public bool HasTimedOut
=> DateTimeOffset.Now - LastPing > SessionTimeOut;
2023-02-07 15:01:56 +00:00
public void PrepareForRestart() {
CloseCode = 1012;
}
~ConnectionInfo() {
2023-02-07 15:01:56 +00:00
DoDispose();
}
2022-08-30 15:00:58 +00:00
2023-02-07 15:01:56 +00:00
public void Dispose() {
DoDispose();
GC.SuppressFinalize(this);
}
2022-08-30 15:00:58 +00:00
2023-02-07 15:01:56 +00:00
private void DoDispose() {
if(IsDisposed)
2022-08-30 15:00:58 +00:00
return;
IsDisposed = true;
2023-02-16 21:25:41 +00:00
Socket.Close(CloseCode);
2022-08-30 15:00:58 +00:00
}
public override string ToString() {
return Id;
}
2022-08-30 15:00:58 +00:00
}
}