NotificationManager.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using MediaBrowser.Controller.Entities;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Controller.Notifications;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Notifications;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace MediaBrowser.Server.Implementations.Notifications
  12. {
  13. public class NotificationManager : INotificationManager
  14. {
  15. private readonly ILogger _logger;
  16. private readonly IUserManager _userManager;
  17. private INotificationService[] _services;
  18. public NotificationManager(ILogManager logManager, IUserManager userManager)
  19. {
  20. _userManager = userManager;
  21. _logger = logManager.GetLogger(GetType().Name);
  22. }
  23. public Task SendNotification(NotificationRequest request, CancellationToken cancellationToken)
  24. {
  25. var users = request.UserIds.Select(i => _userManager.GetUserById(new Guid(i)));
  26. var tasks = _services.Select(i => SendNotification(request, i, users, cancellationToken));
  27. return Task.WhenAll(tasks);
  28. }
  29. public Task SendNotification(NotificationRequest request,
  30. INotificationService service,
  31. IEnumerable<User> users,
  32. CancellationToken cancellationToken)
  33. {
  34. users = users.Where(i => IsEnabledForUser(service, i))
  35. .ToList();
  36. var tasks = users.Select(i => SendNotification(request, service, i, cancellationToken));
  37. return Task.WhenAll(tasks);
  38. }
  39. public async Task SendNotification(NotificationRequest request,
  40. INotificationService service,
  41. User user,
  42. CancellationToken cancellationToken)
  43. {
  44. var notification = new UserNotification
  45. {
  46. Date = request.Date,
  47. Description = request.Description,
  48. Level = request.Level,
  49. Name = request.Name,
  50. Url = request.Url,
  51. User = user
  52. };
  53. _logger.Debug("Sending notification via {0} to user {1}", service.Name, user.Name);
  54. try
  55. {
  56. await service.SendNotification(notification, cancellationToken).ConfigureAwait(false);
  57. }
  58. catch (Exception ex)
  59. {
  60. _logger.ErrorException("Error sending notification to {0}", ex, service.Name);
  61. }
  62. }
  63. private bool IsEnabledForUser(INotificationService service, User user)
  64. {
  65. try
  66. {
  67. return service.IsEnabledForUser(user);
  68. }
  69. catch (Exception ex)
  70. {
  71. _logger.ErrorException("Error in IsEnabledForUser", ex);
  72. return false;
  73. }
  74. }
  75. public void AddParts(IEnumerable<INotificationService> services)
  76. {
  77. _services = services.ToArray();
  78. }
  79. }
  80. }