NotificationEntryPoint.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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.Events;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Controller;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Entities.Audio;
  12. using MediaBrowser.Controller.Entities.TV;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.Notifications;
  15. using MediaBrowser.Controller.Plugins;
  16. using MediaBrowser.Model.Activity;
  17. using MediaBrowser.Model.Globalization;
  18. using MediaBrowser.Model.Notifications;
  19. using Microsoft.Extensions.Logging;
  20. namespace Emby.Notifications
  21. {
  22. /// <summary>
  23. /// Creates notifications for various system events.
  24. /// </summary>
  25. public class NotificationEntryPoint : IServerEntryPoint
  26. {
  27. private readonly ILogger<NotificationEntryPoint> _logger;
  28. private readonly IActivityManager _activityManager;
  29. private readonly ILocalizationManager _localization;
  30. private readonly INotificationManager _notificationManager;
  31. private readonly ILibraryManager _libraryManager;
  32. private readonly IServerApplicationHost _appHost;
  33. private readonly IConfigurationManager _config;
  34. private readonly object _libraryChangedSyncLock = new object();
  35. private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
  36. private Timer? _libraryUpdateTimer;
  37. private string[] _coreNotificationTypes;
  38. private bool _disposed = false;
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="NotificationEntryPoint" /> class.
  41. /// </summary>
  42. /// <param name="logger">The logger.</param>
  43. /// <param name="activityManager">The activity manager.</param>
  44. /// <param name="localization">The localization manager.</param>
  45. /// <param name="notificationManager">The notification manager.</param>
  46. /// <param name="libraryManager">The library manager.</param>
  47. /// <param name="appHost">The application host.</param>
  48. /// <param name="config">The configuration manager.</param>
  49. public NotificationEntryPoint(
  50. ILogger<NotificationEntryPoint> logger,
  51. IActivityManager activityManager,
  52. ILocalizationManager localization,
  53. INotificationManager notificationManager,
  54. ILibraryManager libraryManager,
  55. IServerApplicationHost appHost,
  56. IConfigurationManager config)
  57. {
  58. _logger = logger;
  59. _activityManager = activityManager;
  60. _localization = localization;
  61. _notificationManager = notificationManager;
  62. _libraryManager = libraryManager;
  63. _appHost = appHost;
  64. _config = config;
  65. _coreNotificationTypes = new CoreNotificationTypes(localization).GetNotificationTypes().Select(i => i.Type).ToArray();
  66. }
  67. /// <inheritdoc />
  68. public Task RunAsync()
  69. {
  70. _libraryManager.ItemAdded += OnLibraryManagerItemAdded;
  71. _appHost.HasPendingRestartChanged += OnAppHostHasPendingRestartChanged;
  72. _activityManager.EntryCreated += OnActivityManagerEntryCreated;
  73. return Task.CompletedTask;
  74. }
  75. private async void OnAppHostHasPendingRestartChanged(object? sender, EventArgs e)
  76. {
  77. var type = NotificationType.ServerRestartRequired.ToString();
  78. var notification = new NotificationRequest
  79. {
  80. NotificationType = type,
  81. Name = string.Format(
  82. CultureInfo.InvariantCulture,
  83. _localization.GetLocalizedString("ServerNameNeedsToBeRestarted"),
  84. _appHost.Name)
  85. };
  86. await SendNotification(notification, null).ConfigureAwait(false);
  87. }
  88. private async void OnActivityManagerEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e)
  89. {
  90. var entry = e.Argument;
  91. var type = entry.Type;
  92. if (string.IsNullOrEmpty(type) || !_coreNotificationTypes.Contains(type, StringComparer.OrdinalIgnoreCase))
  93. {
  94. return;
  95. }
  96. var userId = e.Argument.UserId;
  97. if (!userId.Equals(Guid.Empty) && !GetOptions().IsEnabledToMonitorUser(type, userId))
  98. {
  99. return;
  100. }
  101. var notification = new NotificationRequest
  102. {
  103. NotificationType = type,
  104. Name = entry.Name,
  105. Description = entry.Overview
  106. };
  107. await SendNotification(notification, null).ConfigureAwait(false);
  108. }
  109. private NotificationOptions GetOptions()
  110. {
  111. return _config.GetConfiguration<NotificationOptions>("notifications");
  112. }
  113. private void OnLibraryManagerItemAdded(object? sender, ItemChangeEventArgs e)
  114. {
  115. if (!FilterItem(e.Item))
  116. {
  117. return;
  118. }
  119. lock (_libraryChangedSyncLock)
  120. {
  121. if (_libraryUpdateTimer == null)
  122. {
  123. _libraryUpdateTimer = new Timer(
  124. LibraryUpdateTimerCallback,
  125. null,
  126. 5000,
  127. Timeout.Infinite);
  128. }
  129. else
  130. {
  131. _libraryUpdateTimer.Change(5000, Timeout.Infinite);
  132. }
  133. _itemsAdded.Add(e.Item);
  134. }
  135. }
  136. private bool FilterItem(BaseItem item)
  137. {
  138. if (item.IsFolder)
  139. {
  140. return false;
  141. }
  142. if (!item.HasPathProtocol)
  143. {
  144. return false;
  145. }
  146. if (item is IItemByName)
  147. {
  148. return false;
  149. }
  150. return item.SourceType == SourceType.Library;
  151. }
  152. private async void LibraryUpdateTimerCallback(object? state)
  153. {
  154. List<BaseItem> items;
  155. lock (_libraryChangedSyncLock)
  156. {
  157. items = _itemsAdded.ToList();
  158. _itemsAdded.Clear();
  159. _libraryUpdateTimer!.Dispose(); // Shouldn't be null as it just set off this callback
  160. _libraryUpdateTimer = null;
  161. }
  162. if (items.Count > 10)
  163. {
  164. items = items.GetRange(0, 10);
  165. }
  166. foreach (var item in items)
  167. {
  168. var notification = new NotificationRequest
  169. {
  170. NotificationType = NotificationType.NewLibraryContent.ToString(),
  171. Name = string.Format(
  172. CultureInfo.InvariantCulture,
  173. _localization.GetLocalizedString("ValueHasBeenAddedToLibrary"),
  174. GetItemName(item)),
  175. Description = item.Overview
  176. };
  177. await SendNotification(notification, item).ConfigureAwait(false);
  178. }
  179. }
  180. /// <summary>
  181. /// Creates a human readable name for the item.
  182. /// </summary>
  183. /// <param name="item">The item.</param>
  184. /// <returns>A human readable name for the item.</returns>
  185. public static string GetItemName(BaseItem item)
  186. {
  187. var name = item.Name;
  188. if (item is Episode episode)
  189. {
  190. if (episode.IndexNumber.HasValue)
  191. {
  192. name = string.Format(
  193. CultureInfo.InvariantCulture,
  194. "Ep{0} - {1}",
  195. episode.IndexNumber.Value,
  196. name);
  197. }
  198. if (episode.ParentIndexNumber.HasValue)
  199. {
  200. name = string.Format(
  201. CultureInfo.InvariantCulture,
  202. "S{0}, {1}",
  203. episode.ParentIndexNumber.Value,
  204. name);
  205. }
  206. }
  207. if (item is IHasSeries hasSeries)
  208. {
  209. name = hasSeries.SeriesName + " - " + name;
  210. }
  211. if (item is IHasAlbumArtist hasAlbumArtist)
  212. {
  213. var artists = hasAlbumArtist.AlbumArtists;
  214. if (artists.Count > 0)
  215. {
  216. name = artists[0] + " - " + name;
  217. }
  218. }
  219. else if (item is IHasArtist hasArtist)
  220. {
  221. var artists = hasArtist.Artists;
  222. if (artists.Count > 0)
  223. {
  224. name = artists[0] + " - " + name;
  225. }
  226. }
  227. return name;
  228. }
  229. private async Task SendNotification(NotificationRequest notification, BaseItem? relatedItem)
  230. {
  231. try
  232. {
  233. await _notificationManager.SendNotification(notification, relatedItem, CancellationToken.None).ConfigureAwait(false);
  234. }
  235. catch (Exception ex)
  236. {
  237. _logger.LogError(ex, "Error sending notification");
  238. }
  239. }
  240. /// <inheritdoc />
  241. public void Dispose()
  242. {
  243. Dispose(true);
  244. GC.SuppressFinalize(this);
  245. }
  246. /// <summary>
  247. /// Releases unmanaged and optionally managed resources.
  248. /// </summary>
  249. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  250. protected virtual void Dispose(bool disposing)
  251. {
  252. if (_disposed)
  253. {
  254. return;
  255. }
  256. if (disposing)
  257. {
  258. _libraryUpdateTimer?.Dispose();
  259. }
  260. _libraryUpdateTimer = null;
  261. _libraryManager.ItemAdded -= OnLibraryManagerItemAdded;
  262. _appHost.HasPendingRestartChanged -= OnAppHostHasPendingRestartChanged;
  263. _activityManager.EntryCreated -= OnActivityManagerEntryCreated;
  264. _disposed = true;
  265. }
  266. }
  267. }