Notifications.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. using System.Globalization;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Plugins;
  4. using MediaBrowser.Common.ScheduledTasks;
  5. using MediaBrowser.Common.Updates;
  6. using MediaBrowser.Controller;
  7. using MediaBrowser.Controller.Configuration;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Entities.Audio;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Notifications;
  12. using MediaBrowser.Controller.Plugins;
  13. using MediaBrowser.Controller.Session;
  14. using MediaBrowser.Model.Configuration;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.Events;
  17. using MediaBrowser.Model.Logging;
  18. using MediaBrowser.Model.Notifications;
  19. using MediaBrowser.Model.Tasks;
  20. using MediaBrowser.Model.Updates;
  21. using System;
  22. using System.Collections.Generic;
  23. using System.Linq;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
  27. {
  28. /// <summary>
  29. /// Creates notifications for various system events
  30. /// </summary>
  31. public class Notifications : IServerEntryPoint
  32. {
  33. private readonly IInstallationManager _installationManager;
  34. private readonly IUserManager _userManager;
  35. private readonly ILogger _logger;
  36. private readonly ITaskManager _taskManager;
  37. private readonly INotificationManager _notificationManager;
  38. private readonly IServerConfigurationManager _config;
  39. private readonly ILibraryManager _libraryManager;
  40. private readonly ISessionManager _sessionManager;
  41. private readonly IServerApplicationHost _appHost;
  42. private Timer LibraryUpdateTimer { get; set; }
  43. private readonly object _libraryChangedSyncLock = new object();
  44. public Notifications(IInstallationManager installationManager, IUserManager userManager, ILogger logger, ITaskManager taskManager, INotificationManager notificationManager, IServerConfigurationManager config, ILibraryManager libraryManager, ISessionManager sessionManager, IServerApplicationHost appHost)
  45. {
  46. _installationManager = installationManager;
  47. _userManager = userManager;
  48. _logger = logger;
  49. _taskManager = taskManager;
  50. _notificationManager = notificationManager;
  51. _config = config;
  52. _libraryManager = libraryManager;
  53. _sessionManager = sessionManager;
  54. _appHost = appHost;
  55. }
  56. public void Run()
  57. {
  58. _installationManager.PluginInstalled += _installationManager_PluginInstalled;
  59. _installationManager.PluginUpdated += _installationManager_PluginUpdated;
  60. _installationManager.PackageInstallationFailed += _installationManager_PackageInstallationFailed;
  61. _installationManager.PluginUninstalled += _installationManager_PluginUninstalled;
  62. _taskManager.TaskCompleted += _taskManager_TaskCompleted;
  63. _userManager.UserCreated += _userManager_UserCreated;
  64. _libraryManager.ItemAdded += _libraryManager_ItemAdded;
  65. _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
  66. _appHost.HasPendingRestartChanged += _appHost_HasPendingRestartChanged;
  67. _appHost.HasUpdateAvailableChanged += _appHost_HasUpdateAvailableChanged;
  68. _appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
  69. }
  70. async void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
  71. {
  72. var type = NotificationType.ApplicationUpdateInstalled.ToString();
  73. var notification = new NotificationRequest
  74. {
  75. NotificationType = type
  76. };
  77. notification.Variables["Version"] = e.Argument.versionStr;
  78. notification.Variables["ReleaseNotes"] = e.Argument.description;
  79. await SendNotification(notification).ConfigureAwait(false);
  80. }
  81. async void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
  82. {
  83. var type = NotificationType.PluginUpdateInstalled.ToString();
  84. var installationInfo = e.Argument.Item1;
  85. var notification = new NotificationRequest
  86. {
  87. Description = installationInfo.Description,
  88. NotificationType = type
  89. };
  90. notification.Variables["Name"] = installationInfo.Name;
  91. notification.Variables["Version"] = installationInfo.Version.ToString();
  92. notification.Variables["ReleaseNotes"] = e.Argument.Item2.description;
  93. await SendNotification(notification).ConfigureAwait(false);
  94. }
  95. async void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
  96. {
  97. var type = NotificationType.PluginInstalled.ToString();
  98. var installationInfo = e.Argument;
  99. var notification = new NotificationRequest
  100. {
  101. Description = installationInfo.description,
  102. NotificationType = type
  103. };
  104. notification.Variables["Name"] = installationInfo.name;
  105. notification.Variables["Version"] = installationInfo.versionStr;
  106. await SendNotification(notification).ConfigureAwait(false);
  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 mediabrowser.tv for details.",
  119. NotificationType = type
  120. };
  121. await SendNotification(notification).ConfigureAwait(false);
  122. }
  123. async void _appHost_HasPendingRestartChanged(object sender, EventArgs e)
  124. {
  125. if (!_appHost.HasPendingRestart)
  126. {
  127. return;
  128. }
  129. var type = NotificationType.ServerRestartRequired.ToString();
  130. var notification = new NotificationRequest
  131. {
  132. NotificationType = type
  133. };
  134. await SendNotification(notification).ConfigureAwait(false);
  135. }
  136. async void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
  137. {
  138. var user = e.Users.FirstOrDefault();
  139. var item = e.MediaInfo;
  140. if (item == null)
  141. {
  142. _logger.Warn("PlaybackStart reported with null media info.");
  143. return;
  144. }
  145. if (e.Item != null && e.Item.Parent == null)
  146. {
  147. // Don't report theme song or local trailer playback
  148. // TODO: This will also cause movie specials to not be reported
  149. return;
  150. }
  151. var notification = new NotificationRequest
  152. {
  153. NotificationType = GetPlaybackNotificationType(item.MediaType),
  154. ExcludeUserIds = e.Users.Select(i => i.Id.ToString("N")).ToList()
  155. };
  156. notification.Variables["ItemName"] = item.Name;
  157. notification.Variables["UserName"] = user == null ? "Unknown user" : user.Name;
  158. notification.Variables["AppName"] = e.ClientName;
  159. notification.Variables["DeviceName"] = e.DeviceName;
  160. await SendNotification(notification).ConfigureAwait(false);
  161. }
  162. private string GetPlaybackNotificationType(string mediaType)
  163. {
  164. if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  165. {
  166. return NotificationType.AudioPlayback.ToString();
  167. }
  168. if (string.Equals(mediaType, MediaType.Game, StringComparison.OrdinalIgnoreCase))
  169. {
  170. return NotificationType.GamePlayback.ToString();
  171. }
  172. if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  173. {
  174. return NotificationType.VideoPlayback.ToString();
  175. }
  176. return null;
  177. }
  178. private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
  179. void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  180. {
  181. if (e.Item.LocationType == LocationType.FileSystem && !e.Item.IsFolder)
  182. {
  183. lock (_libraryChangedSyncLock)
  184. {
  185. if (LibraryUpdateTimer == null)
  186. {
  187. LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, 5000,
  188. Timeout.Infinite);
  189. }
  190. else
  191. {
  192. LibraryUpdateTimer.Change(5000, Timeout.Infinite);
  193. }
  194. _itemsAdded.Add(e.Item);
  195. }
  196. }
  197. }
  198. private async void LibraryUpdateTimerCallback(object state)
  199. {
  200. List<BaseItem> items;
  201. lock (_libraryChangedSyncLock)
  202. {
  203. items = _itemsAdded.ToList();
  204. _itemsAdded.Clear();
  205. DisposeLibraryUpdateTimer();
  206. }
  207. if (items.Count == 1)
  208. {
  209. var item = items.First();
  210. var notification = new NotificationRequest
  211. {
  212. NotificationType = NotificationType.NewLibraryContent.ToString()
  213. };
  214. notification.Variables["Name"] = GetItemName(item);
  215. await SendNotification(notification).ConfigureAwait(false);
  216. }
  217. else
  218. {
  219. var notification = new NotificationRequest
  220. {
  221. NotificationType = NotificationType.NewLibraryContentMultiple.ToString()
  222. };
  223. notification.Variables["ItemCount"] = items.Count.ToString(CultureInfo.InvariantCulture);
  224. await SendNotification(notification).ConfigureAwait(false);
  225. }
  226. }
  227. private string GetItemName(BaseItem item)
  228. {
  229. var name = item.Name;
  230. var hasSeries = item as IHasSeries;
  231. if (hasSeries != null)
  232. {
  233. name = hasSeries.SeriesName + " - " + name;
  234. }
  235. var hasArtist = item as IHasArtist;
  236. if (hasArtist != null)
  237. {
  238. var artists = hasArtist.AllArtists;
  239. if (artists.Count > 0)
  240. {
  241. name = hasArtist.AllArtists[0] + " - " + name;
  242. }
  243. }
  244. return name;
  245. }
  246. async void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
  247. {
  248. var notification = new NotificationRequest
  249. {
  250. UserIds = new List<string> { e.Argument.Id.ToString("N") },
  251. Name = "Welcome to Media Browser!",
  252. Description = "Check back here for more notifications."
  253. };
  254. await SendNotification(notification).ConfigureAwait(false);
  255. }
  256. async void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
  257. {
  258. var result = e.Result;
  259. if (result.Status == TaskCompletionStatus.Failed)
  260. {
  261. var type = NotificationType.TaskFailed.ToString();
  262. var notification = new NotificationRequest
  263. {
  264. Description = result.ErrorMessage,
  265. Level = NotificationLevel.Error,
  266. NotificationType = type
  267. };
  268. notification.Variables["Name"] = result.Name;
  269. notification.Variables["ErrorMessage"] = result.ErrorMessage;
  270. await SendNotification(notification).ConfigureAwait(false);
  271. }
  272. }
  273. async void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
  274. {
  275. var type = NotificationType.PluginUninstalled.ToString();
  276. var plugin = e.Argument;
  277. var notification = new NotificationRequest
  278. {
  279. NotificationType = type
  280. };
  281. notification.Variables["Name"] = plugin.Name;
  282. notification.Variables["Version"] = plugin.Version.ToString();
  283. await SendNotification(notification).ConfigureAwait(false);
  284. }
  285. async void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
  286. {
  287. var installationInfo = e.InstallationInfo;
  288. var type = NotificationType.InstallationFailed.ToString();
  289. var notification = new NotificationRequest
  290. {
  291. Level = NotificationLevel.Error,
  292. Description = e.Exception.Message,
  293. NotificationType = type
  294. };
  295. notification.Variables["Name"] = installationInfo.Name;
  296. notification.Variables["Version"] = installationInfo.Version;
  297. await SendNotification(notification).ConfigureAwait(false);
  298. }
  299. private async Task SendNotification(NotificationRequest notification)
  300. {
  301. try
  302. {
  303. await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
  304. }
  305. catch (Exception ex)
  306. {
  307. _logger.ErrorException("Error sending notification", ex);
  308. }
  309. }
  310. public void Dispose()
  311. {
  312. DisposeLibraryUpdateTimer();
  313. _installationManager.PluginInstalled -= _installationManager_PluginInstalled;
  314. _installationManager.PluginUpdated -= _installationManager_PluginUpdated;
  315. _installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
  316. _installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
  317. _taskManager.TaskCompleted -= _taskManager_TaskCompleted;
  318. _userManager.UserCreated -= _userManager_UserCreated;
  319. _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
  320. _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
  321. _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged;
  322. _appHost.HasUpdateAvailableChanged -= _appHost_HasUpdateAvailableChanged;
  323. _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
  324. }
  325. private void DisposeLibraryUpdateTimer()
  326. {
  327. if (LibraryUpdateTimer != null)
  328. {
  329. LibraryUpdateTimer.Dispose();
  330. LibraryUpdateTimer = null;
  331. }
  332. }
  333. }
  334. }