sharp-chat/SharpChat/ConnectionInfo.cs

64 lines
1.9 KiB
C#

using Fleck;
using SharpChat.PacketsS2C;
using System;
using System.Net;
namespace SharpChat {
public class ConnectionInfo {
public IWebSocketConnection Socket { get; }
public DateTimeOffset LastPing { get; private set; }
public long UserId { get; private set; } = 0;
public string RemoteAddress { get; }
public ushort RemotePort { get; }
public string RemoteEndPoint { get; }
public ConnectionInfo(IWebSocketConnection sock) {
Socket = sock;
BumpPing();
IPAddress remoteAddr = IPAddress.Parse(sock.ConnectionInfo.ClientIpAddress);
if(IPAddress.IsLoopback(remoteAddr)
&& sock.ConnectionInfo.Headers.ContainsKey("X-Real-IP")
&& IPAddress.TryParse(sock.ConnectionInfo.Headers["X-Real-IP"], out IPAddress? realAddr))
remoteAddr = realAddr;
RemoteAddress = remoteAddr.ToString();
RemotePort = (ushort)sock.ConnectionInfo.ClientPort;
RemoteEndPoint = string.Format(
RemoteAddress.Contains(':') ? "[{0}]:{1}" : "{0}:{1}",
RemoteAddress, RemotePort
);
}
// please call this through ConnectionsContext
public void SetUserId(long userId) {
if(UserId > 0)
throw new InvalidOperationException("This connection is already associated with a user.");
UserId = userId;
}
public void Send(SockChatS2CPacket packet) {
string data = packet.Pack();
if(!string.IsNullOrWhiteSpace(data))
Send(data);
}
public void Send(string packet) {
if(Socket.IsAvailable)
Socket.Send(packet).Wait();
}
public void BumpPing() {
LastPing = DateTimeOffset.UtcNow;
}
public void Close(int code) {
Socket.Close(code);
}
}
}