manager-service/ManagerService/Services/NotificationService.cs
2026-03-17 09:10:56 +01:00

68 lines
2.2 KiB
C#

using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using Hangfire;
using Manager.Services;
using ManagerService.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace ManagerService.Services
{
public class NotificationService
{
private readonly ILogger<NotificationService> _logger;
private readonly IServiceScopeFactory _scopeFactory;
public NotificationService(ILogger<NotificationService> logger, IServiceScopeFactory scopeFactory)
{
_logger = logger;
_scopeFactory = scopeFactory;
}
public async Task SendToTopicAsync(string notificationId)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MyInfoMateDbContext>();
IHexIdGeneratorService idService = new HexIdGeneratorService();
var notification = await db.PushNotifications.FirstOrDefaultAsync(n => n.Id == notificationId);
if (notification == null)
{
_logger.LogWarning("Notification {Id} not found", notificationId);
return;
}
try
{
var message = new Message
{
Topic = notification.Topic,
Notification = new Notification
{
Title = notification.Title,
Body = notification.Body
}
};
await FirebaseMessaging.DefaultInstance.SendAsync(message);
notification.Status = PushNotificationStatus.Sent;
notification.SentAt = DateTime.UtcNow;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send notification {Id}", notificationId);
notification.Status = PushNotificationStatus.Failed;
}
await db.SaveChangesAsync();
}
}
}