using System.Globalization; using System.Xml; using System.Xml.Linq; using SmsSluzba.Api.Contracts; namespace SmsSluzba.Api.Gateway; internal sealed record ParsedEvents(IReadOnlyList Events, IReadOnlyList SkippedTypes); /// Builds and reads the XML documents of the SMS Gate API XML 3.0. internal static class GatewayXml { // dr_request values defined by the gateway. private const string DeliveryReportRequested = "20"; private const string DeliveryReportNotRequested = "0"; private const string SourceApi = "api"; private const string SourcePortal = "portal"; private static readonly XmlReaderSettings ReaderSettings = new() { DtdProcessing = DtdProcessing.Prohibit }; public static string BuildOutgoingMessage(string recipient, string text, bool? deliveryReport, DateTimeOffset? sendAt) { var root = new XElement("outgoing_message"); if (deliveryReport is { } requested) { root.Add(new XElement("dr_request", requested ? DeliveryReportRequested : DeliveryReportNotRequested)); } root.Add(new XElement("text", text), new XElement("recipient", recipient)); if (sendAt is { } at) { root.Add(new XElement("send_at", GatewayTime.ToGateway(at))); } var declaration = new XDeclaration("1.0", "UTF-8", null); return declaration + Environment.NewLine + root.ToString(SaveOptions.DisableFormatting); } /// Null when the body is not XML (for example an error page of a proxy); the caller then decides by HTTP status. public static XDocument? TryParse(string body) { try { using var stringReader = new StringReader(body); using var xmlReader = XmlReader.Create(stringReader, ReaderSettings); return XDocument.Load(xmlReader); } catch (XmlException) { return null; } } public static SendMessageResponse ParseSendResult(XDocument document) { var root = document.Root; var message = root?.Element("message"); if (root is null || message is null) { throw Invalid("send result without "); } return new SendMessageResponse( Id: RequiredText(message, "id"), Recipient: OptionalText(message, "recipient"), SendAt: GatewayTime.FromGateway(OptionalText(message, "send_at")), Parts: ParseInt(OptionalText(message, "parts")), Price: ParseDecimal(OptionalText(message, "price")), Credit: ParseDecimal(OptionalText(root, "credit"))); } public static ParsedEvents ParseEvents(XDocument document) { var events = new List(); var skipped = new List(); foreach (var message in document.Root?.Elements("message") ?? Enumerable.Empty()) { var type = OptionalText(message, "type") ?? string.Empty; SmsEvent? parsed = type switch { "incoming_message" => new IncomingSmsEvent( RequiredText(message, "id"), OptionalText(message, "sender"), OptionalText(message, "recipient"), OptionalText(message, "text"), GatewayTime.FromGateway(OptionalText(message, "sent_at"))), "answer_message" => new AnswerSmsEvent( RequiredText(message, "id"), OptionalText(message, "sender"), OptionalText(message, "recipient"), OptionalText(message, "text"), GatewayTime.FromGateway(OptionalText(message, "sent_at")), OptionalText(message, "in_reply_to")), "delivery_report" => ParseDeliveryReport(message), "gate_outgoing_message" => ParseOutgoing(message, SourcePortal), "api_outgoing_message" => ParseOutgoing(message, SourceApi), _ => null, }; if (parsed is null) { skipped.Add(type); } else { events.Add(parsed); } } return new ParsedEvents(events, skipped); } public static CreditResponse ParseCredit(XDocument document) { var root = document.Root ?? throw Invalid("empty credit document"); return new CreditResponse( RequiredDecimal(root, "credit"), RequiredDecimal(root, "price_cz_sms"), RequiredDecimal(root, "price_sk_sms"), RequiredDecimal(root, "price_other_sms")); } private static DeliveryReportSmsEvent ParseDeliveryReport(XElement message) { // The id of a delivery report is the id of the outgoing message it belongs to. var id = RequiredText(message, "id"); return new DeliveryReportSmsEvent( id, id, ParseInt(OptionalText(message, "status")), OptionalText(message, "description"), GatewayTime.FromGateway(OptionalText(message, "delivery_timestamp"))); } private static OutgoingSmsEvent ParseOutgoing(XElement message, string source) => new( RequiredText(message, "id"), OptionalText(message, "recipient"), OptionalText(message, "text"), GatewayTime.FromGateway(OptionalText(message, "send_at")), source); private static string? OptionalText(XElement parent, string name) { var value = parent.Element(name)?.Value.Trim(); return string.IsNullOrEmpty(value) ? null : value; } private static string RequiredText(XElement parent, string name) => OptionalText(parent, name) ?? throw Invalid($"missing <{name}>"); private static int? ParseInt(string? value) => int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) ? result : null; private static decimal? ParseDecimal(string? value) => decimal.TryParse(value?.Replace(',', '.'), NumberStyles.Number, CultureInfo.InvariantCulture, out var result) ? result : null; private static decimal RequiredDecimal(XElement parent, string name) => ParseDecimal(OptionalText(parent, name)) ?? throw Invalid($"missing or invalid <{name}>"); private static GatewayException Invalid(string reason) => new(GatewayErrorKind.InvalidResponse, inner: new FormatException("Unexpected gateway XML: " + reason)); }