2
0

Notifications.cs 14 KB

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