using Cleanuparr.Domain.Entities.Arr.Queue; using Cleanuparr.Domain.Enums; using Cleanuparr.Infrastructure.Events.Interfaces; using Cleanuparr.Infrastructure.Features.Arr.Interfaces; using Cleanuparr.Infrastructure.Features.Context; using Cleanuparr.Infrastructure.Features.DownloadClient; using Cleanuparr.Infrastructure.Features.MalwareBlocker; using Cleanuparr.Infrastructure.Helpers; using Cleanuparr.Persistence; using Cleanuparr.Persistence.Models.Configuration; using Cleanuparr.Persistence.Models.Configuration.Arr; using Cleanuparr.Persistence.Models.Configuration.General; using Cleanuparr.Persistence.Models.Configuration.MalwareBlocker; using MassTransit; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using LogContext = Serilog.Context.LogContext; namespace Cleanuparr.Infrastructure.Features.Jobs; public sealed class MalwareBlocker : GenericHandler { private readonly IBlocklistProvider _blocklistProvider; public MalwareBlocker( ILogger logger, DataContext dataContext, IMemoryCache cache, IBus messageBus, IArrClientFactory arrClientFactory, IArrQueueIterator arrArrQueueIterator, IDownloadServiceFactory downloadServiceFactory, IBlocklistProvider blocklistProvider, IEventPublisher eventPublisher ) : base( logger, dataContext, cache, messageBus, arrClientFactory, arrArrQueueIterator, downloadServiceFactory, eventPublisher ) { _blocklistProvider = blocklistProvider; } protected override async Task ExecuteInternalAsync(CancellationToken cancellationToken = default) { if (ContextProvider.Get>(nameof(DownloadClientConfig)).Count is 0) { _logger.LogWarning("No download clients configured"); return; } ContentBlockerConfig malwareBlockerConfig = ContextProvider.Get(); if (!malwareBlockerConfig.Sonarr.Enabled && !malwareBlockerConfig.Radarr.Enabled && !malwareBlockerConfig.Lidarr.Enabled && !malwareBlockerConfig.Readarr.Enabled && !malwareBlockerConfig.Whisparr.Enabled) { _logger.LogWarning("No blocklists are enabled"); return; } await _blocklistProvider.LoadBlocklistsAsync(); var sonarrConfig = ContextProvider.Get(nameof(InstanceType.Sonarr)); var radarrConfig = ContextProvider.Get(nameof(InstanceType.Radarr)); var lidarrConfig = ContextProvider.Get(nameof(InstanceType.Lidarr)); var readarrConfig = ContextProvider.Get(nameof(InstanceType.Readarr)); var whisparrConfig = ContextProvider.Get(nameof(InstanceType.Whisparr)); if (malwareBlockerConfig.Sonarr.Enabled) { await ProcessArrConfigAsync(sonarrConfig); } if (malwareBlockerConfig.Radarr.Enabled) { await ProcessArrConfigAsync(radarrConfig); } if (malwareBlockerConfig.Lidarr.Enabled) { await ProcessArrConfigAsync(lidarrConfig); } if (malwareBlockerConfig.Readarr.Enabled) { await ProcessArrConfigAsync(readarrConfig); } if (malwareBlockerConfig.Whisparr.Enabled) { await ProcessArrConfigAsync(whisparrConfig); } } protected override async Task ProcessInstanceAsync(ArrInstance instance) { List ignoredDownloads = ContextProvider.Get(nameof(GeneralConfig)).IgnoredDownloads; ignoredDownloads.AddRange(ContextProvider.Get().IgnoredDownloads); using var _ = LogContext.PushProperty(LogProperties.Category, instance.ArrConfig.Type.ToString()); using var _2 = LogContext.PushProperty(LogProperties.InstanceName, instance.Name); IArrClient arrClient = _arrClientFactory.GetClient(instance.ArrConfig.Type, instance.Version); // push to context ContextProvider.Set(ContextProvider.Keys.ArrInstanceUrl, instance.ExternalUrl ?? instance.Url); ContextProvider.Set(nameof(InstanceType), instance.ArrConfig.Type); ContextProvider.Set(ContextProvider.Keys.Version, instance.Version); IReadOnlyList downloadServices = await GetInitializedDownloadServicesAsync(); var config = ContextProvider.Get(); await _arrArrQueueIterator.Iterate(arrClient, instance, async items => { var groups = items .GroupBy(x => x.DownloadId) .ToList(); foreach (var group in groups) { QueueRecord record = group.First(); if (!arrClient.IsRecordValid(record)) { continue; } if (ignoredDownloads.Contains(record.DownloadId, StringComparer.InvariantCultureIgnoreCase)) { _logger.LogInformation("skip | {title} | ignored", record.Title); continue; } _logger.LogTrace("processing | {title} | {id}", record.Title, record.DownloadId); bool hasContentId = arrClient.HasContentId(record); if (!hasContentId) { if (!config.ProcessNoContentId) { _logger.LogInformation("skip | item is missing the content id | {title}", record.Title); continue; } _logger.LogDebug("item is missing the content id | {title}", record.Title); } string downloadRemovalKey = CacheKeys.DownloadMarkedForRemoval(record.DownloadId, instance.Url); if (_cache.TryGetValue(downloadRemovalKey, out bool _)) { _logger.LogDebug("skip | already marked for removal | {title}", record.Title); continue; } // push record to context ContextProvider.Set(nameof(QueueRecord), record); BlockFilesResult result = new(); bool isTorrent = record.Protocol.Contains("torrent", StringComparison.InvariantCultureIgnoreCase); if (isTorrent) { var torrentClients = downloadServices .Where(x => x.ClientConfig.Type is DownloadClientType.Torrent) .ToList(); _logger.LogDebug("searching unwanted files for {title}", record.Title); if (torrentClients.Count > 0) { // Check each download client for the download item foreach (var downloadService in torrentClients) { try { // stalled download check result = await downloadService .BlockUnwantedFilesAsync(record.DownloadId, ignoredDownloads); if (result.Found) { break; } } catch (Exception ex) { _logger.LogError(ex, "Error checking download {dName} with download client {cName}", record.Title, downloadService.ClientConfig.Name); } } if (!result.Found) { _logger.LogWarning("Download not found in any torrent client | {title}", record.Title); } } else { _logger.LogDebug("No torrent clients enabled"); } } if (!result.ShouldRemove) { continue; } bool removeFromClient = true; if (result.IsPrivate && !config.DeletePrivate) { removeFromClient = false; } await PublishQueueItemRemoveRequest( downloadRemovalKey, instance.ArrConfig.Type, instance, record, group.Count() > 1, removeFromClient, result.DeleteReason, skipSearch: !hasContentId ); } }); } }