Notifications.cs 10 KB

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