Notifications.cs 14 KB

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