File size: 8,768 Bytes
1459920 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | using Microsoft.Extensions.Logging;
using SilkroadBot.Core.Events;
using SilkroadBot.Core.Networking;
using SilkroadBot.Core.Cryptography;
using SilkroadBot.Domain.Enums;
using SilkroadBot.Domain.Interfaces;
using SilkroadBot.Domain.Models;
namespace SilkroadBot.Core.State;
/// <summary>
/// Central bot state machine. Manages the lifecycle of a single bot instance
/// including connection, authentication, and game session management.
/// </summary>
public class BotContext : IDisposable
{
private readonly IProtocolAdapter _adapter;
private readonly IEventDispatcher _eventDispatcher;
private readonly ILogger<BotContext> _logger;
private readonly SilkroadSecurity _security;
private NetworkClient? _networkClient;
private CancellationTokenSource? _cts;
public string ProfileId { get; }
public GameState GameState { get; } = new();
public ConnectionState ConnectionState { get; private set; } = ConnectionState.Disconnected;
public ExecutionMode ExecutionMode { get; set; } = ExecutionMode.Clientless;
public IProtocolAdapter Adapter => _adapter;
public IEventDispatcher Events => _eventDispatcher;
public event Action<ConnectionState>? StateChanged;
public BotContext(
string profileId,
IProtocolAdapter adapter,
IEventDispatcher eventDispatcher,
ILogger<BotContext> logger)
{
ProfileId = profileId;
_adapter = adapter;
_eventDispatcher = eventDispatcher;
_logger = logger;
_security = new SilkroadSecurity();
}
/// <summary>
/// Connect to the gateway server and begin the authentication flow.
/// </summary>
public async Task ConnectAsync(string host, int port, CancellationToken ct = default)
{
if (ConnectionState != ConnectionState.Disconnected)
throw new InvalidOperationException($"Cannot connect in state {ConnectionState}");
_cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
_networkClient = new NetworkClient(_adapter,
LoggerFactory.Create(b => b.AddConsole()).CreateLogger<NetworkClient>());
_networkClient.PacketReceived += OnPacketReceivedAsync;
_networkClient.Disconnected += OnDisconnectedAsync;
SetState(ConnectionState.Connecting);
try
{
await _networkClient.ConnectAsync(host, port, _cts.Token);
SetState(ConnectionState.Handshaking);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to connect to {Host}:{Port}", host, port);
SetState(ConnectionState.Disconnected);
throw;
}
}
/// <summary>
/// Login with credentials.
/// </summary>
public async Task LoginAsync(string username, string password, CancellationToken ct = default)
{
if (_networkClient == null || !_networkClient.IsConnected)
throw new InvalidOperationException("Not connected");
SetState(ConnectionState.Authenticating);
var writer = new PacketWriter();
writer.WriteByte(0x01); // Login type
writer.WriteAscii(username);
writer.WriteAscii(password);
var opcode = _adapter.GetOpcodeMap().GetOpcode("LOGIN_REQUEST");
var packet = Packet.ToServer(opcode, writer.ToArray());
await _networkClient.SendAsync(packet, ct);
await _eventDispatcher.PublishAsync(new PacketSentEvent { Packet = packet });
}
/// <summary>
/// Send a packet through the connection.
/// </summary>
public async Task SendPacketAsync(Packet packet, CancellationToken ct = default)
{
if (_networkClient == null || !_networkClient.IsConnected)
throw new InvalidOperationException("Not connected");
await _networkClient.SendAsync(packet, ct);
await _eventDispatcher.PublishAsync(new PacketSentEvent { Packet = packet });
}
/// <summary>
/// Disconnect and cleanup.
/// </summary>
public async Task DisconnectAsync()
{
if (_networkClient != null)
{
await _networkClient.DisconnectAsync();
}
SetState(ConnectionState.Disconnected);
}
private async Task OnPacketReceivedAsync(Packet packet)
{
await _eventDispatcher.PublishAsync(new PacketReceivedEvent { Packet = packet });
// Handle handshake packets
var opcodeMap = _adapter.GetOpcodeMap();
var logicalName = opcodeMap.GetLogicalName(packet.Opcode);
switch (logicalName)
{
case "HANDSHAKE":
await HandleHandshakeAsync(packet);
break;
case "LOGIN_RESPONSE":
HandleLoginResponse(packet);
break;
case "HP_MP_UPDATE":
HandleHealthUpdate(packet);
break;
case "CHAT_RECEIVE":
await HandleChatAsync(packet);
break;
case "ENTITY_SPAWN":
await HandleEntitySpawnAsync(packet);
break;
case "ENTITY_DESPAWN":
await HandleEntityDespawnAsync(packet);
break;
}
}
private async Task HandleHandshakeAsync(Packet packet)
{
_logger.LogDebug("Processing handshake...");
var response = _security.ProcessHandshake(packet.Payload);
var opcode = _adapter.GetOpcodeMap().GetOpcode("HANDSHAKE_RESPONSE");
await _networkClient!.SendAsync(Packet.ToServer(opcode, response));
SetState(ConnectionState.Connected);
}
private void HandleLoginResponse(Packet packet)
{
var reader = new PacketReader(packet.Payload);
byte result = reader.ReadByte();
if (result == 0x01)
{
_logger.LogInformation("Login successful");
SetState(ConnectionState.InGame);
}
else
{
_logger.LogWarning("Login failed with code: 0x{Code:X2}", result);
SetState(ConnectionState.Connected);
}
}
private void HandleHealthUpdate(Packet packet)
{
if (packet.Payload.Length < 8) return;
var reader = new PacketReader(packet.Payload);
int hp = (int)reader.ReadUInt32();
int mp = (int)reader.ReadUInt32();
GameState.Update(s =>
{
s.Character.HP = hp;
s.Character.MP = mp;
});
_ = _eventDispatcher.PublishAsync(new HealthChangedEvent
{
HP = hp,
MaxHP = GameState.Character.MaxHP,
MP = mp,
MaxMP = GameState.Character.MaxMP
});
}
private async Task HandleChatAsync(Packet packet)
{
var reader = new PacketReader(packet.Payload);
var chatType = (ChatType)reader.ReadByte();
var sender = reader.ReadAscii();
var message = reader.ReadUnicode();
await _eventDispatcher.PublishAsync(new ChatMessageEvent
{
ChatType = chatType,
Sender = sender,
Message = message
});
}
private async Task HandleEntitySpawnAsync(Packet packet)
{
var reader = new PacketReader(packet.Payload);
var entity = new GameEntity
{
UniqueId = reader.ReadUInt32(),
ModelId = reader.ReadUInt32()
};
GameState.Update(s => s.NearbyEntities.Add(entity));
await _eventDispatcher.PublishAsync(new EntitySpawnEvent { Entity = entity });
}
private async Task HandleEntityDespawnAsync(Packet packet)
{
var reader = new PacketReader(packet.Payload);
uint uid = reader.ReadUInt32();
GameState.Update(s => s.NearbyEntities.RemoveAll(e => e.UniqueId == uid));
await _eventDispatcher.PublishAsync(new EntityDespawnEvent { UniqueId = uid });
}
private Task OnDisconnectedAsync(Exception? ex)
{
if (ex != null)
_logger.LogError(ex, "Disconnected with error");
else
_logger.LogInformation("Disconnected");
SetState(ConnectionState.Disconnected);
return Task.CompletedTask;
}
private void SetState(ConnectionState newState)
{
var oldState = ConnectionState;
ConnectionState = newState;
GameState.ConnectionState = newState;
StateChanged?.Invoke(newState);
_ = _eventDispatcher.PublishAsync(new ConnectionStateChangedEvent
{
OldState = oldState,
NewState = newState
});
}
public void Dispose()
{
_cts?.Cancel();
_cts?.Dispose();
_networkClient?.Dispose();
}
}
|