NotificationEntryPoint.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 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. items = items.Take(10).ToList();
  179. foreach (var item in items)
  180. {
  181. var notification = new NotificationRequest
  182. {
  183. NotificationType = NotificationType.NewLibraryContent.ToString(),
  184. Name = string.Format(
  185. CultureInfo.InvariantCulture,
  186. _localization.GetLocalizedString("ValueHasBeenAddedToLibrary"),
  187. GetItemName(item)),
  188. Description = item.Overview
  189. };
  190. await SendNotification(notification, item).ConfigureAwait(false);
  191. }
  192. }
  193. /// <summary>
  194. /// Creates a human readable name for the item.
  195. /// </summary>
  196. /// <param name="item">The item.</param>
  197. /// <returns>A human readable name for the item.</returns>
  198. public static string GetItemName(BaseItem item)
  199. {
  200. var name = item.Name;
  201. if (item is Episode episode)
  202. {
  203. if (episode.IndexNumber.HasValue)
  204. {
  205. name = string.Format(
  206. CultureInfo.InvariantCulture,
  207. "Ep{0} - {1}",
  208. episode.IndexNumber.Value,
  209. name);
  210. }
  211. if (episode.ParentIndexNumber.HasValue)
  212. {
  213. name = string.Format(
  214. CultureInfo.InvariantCulture,
  215. "S{0}, {1}",
  216. episode.ParentIndexNumber.Value,
  217. name);
  218. }
  219. }
  220. if (item is IHasSeries hasSeries)
  221. {
  222. name = hasSeries.SeriesName + " - " + name;
  223. }
  224. if (item is IHasAlbumArtist hasAlbumArtist)
  225. {
  226. var artists = hasAlbumArtist.AlbumArtists;
  227. if (artists.Count > 0)
  228. {
  229. name = artists[0] + " - " + name;
  230. }
  231. }
  232. else if (item is IHasArtist hasArtist)
  233. {
  234. var artists = hasArtist.Artists;
  235. if (artists.Count > 0)
  236. {
  237. name = artists[0] + " - " + name;
  238. }
  239. }
  240. return name;
  241. }
  242. private async Task SendNotification(NotificationRequest notification, BaseItem? relatedItem)
  243. {
  244. try
  245. {
  246. await _notificationManager.SendNotification(notification, relatedItem, CancellationToken.None).ConfigureAwait(false);
  247. }
  248. catch (Exception ex)
  249. {
  250. _logger.LogError(ex, "Error sending notification");
  251. }
  252. }
  253. /// <inheritdoc />
  254. public void Dispose()
  255. {
  256. Dispose(true);
  257. GC.SuppressFinalize(this);
  258. }
  259. /// <summary>
  260. /// Releases unmanaged and optionally managed resources.
  261. /// </summary>
  262. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  263. protected virtual void Dispose(bool disposing)
  264. {
  265. if (_disposed)
  266. {
  267. return;
  268. }
  269. if (disposing)
  270. {
  271. _libraryUpdateTimer?.Dispose();
  272. }
  273. _libraryUpdateTimer = null;
  274. _libraryManager.ItemAdded -= OnLibraryManagerItemAdded;
  275. _appHost.HasPendingRestartChanged -= OnAppHostHasPendingRestartChanged;
  276. _appHost.HasUpdateAvailableChanged -= OnAppHostHasUpdateAvailableChanged;
  277. _activityManager.EntryCreated -= OnActivityManagerEntryCreated;
  278. _disposed = true;
  279. }
  280. }
  281. }