Notifications.cs 10 KB

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