NotificationEntryPoint.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. _appHost.HasUpdateAvailableChanged += OnAppHostHasUpdateAvailableChanged;
  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, StringComparer.OrdinalIgnoreCase))
  94. {
  95. return;
  96. }
  97. var userId = e.Argument.UserId;
  98. if (!userId.Equals(Guid.Empty) && !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 async void OnAppHostHasUpdateAvailableChanged(object? sender, EventArgs e)
  115. {
  116. if (!_appHost.HasUpdateAvailable)
  117. {
  118. return;
  119. }
  120. var type = NotificationType.ApplicationUpdateAvailable.ToString();
  121. var notification = new NotificationRequest
  122. {
  123. Description = "Please see jellyfin.org for details.",
  124. NotificationType = type,
  125. Name = _localization.GetLocalizedString("NewVersionIsAvailable")
  126. };
  127. await SendNotification(notification, null).ConfigureAwait(false);
  128. }
  129. private void OnLibraryManagerItemAdded(object? sender, ItemChangeEventArgs e)
  130. {
  131. if (!FilterItem(e.Item))
  132. {
  133. return;
  134. }
  135. lock (_libraryChangedSyncLock)
  136. {
  137. if (_libraryUpdateTimer == null)
  138. {
  139. _libraryUpdateTimer = new Timer(
  140. LibraryUpdateTimerCallback,
  141. null,
  142. 5000,
  143. Timeout.Infinite);
  144. }
  145. else
  146. {
  147. _libraryUpdateTimer.Change(5000, Timeout.Infinite);
  148. }
  149. _itemsAdded.Add(e.Item);
  150. }
  151. }
  152. private bool FilterItem(BaseItem item)
  153. {
  154. if (item.IsFolder)
  155. {
  156. return false;
  157. }
  158. if (!item.HasPathProtocol)
  159. {
  160. return false;
  161. }
  162. if (item is IItemByName)
  163. {
  164. return false;
  165. }
  166. return item.SourceType == SourceType.Library;
  167. }
  168. private async void LibraryUpdateTimerCallback(object? state)
  169. {
  170. List<BaseItem> items;
  171. lock (_libraryChangedSyncLock)
  172. {
  173. items = _itemsAdded.ToList();
  174. _itemsAdded.Clear();
  175. _libraryUpdateTimer!.Dispose(); // Shouldn't be null as it just set off this callback
  176. _libraryUpdateTimer = null;
  177. }
  178. if (items.Count > 10)
  179. {
  180. items = items.GetRange(0, 10);
  181. }
  182. foreach (var item in items)
  183. {
  184. var notification = new NotificationRequest
  185. {
  186. NotificationType = NotificationType.NewLibraryContent.ToString(),
  187. Name = string.Format(
  188. CultureInfo.InvariantCulture,
  189. _localization.GetLocalizedString("ValueHasBeenAddedToLibrary"),
  190. GetItemName(item)),
  191. Description = item.Overview
  192. };
  193. await SendNotification(notification, item).ConfigureAwait(false);
  194. }
  195. }
  196. /// <summary>
  197. /// Creates a human readable name for the item.
  198. /// </summary>
  199. /// <param name="item">The item.</param>
  200. /// <returns>A human readable name for the item.</returns>
  201. public static string GetItemName(BaseItem item)
  202. {
  203. var name = item.Name;
  204. if (item is Episode episode)
  205. {
  206. if (episode.IndexNumber.HasValue)
  207. {
  208. name = string.Format(
  209. CultureInfo.InvariantCulture,
  210. "Ep{0} - {1}",
  211. episode.IndexNumber.Value,
  212. name);
  213. }
  214. if (episode.ParentIndexNumber.HasValue)
  215. {
  216. name = string.Format(
  217. CultureInfo.InvariantCulture,
  218. "S{0}, {1}",
  219. episode.ParentIndexNumber.Value,
  220. name);
  221. }
  222. }
  223. if (item is IHasSeries hasSeries)
  224. {
  225. name = hasSeries.SeriesName + " - " + name;
  226. }
  227. if (item is IHasAlbumArtist hasAlbumArtist)
  228. {
  229. var artists = hasAlbumArtist.AlbumArtists;
  230. if (artists.Count > 0)
  231. {
  232. name = artists[0] + " - " + name;
  233. }
  234. }
  235. else if (item is IHasArtist hasArtist)
  236. {
  237. var artists = hasArtist.Artists;
  238. if (artists.Count > 0)
  239. {
  240. name = artists[0] + " - " + name;
  241. }
  242. }
  243. return name;
  244. }
  245. private async Task SendNotification(NotificationRequest notification, BaseItem? relatedItem)
  246. {
  247. try
  248. {
  249. await _notificationManager.SendNotification(notification, relatedItem, CancellationToken.None).ConfigureAwait(false);
  250. }
  251. catch (Exception ex)
  252. {
  253. _logger.LogError(ex, "Error sending notification");
  254. }
  255. }
  256. /// <inheritdoc />
  257. public void Dispose()
  258. {
  259. Dispose(true);
  260. GC.SuppressFinalize(this);
  261. }
  262. /// <summary>
  263. /// Releases unmanaged and optionally managed resources.
  264. /// </summary>
  265. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  266. protected virtual void Dispose(bool disposing)
  267. {
  268. if (_disposed)
  269. {
  270. return;
  271. }
  272. if (disposing)
  273. {
  274. _libraryUpdateTimer?.Dispose();
  275. }
  276. _libraryUpdateTimer = null;
  277. _libraryManager.ItemAdded -= OnLibraryManagerItemAdded;
  278. _appHost.HasPendingRestartChanged -= OnAppHostHasPendingRestartChanged;
  279. _appHost.HasUpdateAvailableChanged -= OnAppHostHasUpdateAvailableChanged;
  280. _activityManager.EntryCreated -= OnActivityManagerEntryCreated;
  281. _disposed = true;
  282. }
  283. }
  284. }