Skip to content

Commit

Permalink
Merge pull request #559 from henriqueholtz/develop
Browse files Browse the repository at this point in the history
Turning endpoints of `ContactUsController` and `MeetupController` as async
  • Loading branch information
raffacabofrio authored Jun 11, 2024
2 parents 50b6a4d + 1d871c3 commit 79d2b21
Show file tree
Hide file tree
Showing 18 changed files with 152 additions and 55 deletions.
5 changes: 3 additions & 2 deletions ShareBook/ShareBook.Api/Controllers/ContactUsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using ShareBook.Domain;
using ShareBook.Domain.Common;
using ShareBook.Service;
using System.Threading.Tasks;

namespace ShareBook.Api.Controllers
{
Expand All @@ -23,11 +24,11 @@ public ContactUsController(IContactUsService contactUsService,
}

[HttpPost("SendMessage")]
public Result<ContactUs> SendMessage([FromBody]ContactUsVM contactUsVM)
public async Task<Result<ContactUs>> SendMessageAsync([FromBody]ContactUsVM contactUsVM)
{
var contactUS = _mapper.Map<ContactUs>(contactUsVM);

return _contactUsService.SendContactUs(contactUS, contactUsVM?.RecaptchaReactive);
return await _contactUsService.SendContactUsAsync(contactUS, contactUsVM?.RecaptchaReactive);
}
}
}
6 changes: 3 additions & 3 deletions ShareBook/ShareBook.Api/Controllers/MeetupController.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using ShareBook.Domain;
using ShareBook.Domain.Common;
using ShareBook.Service;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ShareBook.Api.Controllers
{
Expand Down Expand Up @@ -37,9 +37,9 @@ public IActionResult Get(string id)
}

[HttpGet("Search")]
public IList<Meetup> Search([FromQuery]string criteria)
public async Task<IList<Meetup>> SearchAsync([FromQuery]string criteria)
{
return _meetupService.Search(criteria);
return await _meetupService.SearchAsync(criteria);
}
}
}
4 changes: 2 additions & 2 deletions ShareBook/ShareBook.Api/Controllers/OperationsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ public async Task<IActionResult> ExecutorAsync()
[HttpPost("EmailTest")]
[Authorize("Bearer")]
[AuthorizationFilter(Permissions.Permission.ApproveBook)] // adm
public IActionResult EmailTest([FromBody] EmailTestVM emailVM)
public async Task<IActionResult> EmailTestAsync([FromBody] EmailTestVM emailVM)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);

_emailService.Test(emailVM.Email, emailVM.Name).Wait();
await _emailService.Test(emailVM.Email, emailVM.Name);
return Ok();
}

Expand Down
8 changes: 5 additions & 3 deletions ShareBook/ShareBook.Service/Book/BookService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ public override Book Find(object keyValue)

public override Result<Book> Insert(Book entity)
{
// TODO: Migrate to Async and remove ".GetAwaiter().GetResult()" and ".Wait()"
entity.UserId = new Guid(Thread.CurrentPrincipal?.Identity?.Name);

EBookValidate(entity);
Expand All @@ -197,11 +198,11 @@ public override Result<Book> Insert(Book entity)
entity.ImageSlug = ImageHelper.FormatImageName(entity.ImageName, entity.Slug);

if (entity.IsEbookPdfValid())
entity.EBookPdfFile = _uploadService.UploadPdf(entity.EBookPdfBytes, entity.EBookPdfFile, "EBooks");
entity.EBookPdfFile = _uploadService.UploadPdfAsync(entity.EBookPdfBytes, entity.EBookPdfFile, "EBooks").GetAwaiter().GetResult();

result.Value = _repository.Insert(entity);

result.Value.ImageUrl = _uploadService.UploadImage(entity.ImageBytes, entity.ImageSlug, "Books");
result.Value.ImageUrl = _uploadService.UploadImageAsync(entity.ImageBytes, entity.ImageSlug, "Books").GetAwaiter().GetResult();

result.Value.ImageBytes = null;

Expand All @@ -212,6 +213,7 @@ public override Result<Book> Insert(Book entity)

public override Result<Book> Update(Book entity)
{
// TODO: Migrate to Async and remove ".GetAwaiter().GetResult()" and ".Wait()"
Result<Book> result = Validate(entity, x =>
x.Title,
x => x.Author,
Expand All @@ -234,7 +236,7 @@ public override Result<Book> Update(Book entity)
if (!string.IsNullOrEmpty(entity.ImageName) && entity.ImageBytes.Length > 0)
{
entity.ImageSlug = ImageHelper.FormatImageName(entity.ImageName, savedBook.Slug);
_uploadService.UploadImage(entity.ImageBytes, savedBook.ImageSlug, "Books");
_uploadService.UploadImageAsync(entity.ImageBytes, savedBook.ImageSlug, "Books").GetAwaiter().GetResult();
}

//preparar o book para atualização
Expand Down
15 changes: 7 additions & 8 deletions ShareBook/ShareBook.Service/ContactUs/ContactUsEmailService.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
using ShareBook.Domain;
using ShareBook.Service.AwsSqs;
using System.Threading.Tasks;

namespace ShareBook.Service
{
public class ContactUsEmailService : IContactUsEmailService
{
private const string ContactUsTemplate = "ContactUsTemplate";
private const string ContactUsTitle = "Fale Conosco - Sharebook";
public const string ContactUsTitle = "Fale Conosco - Sharebook";
private const string ContactUsNotificationTemplate = "ContactUsNotificationTemplate";
private const string ContactUsNotificationTitle = "Fale Conosco - Sharebook";
public const string ContactUsNotificationTitle = "Fale Conosco - Sharebook";

private readonly IEmailService _emailService;

Expand All @@ -21,18 +20,18 @@ public ContactUsEmailService(IEmailService emailService, IEmailTemplate emailTem
_emailService = emailService;
_emailTemplate = emailTemplate;
}
public async Task SendEmailContactUs(ContactUs contactUs)
public async Task SendEmailContactUsAsync(ContactUs contactUs)
{
await SendEmailContactUsToAdministrator(contactUs);
await SendEmailContactUsToAdministratorAsync(contactUs);

await SendEmailNotificationToUser(contactUs);
await SendEmailNotificationToUserAsync(contactUs);
}
private async Task SendEmailContactUsToAdministrator(ContactUs contactUs)
private async Task SendEmailContactUsToAdministratorAsync(ContactUs contactUs)
{
var html = await _emailTemplate.GenerateHtmlFromTemplateAsync(ContactUsTemplate, contactUs);
await _emailService.SendToAdmins(html, ContactUsTitle);
}
private async Task SendEmailNotificationToUser(ContactUs contactUs)
private async Task SendEmailNotificationToUserAsync(ContactUs contactUs)
{
var html = await _emailTemplate.GenerateHtmlFromTemplateAsync(ContactUsNotificationTemplate, contactUs);
await _emailService.Send(contactUs.Email, contactUs.Name, html, ContactUsNotificationTitle, copyAdmins: false, highPriority: true);
Expand Down
13 changes: 7 additions & 6 deletions ShareBook/ShareBook.Service/ContactUs/ContactUsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,25 @@
using ShareBook.Domain;
using ShareBook.Domain.Common;
using ShareBook.Service.Recaptcha;
using System.Threading.Tasks;

namespace ShareBook.Service
{
public class ContactUsService : IContactUsService
{
IContactUsEmailService _contactUsEmailService;
IValidator<ContactUs> _validator;
IRecaptchaService _recaptchaService;
readonly IContactUsEmailService _contactUsEmailService;
readonly IValidator<ContactUs> _validator;
readonly IRecaptchaService _recaptchaService;
public ContactUsService(IContactUsEmailService contactUsEmailService, IValidator<ContactUs> validator, IRecaptchaService recaptchaService)
{
_contactUsEmailService = contactUsEmailService;
_validator = validator;
_recaptchaService = recaptchaService;
}
public Result<ContactUs> SendContactUs(ContactUs entity, string recaptchaReactive)
public async Task<Result<ContactUs>> SendContactUsAsync(ContactUs contactUs, string recaptchaReactive)
{

var result = new Result<ContactUs>(_validator.Validate(entity));
var result = new Result<ContactUs>(_validator.Validate(contactUs));

Result resultRecaptcha = _recaptchaService.SimpleValidationRecaptcha(recaptchaReactive);
if (!resultRecaptcha.Success)
Expand All @@ -28,7 +29,7 @@ public Result<ContactUs> SendContactUs(ContactUs entity, string recaptchaReactiv
if (!result.Success)
return result;

_contactUsEmailService.SendEmailContactUs(entity).Wait();
await _contactUsEmailService.SendEmailContactUsAsync(contactUs);

return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ namespace ShareBook.Service
{
public interface IContactUsEmailService
{
Task SendEmailContactUs(ContactUs contactUs);
Task SendEmailContactUsAsync(ContactUs contactUs);
}
}
3 changes: 2 additions & 1 deletion ShareBook/ShareBook.Service/ContactUs/IContactUsService.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using ShareBook.Domain;
using ShareBook.Domain.Common;
using System.Threading.Tasks;

namespace ShareBook.Service
{
public interface IContactUsService
{
Result<ContactUs> SendContactUs(ContactUs contactUs, string recaptchaReactive);
Task<Result<ContactUs>> SendContactUsAsync(ContactUs contactUs, string recaptchaReactive);
}
}
2 changes: 1 addition & 1 deletion ShareBook/ShareBook.Service/Meetup/IMeetupService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ namespace ShareBook.Service
public interface IMeetupService : IBaseService<Meetup>
{
public Task<IList<string>> FetchMeetupsAsync();
IList<Meetup> Search(string criteria);
Task<IList<Meetup>> SearchAsync(string criteria);
}
}
11 changes: 6 additions & 5 deletions ShareBook/ShareBook.Service/Meetup/MeetupService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using FluentValidation;
using Flurl;
using Flurl.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using ShareBook.Domain;
using ShareBook.Domain.Exceptions;
Expand Down Expand Up @@ -210,15 +211,15 @@ private async Task<string> UploadCoverAsync(string coverUrl, string eventName)

var imageName = ImageHelper.FormatImageName(fileName, imageSlug);

return _uploadService.UploadImage(resizedImageBytes, imageName, "Meetup");
return await _uploadService.UploadImageAsync(resizedImageBytes, imageName, "Meetup");
}

public IList<Meetup> Search(string criteria)
public async Task<IList<Meetup>> SearchAsync(string criteria)
{
return _repository.Get()
.Where(m => m.Active && ( m.Title.ToUpper().Contains(criteria.ToUpper()) || m.Description.ToUpper().Contains(criteria.ToUpper())))
return await _repository.Get()
.Where(m => m.Active && ( m.Title.Contains(criteria, StringComparison.InvariantCultureIgnoreCase) || m.Description.Contains(criteria, StringComparison.InvariantCultureIgnoreCase)))
.OrderByDescending(m => m.CreationDate)
.ToList();
.ToListAsync();
}
}
}
4 changes: 2 additions & 2 deletions ShareBook/ShareBook.Service/Recaptcha/RecaptchaService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ namespace ShareBook.Service.Recaptcha
public class RecaptchaService : IRecaptchaService
{
// TODO: Fazer a validação real do "RecaptchaReactive" (https://developers.google.com/recaptcha/docs/verify)
public Result SimpleValidationRecaptcha(string recaptchaReactive)
public Result SimpleValidationRecaptcha(string recaptcha)
{
Result result = new Result();
if (string.IsNullOrWhiteSpace(recaptchaReactive) || recaptchaReactive.Length <= 100)
if (string.IsNullOrWhiteSpace(recaptcha) || recaptcha.Length <= 100)
result.Messages.Add("RecaptchaReactive está inválido!");

return result;
Expand Down
8 changes: 5 additions & 3 deletions ShareBook/ShareBook.Service/Upload/IUploadService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
namespace ShareBook.Service.Upload
using System.Threading.Tasks;

namespace ShareBook.Service.Upload
{
public interface IUploadService
{
string UploadImage(byte[] imageBytes, string imageName, string lastDirectory);
string UploadPdf(byte[] imageBytes, string imageName, string lastDirectory);
Task<string> UploadImageAsync(byte[] imageBytes, string imageName, string lastDirectory);
Task<string> UploadPdfAsync(byte[] imageBytes, string imageName, string lastDirectory);
string GetImageUrl(string imageName, string lastDirectory);
}
}
14 changes: 7 additions & 7 deletions ShareBook/ShareBook.Service/Upload/UploadService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using ShareBook.Service.Server;
using System;
using System.IO;

using System.Threading.Tasks;

namespace ShareBook.Service.Upload
{
Expand All @@ -25,7 +25,7 @@ public string GetImageUrl(string imageName, string lastDirectory)
}


public string UploadImage(byte[] imageBytes, string imageName, string lastDirectory)
public async Task<string> UploadImageAsync(byte[] imageBytes, string imageName, string lastDirectory)
{
var dinamicDirectory = Path.Combine(_imageSettings.ImagePath, lastDirectory);

Expand All @@ -39,29 +39,29 @@ public string UploadImage(byte[] imageBytes, string imageName, string lastDirect
imageName = Path.GetFileNameWithoutExtension(testPath) + DateTimeOffset.Now.ToUnixTimeSeconds() + extension;
}

UploadFile(imageBytes, imageName, dinamicDirectory);
await UploadFileAsync(imageBytes, imageName, dinamicDirectory);

return GetImageUrl(imageName, lastDirectory);
}

public string UploadPdf(byte[] imageBytes, string imageName, string lastDirectory)
public async Task<string> UploadPdfAsync(byte[] imageBytes, string imageName, string lastDirectory)
{
var dinamicDirectory = Path.Combine(_imageSettings.EBookPdfPath, lastDirectory);

UploadFile(imageBytes, imageName, dinamicDirectory);
await UploadFileAsync(imageBytes, imageName, dinamicDirectory);

return Path.Combine(lastDirectory, dinamicDirectory.Replace("wwwroot", ""), imageName);

}

private static void UploadFile(byte[] imageBytes, string imageName, string dinamicDirectory)
private static async Task UploadFileAsync(byte[] imageBytes, string imageName, string dinamicDirectory)
{
var directoryBase = AppDomain.CurrentDomain.BaseDirectory + dinamicDirectory;
if (!Directory.Exists(directoryBase))
Directory.CreateDirectory(directoryBase);

var imageCompletePath = Path.Combine(directoryBase, imageName);
File.WriteAllBytes(imageCompletePath, imageBytes);
await File.WriteAllBytesAsync(imageCompletePath, imageBytes);
}
}
}
49 changes: 49 additions & 0 deletions ShareBook/ShareBook.Test.Unit/Jobs/MeetupSearchTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using Moq;
using Sharebook.Jobs;
using ShareBook.Service;
using System.Threading.Tasks;
using Xunit;
using ShareBook.Repository;
using Microsoft.Extensions.Configuration;
using ShareBook.Domain.Enums;
using System.Collections.Generic;
using ShareBook.Domain;

namespace ShareBook.Test.Unit.Jobs
{
public class MeetupSearchTests
{
private readonly Mock<IJobHistoryRepository> _mockJobHistoryRepository = new();
private readonly Mock<IMeetupService> _mockMeetupService = new();
private readonly Mock<IConfiguration> _mockConfiguration = new();

[Fact]
public async Task MeetupSettingsDisabled_ShouldReturn_MeetupDisabled()
{
_mockConfiguration.SetupGet(s => s[It.IsAny<string>()]).Returns("false");
MeetupSearch job = new MeetupSearch(_mockJobHistoryRepository.Object, _mockMeetupService.Object, _mockConfiguration.Object);

JobResult result = await job.ExecuteAsync();
Assert.Equal(JobResult.MeetupDisabled, result);
_mockMeetupService.VerifyNoOtherCalls();
_mockJobHistoryRepository.VerifyNoOtherCalls();
}

[Fact]
public async Task MeetupSettingsEnabled_ShouldReturn_MeetupsCorrectly()
{
List<string> mockedMeetups = new List<string> { "Meetup Mock 1", "Meetup Mock 2" };
_mockConfiguration.SetupGet(s => s[It.IsAny<string>()]).Returns("true");
_mockMeetupService.Setup(s => s.FetchMeetupsAsync()).ReturnsAsync(() => mockedMeetups);
MeetupSearch job = new MeetupSearch(_mockJobHistoryRepository.Object, _mockMeetupService.Object, _mockConfiguration.Object);

JobHistory result = await job.WorkAsync();
Assert.Equal("MeetupSearch", result.JobName);
Assert.True(result.IsSuccess);
Assert.Equal(string.Join("\n", mockedMeetups), result.Details);
_mockMeetupService.Verify(c => c.FetchMeetupsAsync(), Times.Once);
_mockMeetupService.VerifyNoOtherCalls();
_mockJobHistoryRepository.VerifyNoOtherCalls();
}
}
}
2 changes: 1 addition & 1 deletion ShareBook/ShareBook.Test.Unit/Services/BookServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public BookServiceTests()
{
return BookMock.GetLordTheRings();
});
uploadServiceMock.Setup(service => service.UploadImage(null, null, null));
uploadServiceMock.Setup(service => service.UploadImageAsync(null, null, null));
bookServiceMock.Setup(service => service.Insert(It.IsAny<Book>())).Verifiable();
}

Expand Down
Loading

0 comments on commit 79d2b21

Please sign in to comment.