Files
telegram-bot/modules/RichSiteSummary/Service/Unsubscriber.cs
T

49 lines
1.6 KiB
C#
Raw Normal View History

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