Skip to content

Instantly share code, notes, and snippets.

@AnchyDev
Created May 9, 2024 12:54
Show Gist options
  • Save AnchyDev/e4df4381b949a4da9347d760eb5d72c1 to your computer and use it in GitHub Desktop.
Save AnchyDev/e4df4381b949a4da9347d760eb5d72c1 to your computer and use it in GitHub Desktop.
using Microsoft.Extensions.Options;
using OceanicWar.Configuration;
using System.Text;
using System.Xml;
namespace OceanicWar.Services.Soap
{
public class SoapClient
{
private readonly HttpClient httpClient;
private readonly OceanicOptions? settings;
private readonly ILogger<SoapClient> logger;
public SoapClient(HttpClient httpClient,
IOptions<OceanicOptions> settings,
ILogger<SoapClient> logger)
{
this.httpClient = httpClient;
this.settings = settings.Value;
this.logger = logger;
if(this.settings is null ||
this.settings.Soap is null ||
string.IsNullOrEmpty(this.settings.Soap.Username) ||
string.IsNullOrEmpty(this.settings.Soap.Password))
{
logger.LogError("Failed to get soap credentials when creating soap client.");
return;
}
if(this.settings.Soap.Endpoint is null)
{
logger.LogError("Failed to get endpoint from soap settings.");
return;
}
string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{this.settings.Soap.Username}:{this.settings.Soap.Password}"));
this.httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + auth);
this.httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
}
public async Task<string?> SendCommandAsync(string command)
{
var tx = new StringContent(
@$"<SOAP-ENV:Envelope
xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/""
xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/1999/XMLSchema""
xmlns:ns1=""urn:AC"">
<SOAP-ENV:Body>
<ns1:executeCommand>
<command>{command}</command>
</ns1:executeCommand>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
");
try
{
var response = await this.httpClient.PostAsync(this.settings?.Soap?.Endpoint, tx);
if (!response.IsSuccessStatusCode)
{
logger.LogWarning($"Got HTTP status code {(int)response.StatusCode}:{response.StatusCode} when trying to fetch online player count.");
logger.LogWarning($"Body: {await response.Content.ReadAsStringAsync()}");
return null;
}
var xml = await response.Content.ReadAsStringAsync();
var doc = new XmlDocument();
doc.LoadXml(xml);
var rootNode = doc.DocumentElement;
var result = rootNode?.FirstChild?.FirstChild?.FirstChild?.InnerText;
return result;
}
catch (Exception ex)
{
logger.LogError($"An error occured while fetching online player count: {ex.Message}");
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment