using System.Threading; using System.Threading.Tasks; using EasyNetQ; using MalwareMultiScan.Backends.Messages; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MalwareMultiScan.Api.Services { public class ReceiverHostedService : IHostedService { private readonly IBus _bus; private readonly IConfiguration _configuration; private readonly ScanResultService _scanResultService; private readonly ILogger _logger; public ReceiverHostedService(IBus bus, IConfiguration configuration, ScanResultService scanResultService, ILogger logger) { _bus = bus; _configuration = configuration; _scanResultService = scanResultService; _logger = logger; } public Task StartAsync(CancellationToken cancellationToken) { _bus.Receive(_configuration.GetValue("ResultsSubscriptionId"), async message => { _logger.LogInformation( $"Received a result from {message.Backend} for {message.Id} " + $"with threats {string.Join(",", message.Threats)}"); await _scanResultService.UpdateScanResultForBackend( message.Id, message.Backend, true, true, message.Threats); }); _logger.LogInformation( "Started hosted service for receiving scan results"); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _bus.Dispose(); _logger.LogInformation( "Stopped hosted service for receiving scan results"); return Task.CompletedTask; } } }