btcpayserver/BTCPayServer/Services/Notifications/NotificationSender.cs

77 lines
2.8 KiB
C#
Raw Normal View History

2020-06-28 21:44:35 -05:00
using System;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Data;
using Microsoft.AspNetCore.Identity;
using Newtonsoft.Json;
namespace BTCPayServer.Services.Notifications
{
public class UserNotificationsUpdatedEvent
{
public string UserId { get; set; }
}
public class NotificationSender
{
2020-06-15 01:25:55 -05:00
private readonly ApplicationDbContextFactory _contextFactory;
private readonly UserManager<ApplicationUser> _userManager;
2020-06-16 23:29:25 +09:00
private readonly NotificationManager _notificationManager;
2020-06-28 17:55:27 +09:00
public NotificationSender(ApplicationDbContextFactory contextFactory, UserManager<ApplicationUser> userManager, NotificationManager notificationManager)
{
2020-06-15 01:25:55 -05:00
_contextFactory = contextFactory;
_userManager = userManager;
2020-06-16 23:29:25 +09:00
_notificationManager = notificationManager;
}
2020-06-16 23:29:25 +09:00
public async Task SendNotification(NotificationScope scope, object notification)
{
if (scope == null)
throw new ArgumentNullException(nameof(scope));
if (notification == null)
throw new ArgumentNullException(nameof(notification));
var users = await GetUsers(scope);
2020-06-15 01:25:55 -05:00
using (var db = _contextFactory.CreateContext())
{
foreach (var uid in users)
{
2020-06-15 17:18:45 +09:00
var obj = JsonConvert.SerializeObject(notification);
var data = new NotificationData
{
Id = Guid.NewGuid().ToString(),
Created = DateTimeOffset.UtcNow,
ApplicationUserId = uid,
2020-06-16 23:29:25 +09:00
NotificationType = _notificationManager.GetHandler(notification.GetType()).NotificationType,
Blob = ZipUtils.Zip(obj),
Seen = false
};
db.Notifications.Add(data);
}
await db.SaveChangesAsync();
}
foreach (string user in users)
{
_notificationManager.InvalidateNotificationCache(user);
}
}
private async Task<string[]> GetUsers(NotificationScope scope)
{
if (scope is AdminScope)
{
var admins = await _userManager.GetUsersInRoleAsync(Roles.ServerAdmin);
return admins.Select(a => a.Id).ToArray();
}
2020-06-15 17:18:45 +09:00
if (scope is StoreScope s)
{
using var ctx = _contextFactory.CreateContext();
return ctx.UserStore
.Where(u => u.StoreDataId == s.StoreId)
.Select(u => u.ApplicationUserId)
.ToArray();
}
throw new NotSupportedException("Notification scope not supported");
}
}
}