/*
* Copyright (c) 2022 Vaughn Nugent
*
* Library: VNLib
* Package: Emails.Transactional.Client
* File: ClientExtensions.cs
*
* ClientExtensions.cs is part of Emails.Transactional.Client which is part of the larger
* VNLib collection of libraries and utilities.
*
* Emails.Transactional.Client is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 2 of the License,
* or (at your option) any later version.
*
* Emails.Transactional.Client is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Emails.Transactional.Client. If not, see http://www.gnu.org/licenses/.
*/
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Emails.Transactional.Client.Exceptions;
using RestSharp;
namespace Emails.Transactional.Client
{
///
/// Contains extension methods to send emails on remote transational email servers
///
public static class ClientExtensions
{
private const Method DEFAULT_SEND_METHOD = Method.Post;
///
/// Asynchronously begins an email transaction against the mail server with the specified
/// transaction request.
///
///
/// The to submit
/// A cancelaion token to cancel the operation
/// A task that represents the async send operation
///
///
///
///
public static async Task SendEmailAsync(this RestClient client, EmailTransactionRequest transaction, CancellationToken token = default)
{
//Init the new request
RestRequest request = new(transaction.Endpoint, DEFAULT_SEND_METHOD)
{
//Json request
RequestFormat = DataFormat.Json
};
//add/serialze the transacion request
request.AddJsonBody(transaction);
//Exec the tranasction on the client
RestResponse response = await client.ExecuteAsync(request, token);
//parse the response body
return response.StatusCode switch
{
HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden => throw new InvalidAuthorizationException("The server did not accept the current authorization", response),
HttpStatusCode.BadRequest => throw new InvalidTransactionRequestException(response),
HttpStatusCode.UnprocessableEntity => throw new ValidationFailedException(response.Data!),
HttpStatusCode.OK => response.Data,
_ => throw new InvalidTransactionResponseException("Unhandled status code", response),
};
}
}
}