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;
|
|
|
|
|
|
2023-07-29 15:14:52 +03:00
|
|
|
namespace Kruzya.TelegramBot.RichSiteSummary.Service;
|
|
|
|
|
|
|
|
|
|
public class Unsubscriber : AbstractTimedHostedService
|
2020-03-02 00:00:52 +04:00
|
|
|
{
|
2023-07-29 15:14:52 +03:00
|
|
|
protected readonly ConcurrentQueue<UserUnsubscribe> Queue;
|
|
|
|
|
protected readonly IServiceScopeFactory ScopeFactory;
|
|
|
|
|
|
|
|
|
|
protected override TimeSpan TimerPeriod => TimeSpan.FromSeconds(1);
|
2020-03-02 00:00:52 +04:00
|
|
|
|
2023-07-29 15:14:52 +03:00
|
|
|
public Unsubscriber(ILogger<Unsubscriber> logger, IBotInstance bot, ConcurrentQueue<UserUnsubscribe> queue, IServiceScopeFactory scopeFactory) : base(logger, bot)
|
|
|
|
|
{
|
|
|
|
|
ScopeFactory = scopeFactory;
|
|
|
|
|
Queue = queue;
|
|
|
|
|
}
|
2020-03-02 00:00:52 +04:00
|
|
|
|
2023-07-29 15:14:52 +03:00
|
|
|
protected override async Task OnRun()
|
|
|
|
|
{
|
|
|
|
|
if (Queue.IsEmpty || !Queue.TryDequeue(out var user))
|
2020-03-02 00:00:52 +04:00
|
|
|
{
|
2023-07-29 15:14:52 +03:00
|
|
|
return;
|
2020-03-02 00:00:52 +04:00
|
|
|
}
|
|
|
|
|
|
2023-07-29 15:14:52 +03:00
|
|
|
await UnsubscribeUser(user.ChatId);
|
|
|
|
|
}
|
2020-03-02 00:00:52 +04:00
|
|
|
|
2023-07-29 15:14:52 +03:00
|
|
|
private async Task UnsubscribeUser(ChatId chatId)
|
|
|
|
|
{
|
|
|
|
|
using var scope = ScopeFactory.CreateScope();
|
|
|
|
|
var dbContext = scope.ServiceProvider.GetRequiredService<RichSiteSummaryContext>();
|
2020-03-02 00:00:52 +04:00
|
|
|
|
2023-07-29 15:14:52 +03:00
|
|
|
var subscriptions = dbContext.Subscriptions;
|
|
|
|
|
subscriptions.RemoveRange(
|
|
|
|
|
subscriptions.Where(s => s.SubscriberId == chatId.Identifier)
|
|
|
|
|
);
|
|
|
|
|
await dbContext.SaveChangesAsync();
|
2020-03-02 00:00:52 +04:00
|
|
|
}
|
|
|
|
|
}
|