using Quasar.Common.Messages; using Quasar.Common.Networking; using Quasar.Server.Networking; namespace Quasar.Server.Messages { /// /// Handles messages for the interaction with the remote shell. /// public class RemoteShellHandler : MessageProcessorBase { /// /// The client which is associated with this remote shell handler. /// private readonly Client _client; /// /// Represents the method that will command errors. /// /// The message processor which raised the event. /// The error message. public delegate void CommandErrorEventHandler(object sender, string errorMessage); /// /// Raised when a command writes to stderr. /// /// /// Handlers registered with this event will be invoked on the /// chosen when the instance was constructed. /// public event CommandErrorEventHandler CommandError; /// /// Reports a command error. /// /// The error message. private void OnCommandError(string errorMessage) { SynchronizationContext.Post(val => { var handler = CommandError; handler?.Invoke(this, (string)val); }, errorMessage); } /// /// Initializes a new instance of the class using the given client. /// /// The associated client. public RemoteShellHandler(Client client) : base(true) { _client = client; } /// public override bool CanExecute(IMessage message) => message is DoShellExecuteResponse; /// public override bool CanExecuteFrom(ISender sender) => _client.Equals(sender); /// public override void Execute(ISender sender, IMessage message) { switch (message) { case DoShellExecuteResponse resp: Execute(sender, resp); break; } } /// /// Sends a command to execute in the remote shell of the client. /// /// The command to execute. public void SendCommand(string command) { _client.Send(new DoShellExecute {Command = command}); } private void Execute(ISender client, DoShellExecuteResponse message) { if (message.IsError) OnCommandError(message.Output); else OnReport(message.Output); } } }