NotificationEntryPoint.cs 10 KB

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