Files
telegram-bot/modules/RichSiteSummary/Service/Unsubscriber.cs
2022-04-21 14:53:25 +03:00

51 lines
1.6 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using BotFramework;
using BotFramework.Abstractions;
using Kruzya.TelegramBot.Core.Service;
using Kruzya.TelegramBot.RichSiteSummary.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Types;
namespace Kruzya.TelegramBot.RichSiteSummary.Service
{
public class Unsubscriber : AbstractTimedHostedService
{
protected readonly ConcurrentQueue<UserUnsubscribe> Queue;
protected readonly IServiceScopeFactory ScopeFactory;
protected override TimeSpan TimerPeriod => TimeSpan.FromSeconds(1);
public Unsubscriber(ILogger<Unsubscriber> logger, IBotInstance bot, ConcurrentQueue<UserUnsubscribe> queue, IServiceScopeFactory scopeFactory) : base(logger, bot)
{
ScopeFactory = scopeFactory;
Queue = queue;
}
protected override async Task OnRun()
{
if (Queue.IsEmpty || !Queue.TryDequeue(out var user))
{
return;
}
await UnsubscribeUser(user.ChatId);
}
private async Task UnsubscribeUser(ChatId chatId)
{
using var scope = ScopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<RichSiteSummaryContext>();
var subscriptions = dbContext.Subscriptions;
subscriptions.RemoveRange(
subscriptions.Where(s => s.SubscriberId == chatId.Identifier)
);
await dbContext.SaveChangesAsync();
}
}
}