NotificationManager.cs 7.6 KB

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