Notifications.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 void Run()
  66. {
  67. _libraryManager.ItemAdded += _libraryManager_ItemAdded;
  68. _appHost.HasPendingRestartChanged += _appHost_HasPendingRestartChanged;
  69. _appHost.HasUpdateAvailableChanged += _appHost_HasUpdateAvailableChanged;
  70. _activityManager.EntryCreated += _activityManager_EntryCreated;
  71. }
  72. private async void _appHost_HasPendingRestartChanged(object sender, EventArgs e)
  73. {
  74. var type = NotificationType.ServerRestartRequired.ToString();
  75. var notification = new NotificationRequest
  76. {
  77. NotificationType = type,
  78. Name = string.Format(_localization.GetLocalizedString("ServerNameNeedsToBeRestarted"), _appHost.Name)
  79. };
  80. await SendNotification(notification, null).ConfigureAwait(false);
  81. }
  82. private async void _activityManager_EntryCreated(object sender, GenericEventArgs<ActivityLogEntry> e)
  83. {
  84. var entry = e.Argument;
  85. var type = entry.Type;
  86. if (string.IsNullOrEmpty(type) || !_coreNotificationTypes.Contains(type, StringComparer.OrdinalIgnoreCase))
  87. {
  88. return;
  89. }
  90. var userId = e.Argument.UserId;
  91. if (!userId.Equals(Guid.Empty) && !GetOptions().IsEnabledToMonitorUser(type, userId))
  92. {
  93. return;
  94. }
  95. var notification = new NotificationRequest
  96. {
  97. NotificationType = type,
  98. Name = entry.Name,
  99. Description = entry.Overview
  100. };
  101. await SendNotification(notification, null).ConfigureAwait(false);
  102. }
  103. private NotificationOptions GetOptions()
  104. {
  105. return _config.GetConfiguration<NotificationOptions>("notifications");
  106. }
  107. async void _appHost_HasUpdateAvailableChanged(object sender, EventArgs e)
  108. {
  109. // This notification is for users who can't auto-update (aka running as service)
  110. if (!_appHost.HasUpdateAvailable || _appHost.CanSelfUpdate)
  111. {
  112. return;
  113. }
  114. var type = NotificationType.ApplicationUpdateAvailable.ToString();
  115. var notification = new NotificationRequest
  116. {
  117. Description = "Please see jellyfin.media for details.",
  118. NotificationType = type,
  119. Name = _localization.GetLocalizedString("NewVersionIsAvailable")
  120. };
  121. await SendNotification(notification, null).ConfigureAwait(false);
  122. }
  123. private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
  124. void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  125. {
  126. if (!FilterItem(e.Item))
  127. {
  128. return;
  129. }
  130. lock (_libraryChangedSyncLock)
  131. {
  132. if (LibraryUpdateTimer == null)
  133. {
  134. LibraryUpdateTimer = _timerFactory.Create(LibraryUpdateTimerCallback, null, 5000,
  135. Timeout.Infinite);
  136. }
  137. else
  138. {
  139. LibraryUpdateTimer.Change(5000, Timeout.Infinite);
  140. }
  141. _itemsAdded.Add(e.Item);
  142. }
  143. }
  144. private bool FilterItem(BaseItem item)
  145. {
  146. if (item.IsFolder)
  147. {
  148. return false;
  149. }
  150. if (!item.HasPathProtocol)
  151. {
  152. return false;
  153. }
  154. if (item is IItemByName)
  155. {
  156. return false;
  157. }
  158. return item.SourceType == SourceType.Library;
  159. }
  160. private async void LibraryUpdateTimerCallback(object state)
  161. {
  162. List<BaseItem> items;
  163. lock (_libraryChangedSyncLock)
  164. {
  165. items = _itemsAdded.ToList();
  166. _itemsAdded.Clear();
  167. DisposeLibraryUpdateTimer();
  168. }
  169. items = items.Take(10).ToList();
  170. foreach (var item in items)
  171. {
  172. var notification = new NotificationRequest
  173. {
  174. NotificationType = NotificationType.NewLibraryContent.ToString(),
  175. Name = string.Format(_localization.GetLocalizedString("ValueHasBeenAddedToLibrary"), GetItemName(item)),
  176. Description = item.Overview
  177. };
  178. await SendNotification(notification, item).ConfigureAwait(false);
  179. }
  180. }
  181. public static string GetItemName(BaseItem item)
  182. {
  183. var name = item.Name;
  184. var episode = item as Episode;
  185. if (episode != null)
  186. {
  187. if (episode.IndexNumber.HasValue)
  188. {
  189. name = string.Format("Ep{0} - {1}", episode.IndexNumber.Value.ToString(CultureInfo.InvariantCulture), name);
  190. }
  191. if (episode.ParentIndexNumber.HasValue)
  192. {
  193. name = string.Format("S{0}, {1}", episode.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture), name);
  194. }
  195. }
  196. var hasSeries = item as IHasSeries;
  197. if (hasSeries != null)
  198. {
  199. name = hasSeries.SeriesName + " - " + name;
  200. }
  201. var hasAlbumArtist = item as IHasAlbumArtist;
  202. if (hasAlbumArtist != null)
  203. {
  204. var artists = hasAlbumArtist.AlbumArtists;
  205. if (artists.Length > 0)
  206. {
  207. name = artists[0] + " - " + name;
  208. }
  209. }
  210. else
  211. {
  212. var hasArtist = item as IHasArtist;
  213. if (hasArtist != null)
  214. {
  215. var artists = hasArtist.Artists;
  216. if (artists.Length > 0)
  217. {
  218. name = artists[0] + " - " + name;
  219. }
  220. }
  221. }
  222. return name;
  223. }
  224. private async Task SendNotification(NotificationRequest notification, BaseItem relatedItem)
  225. {
  226. try
  227. {
  228. await _notificationManager.SendNotification(notification, relatedItem, CancellationToken.None).ConfigureAwait(false);
  229. }
  230. catch (Exception ex)
  231. {
  232. _logger.LogError(ex, "Error sending notification");
  233. }
  234. }
  235. public void Dispose()
  236. {
  237. DisposeLibraryUpdateTimer();
  238. _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
  239. _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged;
  240. _appHost.HasUpdateAvailableChanged -= _appHost_HasUpdateAvailableChanged;
  241. _activityManager.EntryCreated -= _activityManager_EntryCreated;
  242. }
  243. private void DisposeLibraryUpdateTimer()
  244. {
  245. if (LibraryUpdateTimer != null)
  246. {
  247. LibraryUpdateTimer.Dispose();
  248. LibraryUpdateTimer = null;
  249. }
  250. }
  251. }
  252. }