Files
2020-03-02 00:05:07 +04:00

52 lines
1.6 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using BotFramework;
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
{
protected readonly ConcurrentQueue<UserUnsubscribe> _queue;
protected readonly IServiceScopeFactory _scopeFactory;
protected override TimeSpan TimerPeriod => TimeSpan.FromSeconds(1);
public Unsubscriber(ILogger<Unsubscriber> logger, ITelegramBot bot, ConcurrentQueue<UserUnsubscribe> queue, IServiceScopeFactory scopeFactory) : base(logger, bot)
{
_scopeFactory = scopeFactory;
_queue = queue;
}
protected override async Task OnRun()
{
if (_queue.Count == 0)
{
return;
}
UserUnsubscribe user;
if (!_queue.TryDequeue(out user))
{
return;
}
await UnsubscribeUser(user.ChatId);
}
private async Task UnsubscribeUser(ChatId chatId)
{
using var scope = _scopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<RichSiteSummaryContext>();
dbContext.Subscriptions.RemoveRange(dbContext.Subscriptions.Where(s => s.SubscriberId == chatId.Identifier));
await dbContext.SaveChangesAsync();
}
}
}