Files
2026-06-05 21:39:38 +02:00

72 lines
2.4 KiB
C#

using CalendarReminder.Api.Data;
using Microsoft.EntityFrameworkCore;
namespace CalendarReminder.Api.Services;
public class ReminderNotificationService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<ReminderNotificationService> _logger;
public ReminderNotificationService(IServiceScopeFactory scopeFactory,
ILogger<ReminderNotificationService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Notification service spustený");
while (!stoppingToken.IsCancellationRequested)
{
await CheckRemindersAsync();
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
}
private async Task CheckRemindersAsync()
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var emailService = scope.ServiceProvider.GetRequiredService<EmailService>();
var now = DateTime.UtcNow;
var windowEnd = now.AddMinutes(15);
// Nájdi remindery, ktoré sú do 15 minút a notifikácia ešte nebola odoslaná
var upcoming = await db.Reminders
.Include(r => r.User)
.Where(r => !r.IsCompleted
&& !r.NotificationSent
&& r.ReminderDate >= now
&& r.ReminderDate <= windowEnd)
.ToListAsync();
foreach (var reminder in upcoming)
{
var minutesLeft = (int)(reminder.ReminderDate - now).TotalMinutes;
var body = $"""
<h2>⏰ Pripomienka: {reminder.Title}</h2>
<p><strong>Čas:</strong> {reminder.ReminderDate:dd.MM.yyyy HH:mm}</p>
<p><strong>O:</strong> {minutesLeft} minút</p>
{(reminder.Description != null ? $"<p><strong>Popis:</strong> {reminder.Description}</p>" : "")}
<hr>
<small>CalendarReminder</small>
""";
await emailService.SendAsync(
reminder.User!.Email,
reminder.User.Username,
$"⏰ Pripomienka: {reminder.Title}",
body);
reminder.NotificationSent = true;
}
if (upcoming.Count > 0)
await db.SaveChangesAsync();
}
}