Skip to content

Instantly share code, notes, and snippets.

@Dominent
Created August 3, 2019 15:09
Show Gist options
  • Save Dominent/2cda40d9bd9b3f9a09c73745bd05f467 to your computer and use it in GitHub Desktop.
Save Dominent/2cda40d9bd9b3f9a09c73745bd05f467 to your computer and use it in GitHub Desktop.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using CloudSoft.MessageBus.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace Gidora.Web.API.Hubs
{
//TODO(PPavlov): Needs more work
public interface IClient
{
void ReceivePreviewUrl(string previewUrl);
}
public class PreviewHub : Hub
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
private readonly ILogger<PreviewHub> _logger;
public PreviewHub(IServiceProvider serviceProvider)
:base(serviceProvider)
{
_httpClientFactory = _serviceProvider.GetService<IHttpClientFactory>();
_configuration = _serviceProvider.GetService<IConfiguration>();
_logger = _serviceProvider.GetService<ILogger<PreviewHub>>();
}
public override void Connected()
{
Client.Instance.Subscribe<string>(
this.Context.Id.ToString(),
(previewUrl) => this.Server.Send(Context.Id, JsonConvert.SerializeObject(new WebSocketMessage()
{
Method = nameof(IClient.ReceivePreviewUrl),
Parameters = new[] { previewUrl }
})));
}
public override void Disconnected()
{
Client.Instance.Unsubscribe(this.Context.Id.ToString());
}
public async Task PushMailAsync(string body)
{
var subject = SubjectHelper.GenerateSubject();
var connectionId = Context.Id;
using (var httpClient = _httpClientFactory.CreateClient())
{
var content = JsonConvert.SerializeObject(new { body, subject, connectionId });
var response = await httpClient.PostAsync($"{_configuration["Services:Gidora.Email.Client"]}/api/email/send",
new StringContent(body, Encoding.UTF8, "application/json"));
if (!response.IsSuccessStatusCode)
{
_logger.LogError("Email service invalid response, {statusCode}", response.StatusCode);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment