NotificationManager.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Common.Extensions;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Notifications;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.Notifications;
  15. using Microsoft.Extensions.Logging;
  16. namespace Emby.Notifications
  17. {
  18. /// <summary>
  19. /// NotificationManager class.
  20. /// </summary>
  21. public class NotificationManager : INotificationManager
  22. {
  23. private readonly ILogger _logger;
  24. private readonly IUserManager _userManager;
  25. private readonly IServerConfigurationManager _config;
  26. private INotificationService[] _services = Array.Empty<INotificationService>();
  27. private INotificationTypeFactory[] _typeFactories = Array.Empty<INotificationTypeFactory>();
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="NotificationManager" /> class.
  30. /// </summary>
  31. /// <param name="logger">The logger.</param>
  32. /// <param name="userManager">The user manager.</param>
  33. /// <param name="config">The server configuration manager.</param>
  34. public NotificationManager(
  35. ILogger<NotificationManager> logger,
  36. IUserManager userManager,
  37. IServerConfigurationManager config)
  38. {
  39. _logger = logger;
  40. _userManager = userManager;
  41. _config = config;
  42. }
  43. private NotificationOptions GetConfiguration()
  44. {
  45. return _config.GetConfiguration<NotificationOptions>("notifications");
  46. }
  47. /// <inheritdoc />
  48. public Task SendNotification(NotificationRequest request, CancellationToken cancellationToken)
  49. {
  50. return SendNotification(request, null, cancellationToken);
  51. }
  52. /// <inheritdoc />
  53. public Task SendNotification(NotificationRequest request, BaseItem? relatedItem, CancellationToken cancellationToken)
  54. {
  55. var notificationType = request.NotificationType;
  56. var options = string.IsNullOrEmpty(notificationType) ?
  57. null :
  58. GetConfiguration().GetOptions(notificationType);
  59. var users = GetUserIds(request, options)
  60. .Select(i => _userManager.GetUserById(i))
  61. .Where(i => relatedItem == null || relatedItem.IsVisibleStandalone(i))
  62. .ToArray();
  63. var title = request.Name;
  64. var description = request.Description;
  65. var tasks = _services.Where(i => IsEnabled(i, notificationType))
  66. .Select(i => SendNotification(request, i, users, title, description, cancellationToken));
  67. return Task.WhenAll(tasks);
  68. }
  69. private Task SendNotification(
  70. NotificationRequest request,
  71. INotificationService service,
  72. IEnumerable<User> users,
  73. string title,
  74. string description,
  75. CancellationToken cancellationToken)
  76. {
  77. users = users.Where(i => IsEnabledForUser(service, i))
  78. .ToList();
  79. var tasks = users.Select(i => SendNotification(request, service, title, description, i, cancellationToken));
  80. return Task.WhenAll(tasks);
  81. }
  82. private IEnumerable<Guid> GetUserIds(NotificationRequest request, NotificationOption? options)
  83. {
  84. if (request.SendToUserMode.HasValue)
  85. {
  86. switch (request.SendToUserMode.Value)
  87. {
  88. case SendToUserType.Admins:
  89. return _userManager.Users.Where(i => i.Policy.IsAdministrator)
  90. .Select(i => i.Id);
  91. case SendToUserType.All:
  92. return _userManager.UsersIds;
  93. case SendToUserType.Custom:
  94. return request.UserIds;
  95. default:
  96. throw new ArgumentException("Unrecognized SendToUserMode: " + request.SendToUserMode.Value);
  97. }
  98. }
  99. if (options != null && !string.IsNullOrEmpty(request.NotificationType))
  100. {
  101. var config = GetConfiguration();
  102. return _userManager.Users
  103. .Where(i => config.IsEnabledToSendToUser(request.NotificationType, i.Id.ToString("N", CultureInfo.InvariantCulture), i.Policy))
  104. .Select(i => i.Id);
  105. }
  106. return request.UserIds;
  107. }
  108. private async Task SendNotification(
  109. NotificationRequest request,
  110. INotificationService service,
  111. string title,
  112. string description,
  113. User user,
  114. CancellationToken cancellationToken)
  115. {
  116. var notification = new UserNotification
  117. {
  118. Date = request.Date,
  119. Description = description,
  120. Level = request.Level,
  121. Name = title,
  122. Url = request.Url,
  123. User = user
  124. };
  125. _logger.LogDebug("Sending notification via {0} to user {1}", service.Name, user.Name);
  126. try
  127. {
  128. await service.SendNotification(notification, cancellationToken).ConfigureAwait(false);
  129. }
  130. catch (Exception ex)
  131. {
  132. _logger.LogError(ex, "Error sending notification to {0}", service.Name);
  133. }
  134. }
  135. private bool IsEnabledForUser(INotificationService service, User user)
  136. {
  137. try
  138. {
  139. return service.IsEnabledForUser(user);
  140. }
  141. catch (Exception ex)
  142. {
  143. _logger.LogError(ex, "Error in IsEnabledForUser");
  144. return false;
  145. }
  146. }
  147. private bool IsEnabled(INotificationService service, string notificationType)
  148. {
  149. if (string.IsNullOrEmpty(notificationType))
  150. {
  151. return true;
  152. }
  153. return GetConfiguration().IsServiceEnabled(service.Name, notificationType);
  154. }
  155. /// <inheritdoc />
  156. public void AddParts(IEnumerable<INotificationService> services, IEnumerable<INotificationTypeFactory> notificationTypeFactories)
  157. {
  158. _services = services.ToArray();
  159. _typeFactories = notificationTypeFactories.ToArray();
  160. }
  161. /// <inheritdoc />
  162. public List<NotificationTypeInfo> GetNotificationTypes()
  163. {
  164. var list = _typeFactories.Select(i =>
  165. {
  166. try
  167. {
  168. return i.GetNotificationTypes().ToList();
  169. }
  170. catch (Exception ex)
  171. {
  172. _logger.LogError(ex, "Error in GetNotificationTypes");
  173. return new List<NotificationTypeInfo>();
  174. }
  175. }).SelectMany(i => i).ToList();
  176. var config = GetConfiguration();
  177. foreach (var i in list)
  178. {
  179. i.Enabled = config.IsEnabled(i.Type);
  180. }
  181. return list;
  182. }
  183. /// <inheritdoc />
  184. public IEnumerable<NameIdPair> GetNotificationServices()
  185. {
  186. return _services.Select(i => new NameIdPair
  187. {
  188. Name = i.Name,
  189. Id = i.Name.GetMD5().ToString("N", CultureInfo.InvariantCulture)
  190. }).OrderBy(i => i.Name);
  191. }
  192. }
  193. }