Notifications.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Controller;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Entities.Audio;
  11. using MediaBrowser.Controller.Entities.TV;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Notifications;
  14. using MediaBrowser.Controller.Plugins;
  15. using MediaBrowser.Model.Activity;
  16. using MediaBrowser.Model.Events;
  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 Notifications : IServerEntryPoint
  26. {
  27. private readonly ILogger _logger;
  28. private readonly INotificationManager _notificationManager;
  29. private readonly ILibraryManager _libraryManager;
  30. private readonly IServerApplicationHost _appHost;
  31. private Timer LibraryUpdateTimer { get; set; }
  32. private readonly object _libraryChangedSyncLock = new object();
  33. private readonly IConfigurationManager _config;
  34. private readonly ILocalizationManager _localization;
  35. private readonly IActivityManager _activityManager;
  36. private string[] _coreNotificationTypes;
  37. public Notifications(
  38. IActivityManager activityManager,
  39. ILocalizationManager localization,
  40. ILogger logger,
  41. INotificationManager notificationManager,
  42. ILibraryManager libraryManager,
  43. IServerApplicationHost appHost,
  44. IConfigurationManager config)
  45. {
  46. _logger = logger;
  47. _notificationManager = notificationManager;
  48. _libraryManager = libraryManager;
  49. _appHost = appHost;
  50. _config = config;
  51. _localization = localization;
  52. _activityManager = activityManager;
  53. _coreNotificationTypes = new CoreNotificationTypes(localization).GetNotificationTypes().Select(i => i.Type).ToArray();
  54. }
  55. public Task RunAsync()
  56. {
  57. _libraryManager.ItemAdded += _libraryManager_ItemAdded;
  58. _appHost.HasPendingRestartChanged += _appHost_HasPendingRestartChanged;
  59. _appHost.HasUpdateAvailableChanged += _appHost_HasUpdateAvailableChanged;
  60. _activityManager.EntryCreated += _activityManager_EntryCreated;
  61. return Task.CompletedTask;
  62. }
  63. private async void _appHost_HasPendingRestartChanged(object sender, EventArgs e)
  64. {
  65. var type = NotificationType.ServerRestartRequired.ToString();
  66. var notification = new NotificationRequest
  67. {
  68. NotificationType = type,
  69. Name = string.Format(_localization.GetLocalizedString("ServerNameNeedsToBeRestarted"), _appHost.Name)
  70. };
  71. await SendNotification(notification, null).ConfigureAwait(false);
  72. }
  73. private async void _activityManager_EntryCreated(object sender, GenericEventArgs<ActivityLogEntry> e)
  74. {
  75. var entry = e.Argument;
  76. var type = entry.Type;
  77. if (string.IsNullOrEmpty(type) || !_coreNotificationTypes.Contains(type, StringComparer.OrdinalIgnoreCase))
  78. {
  79. return;
  80. }
  81. var userId = e.Argument.UserId;
  82. if (!userId.Equals(Guid.Empty) && !GetOptions().IsEnabledToMonitorUser(type, userId))
  83. {
  84. return;
  85. }
  86. var notification = new NotificationRequest
  87. {
  88. NotificationType = type,
  89. Name = entry.Name,
  90. Description = entry.Overview
  91. };
  92. await SendNotification(notification, null).ConfigureAwait(false);
  93. }
  94. private NotificationOptions GetOptions()
  95. {
  96. return _config.GetConfiguration<NotificationOptions>("notifications");
  97. }
  98. private async void _appHost_HasUpdateAvailableChanged(object sender, EventArgs e)
  99. {
  100. if (!_appHost.HasUpdateAvailable)
  101. {
  102. return;
  103. }
  104. var type = NotificationType.ApplicationUpdateAvailable.ToString();
  105. var notification = new NotificationRequest
  106. {
  107. Description = "Please see jellyfin.media for details.",
  108. NotificationType = type,
  109. Name = _localization.GetLocalizedString("NewVersionIsAvailable")
  110. };
  111. await SendNotification(notification, null).ConfigureAwait(false);
  112. }
  113. private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
  114. private void _libraryManager_ItemAdded(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(LibraryUpdateTimerCallback, null, 5000,
  125. Timeout.Infinite);
  126. }
  127. else
  128. {
  129. LibraryUpdateTimer.Change(5000, Timeout.Infinite);
  130. }
  131. _itemsAdded.Add(e.Item);
  132. }
  133. }
  134. private bool FilterItem(BaseItem item)
  135. {
  136. if (item.IsFolder)
  137. {
  138. return false;
  139. }
  140. if (!item.HasPathProtocol)
  141. {
  142. return false;
  143. }
  144. if (item is IItemByName)
  145. {
  146. return false;
  147. }
  148. return item.SourceType == SourceType.Library;
  149. }
  150. private async void LibraryUpdateTimerCallback(object state)
  151. {
  152. List<BaseItem> items;
  153. lock (_libraryChangedSyncLock)
  154. {
  155. items = _itemsAdded.ToList();
  156. _itemsAdded.Clear();
  157. DisposeLibraryUpdateTimer();
  158. }
  159. items = items.Take(10).ToList();
  160. foreach (var item in items)
  161. {
  162. var notification = new NotificationRequest
  163. {
  164. NotificationType = NotificationType.NewLibraryContent.ToString(),
  165. Name = string.Format(_localization.GetLocalizedString("ValueHasBeenAddedToLibrary"), GetItemName(item)),
  166. Description = item.Overview
  167. };
  168. await SendNotification(notification, item).ConfigureAwait(false);
  169. }
  170. }
  171. public static string GetItemName(BaseItem item)
  172. {
  173. var name = item.Name;
  174. if (item is Episode episode)
  175. {
  176. if (episode.IndexNumber.HasValue)
  177. {
  178. name = string.Format(
  179. CultureInfo.InvariantCulture,
  180. "Ep{0} - {1}",
  181. episode.IndexNumber.Value,
  182. name);
  183. }
  184. if (episode.ParentIndexNumber.HasValue)
  185. {
  186. name = string.Format(
  187. CultureInfo.InvariantCulture,
  188. "S{0}, {1}",
  189. episode.ParentIndexNumber.Value,
  190. name);
  191. }
  192. }
  193. if (item is IHasSeries hasSeries)
  194. {
  195. name = hasSeries.SeriesName + " - " + name;
  196. }
  197. if (item is IHasAlbumArtist hasAlbumArtist)
  198. {
  199. var artists = hasAlbumArtist.AlbumArtists;
  200. if (artists.Count > 0)
  201. {
  202. name = artists[0] + " - " + name;
  203. }
  204. }
  205. else if (item is IHasArtist hasArtist)
  206. {
  207. var artists = hasArtist.Artists;
  208. if (artists.Count > 0)
  209. {
  210. name = artists[0] + " - " + name;
  211. }
  212. }
  213. return name;
  214. }
  215. private async Task SendNotification(NotificationRequest notification, BaseItem relatedItem)
  216. {
  217. try
  218. {
  219. await _notificationManager.SendNotification(notification, relatedItem, CancellationToken.None).ConfigureAwait(false);
  220. }
  221. catch (Exception ex)
  222. {
  223. _logger.LogError(ex, "Error sending notification");
  224. }
  225. }
  226. public void Dispose()
  227. {
  228. DisposeLibraryUpdateTimer();
  229. _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
  230. _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged;
  231. _appHost.HasUpdateAvailableChanged -= _appHost_HasUpdateAvailableChanged;
  232. _activityManager.EntryCreated -= _activityManager_EntryCreated;
  233. }
  234. private void DisposeLibraryUpdateTimer()
  235. {
  236. if (LibraryUpdateTimer != null)
  237. {
  238. LibraryUpdateTimer.Dispose();
  239. LibraryUpdateTimer = null;
  240. }
  241. }
  242. }
  243. }