NotificationManager.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 == 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. .ToList();
  81. var tasks = users.Select(i => SendNotification(request, service, title, description, i, cancellationToken));
  82. return Task.WhenAll(tasks);
  83. }
  84. private IEnumerable<Guid> GetUserIds(NotificationRequest request, NotificationOption? options)
  85. {
  86. if (request.SendToUserMode.HasValue)
  87. {
  88. switch (request.SendToUserMode.Value)
  89. {
  90. case SendToUserType.Admins:
  91. return _userManager.Users.Where(i => i.HasPermission(PermissionKind.IsAdministrator))
  92. .Select(i => i.Id);
  93. case SendToUserType.All:
  94. return _userManager.UsersIds;
  95. case SendToUserType.Custom:
  96. return request.UserIds;
  97. default:
  98. throw new ArgumentException("Unrecognized SendToUserMode: " + request.SendToUserMode.Value);
  99. }
  100. }
  101. if (options != null && !string.IsNullOrEmpty(request.NotificationType))
  102. {
  103. var config = GetConfiguration();
  104. return _userManager.Users
  105. .Where(i => config.IsEnabledToSendToUser(request.NotificationType, i.Id.ToString("N", CultureInfo.InvariantCulture), i))
  106. .Select(i => i.Id);
  107. }
  108. return request.UserIds;
  109. }
  110. private async Task SendNotification(
  111. NotificationRequest request,
  112. INotificationService service,
  113. string title,
  114. string description,
  115. User user,
  116. CancellationToken cancellationToken)
  117. {
  118. var notification = new UserNotification
  119. {
  120. Date = request.Date,
  121. Description = description,
  122. Level = request.Level,
  123. Name = title,
  124. Url = request.Url,
  125. User = user
  126. };
  127. _logger.LogDebug("Sending notification via {0} to user {1}", service.Name, user.Username);
  128. try
  129. {
  130. await service.SendNotification(notification, cancellationToken).ConfigureAwait(false);
  131. }
  132. catch (Exception ex)
  133. {
  134. _logger.LogError(ex, "Error sending notification to {0}", service.Name);
  135. }
  136. }
  137. private bool IsEnabledForUser(INotificationService service, User user)
  138. {
  139. try
  140. {
  141. return service.IsEnabledForUser(user);
  142. }
  143. catch (Exception ex)
  144. {
  145. _logger.LogError(ex, "Error in IsEnabledForUser");
  146. return false;
  147. }
  148. }
  149. private bool IsEnabled(INotificationService service, string notificationType)
  150. {
  151. if (string.IsNullOrEmpty(notificationType))
  152. {
  153. return true;
  154. }
  155. return GetConfiguration().IsServiceEnabled(service.Name, notificationType);
  156. }
  157. /// <inheritdoc />
  158. public void AddParts(IEnumerable<INotificationService> services, IEnumerable<INotificationTypeFactory> notificationTypeFactories)
  159. {
  160. _services = services.ToArray();
  161. _typeFactories = notificationTypeFactories.ToArray();
  162. }
  163. /// <inheritdoc />
  164. public List<NotificationTypeInfo> GetNotificationTypes()
  165. {
  166. var list = _typeFactories.Select(i =>
  167. {
  168. try
  169. {
  170. return i.GetNotificationTypes().ToList();
  171. }
  172. catch (Exception ex)
  173. {
  174. _logger.LogError(ex, "Error in GetNotificationTypes");
  175. return new List<NotificationTypeInfo>();
  176. }
  177. }).SelectMany(i => i).ToList();
  178. var config = GetConfiguration();
  179. foreach (var i in list)
  180. {
  181. i.Enabled = config.IsEnabled(i.Type);
  182. }
  183. return list;
  184. }
  185. /// <inheritdoc />
  186. public IEnumerable<NameIdPair> GetNotificationServices()
  187. {
  188. return _services.Select(i => new NameIdPair
  189. {
  190. Name = i.Name,
  191. Id = i.Name.GetMD5().ToString("N", CultureInfo.InvariantCulture)
  192. }).OrderBy(i => i.Name);
  193. }
  194. }
  195. }