[rss] Unsubscriber service cleanup.

This commit is contained in:
West14
2022-04-21 14:53:25 +03:00
parent 04a660181d
commit 41a8eaefc2
+11 -14
View File
@@ -15,26 +15,20 @@ namespace Kruzya.TelegramBot.RichSiteSummary.Service
{ {
public class Unsubscriber : AbstractTimedHostedService public class Unsubscriber : AbstractTimedHostedService
{ {
protected readonly ConcurrentQueue<UserUnsubscribe> _queue; protected readonly ConcurrentQueue<UserUnsubscribe> Queue;
protected readonly IServiceScopeFactory _scopeFactory; protected readonly IServiceScopeFactory ScopeFactory;
protected override TimeSpan TimerPeriod => TimeSpan.FromSeconds(1); protected override TimeSpan TimerPeriod => TimeSpan.FromSeconds(1);
public Unsubscriber(ILogger<Unsubscriber> logger, IBotInstance bot, ConcurrentQueue<UserUnsubscribe> queue, IServiceScopeFactory scopeFactory) : base(logger, bot) public Unsubscriber(ILogger<Unsubscriber> logger, IBotInstance bot, ConcurrentQueue<UserUnsubscribe> queue, IServiceScopeFactory scopeFactory) : base(logger, bot)
{ {
_scopeFactory = scopeFactory; ScopeFactory = scopeFactory;
_queue = queue; Queue = queue;
} }
protected override async Task OnRun() protected override async Task OnRun()
{ {
if (_queue.Count == 0) if (Queue.IsEmpty || !Queue.TryDequeue(out var user))
{
return;
}
UserUnsubscribe user;
if (!_queue.TryDequeue(out user))
{ {
return; return;
} }
@@ -44,10 +38,13 @@ namespace Kruzya.TelegramBot.RichSiteSummary.Service
private async Task UnsubscribeUser(ChatId chatId) private async Task UnsubscribeUser(ChatId chatId)
{ {
using var scope = _scopeFactory.CreateScope(); using var scope = ScopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<RichSiteSummaryContext>(); var dbContext = scope.ServiceProvider.GetRequiredService<RichSiteSummaryContext>();
dbContext.Subscriptions.RemoveRange(dbContext.Subscriptions.Where(s => s.SubscriberId == chatId.Identifier)); var subscriptions = dbContext.Subscriptions;
subscriptions.RemoveRange(
subscriptions.Where(s => s.SubscriberId == chatId.Identifier)
);
await dbContext.SaveChangesAsync(); await dbContext.SaveChangesAsync();
} }
} }