Notifications.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Plugins;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Common.Updates;
  5. using MediaBrowser.Controller;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Audio;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Notifications;
  10. using MediaBrowser.Controller.Plugins;
  11. using MediaBrowser.Controller.Session;
  12. using MediaBrowser.Model.Entities;
  13. using MediaBrowser.Model.Events;
  14. using MediaBrowser.Model.Logging;
  15. using MediaBrowser.Model.Notifications;
  16. using MediaBrowser.Model.Tasks;
  17. using MediaBrowser.Model.Updates;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Globalization;
  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 ILibraryManager _libraryManager;
  37. private readonly ISessionManager _sessionManager;
  38. private readonly IServerApplicationHost _appHost;
  39. private Timer LibraryUpdateTimer { get; set; }
  40. private readonly object _libraryChangedSyncLock = new object();
  41. private readonly IConfigurationManager _config;
  42. public Notifications(IInstallationManager installationManager, IUserManager userManager, ILogger logger, ITaskManager taskManager, INotificationManager notificationManager, ILibraryManager libraryManager, ISessionManager sessionManager, IServerApplicationHost appHost, IConfigurationManager config)
  43. {
  44. _installationManager = installationManager;
  45. _userManager = userManager;
  46. _logger = logger;
  47. _taskManager = taskManager;
  48. _notificationManager = notificationManager;
  49. _libraryManager = libraryManager;
  50. _sessionManager = sessionManager;
  51. _appHost = appHost;
  52. _config = config;
  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. _sessionManager.PlaybackStopped += _sessionManager_PlaybackStopped;
  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 = e.Argument.Item2.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. private NotificationOptions GetOptions()
  136. {
  137. return _config.GetConfiguration<NotificationOptions>("notifications");
  138. }
  139. void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
  140. {
  141. var item = e.MediaInfo;
  142. if (item == null)
  143. {
  144. _logger.Warn("PlaybackStart reported with null media info.");
  145. return;
  146. }
  147. var type = GetPlaybackNotificationType(item.MediaType);
  148. SendPlaybackNotification(type, e);
  149. }
  150. void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
  151. {
  152. var item = e.MediaInfo;
  153. if (item == null)
  154. {
  155. _logger.Warn("PlaybackStopped reported with null media info.");
  156. return;
  157. }
  158. var type = GetPlaybackStoppedNotificationType(item.MediaType);
  159. SendPlaybackNotification(type, e);
  160. }
  161. private async void SendPlaybackNotification(string type, PlaybackProgressEventArgs e)
  162. {
  163. var user = e.Users.FirstOrDefault();
  164. if (user != null && !GetOptions().IsEnabledToMonitorUser(type, user.Id.ToString("N")))
  165. {
  166. return;
  167. }
  168. var item = e.MediaInfo;
  169. var themeMedia = item as IThemeMedia;
  170. if (themeMedia != null && themeMedia.IsThemeMedia)
  171. {
  172. // Don't report theme song or local trailer playback
  173. return;
  174. }
  175. var notification = new NotificationRequest
  176. {
  177. NotificationType = type
  178. };
  179. notification.Variables["ItemName"] = item.Name;
  180. notification.Variables["UserName"] = user == null ? "Unknown user" : user.Name;
  181. notification.Variables["AppName"] = e.ClientName;
  182. notification.Variables["DeviceName"] = e.DeviceName;
  183. await SendNotification(notification).ConfigureAwait(false);
  184. }
  185. private string GetPlaybackNotificationType(string mediaType)
  186. {
  187. if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  188. {
  189. return NotificationType.AudioPlayback.ToString();
  190. }
  191. if (string.Equals(mediaType, MediaType.Game, StringComparison.OrdinalIgnoreCase))
  192. {
  193. return NotificationType.GamePlayback.ToString();
  194. }
  195. if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  196. {
  197. return NotificationType.VideoPlayback.ToString();
  198. }
  199. return null;
  200. }
  201. private string GetPlaybackStoppedNotificationType(string mediaType)
  202. {
  203. if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  204. {
  205. return NotificationType.AudioPlaybackStopped.ToString();
  206. }
  207. if (string.Equals(mediaType, MediaType.Game, StringComparison.OrdinalIgnoreCase))
  208. {
  209. return NotificationType.GamePlaybackStopped.ToString();
  210. }
  211. if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  212. {
  213. return NotificationType.VideoPlaybackStopped.ToString();
  214. }
  215. return null;
  216. }
  217. private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
  218. void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  219. {
  220. if (e.Item.LocationType == LocationType.FileSystem && !e.Item.IsFolder)
  221. {
  222. lock (_libraryChangedSyncLock)
  223. {
  224. if (LibraryUpdateTimer == null)
  225. {
  226. LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, 5000,
  227. Timeout.Infinite);
  228. }
  229. else
  230. {
  231. LibraryUpdateTimer.Change(5000, Timeout.Infinite);
  232. }
  233. _itemsAdded.Add(e.Item);
  234. }
  235. }
  236. }
  237. private async void LibraryUpdateTimerCallback(object state)
  238. {
  239. List<BaseItem> items;
  240. lock (_libraryChangedSyncLock)
  241. {
  242. items = _itemsAdded.ToList();
  243. _itemsAdded.Clear();
  244. DisposeLibraryUpdateTimer();
  245. }
  246. if (items.Count == 1)
  247. {
  248. var item = items.First();
  249. var notification = new NotificationRequest
  250. {
  251. NotificationType = NotificationType.NewLibraryContent.ToString()
  252. };
  253. notification.Variables["Name"] = GetItemName(item);
  254. await SendNotification(notification).ConfigureAwait(false);
  255. }
  256. else
  257. {
  258. var notification = new NotificationRequest
  259. {
  260. NotificationType = NotificationType.NewLibraryContentMultiple.ToString()
  261. };
  262. notification.Variables["ItemCount"] = items.Count.ToString(CultureInfo.InvariantCulture);
  263. await SendNotification(notification).ConfigureAwait(false);
  264. }
  265. }
  266. public static string GetItemName(BaseItem item)
  267. {
  268. var name = item.Name;
  269. var hasSeries = item as IHasSeries;
  270. if (hasSeries != null)
  271. {
  272. name = hasSeries.SeriesName + " - " + name;
  273. }
  274. var hasArtist = item as IHasArtist;
  275. if (hasArtist != null)
  276. {
  277. var artists = hasArtist.AllArtists;
  278. if (artists.Count > 0)
  279. {
  280. name = hasArtist.AllArtists[0] + " - " + name;
  281. }
  282. }
  283. return name;
  284. }
  285. async void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
  286. {
  287. var notification = new NotificationRequest
  288. {
  289. UserIds = new List<string> { e.Argument.Id.ToString("N") },
  290. Name = "Welcome to Media Browser!",
  291. Description = "Check back here for more notifications."
  292. };
  293. await SendNotification(notification).ConfigureAwait(false);
  294. }
  295. async void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
  296. {
  297. var result = e.Result;
  298. if (result.Status == TaskCompletionStatus.Failed)
  299. {
  300. var type = NotificationType.TaskFailed.ToString();
  301. var notification = new NotificationRequest
  302. {
  303. Description = result.ErrorMessage,
  304. Level = NotificationLevel.Error,
  305. NotificationType = type
  306. };
  307. notification.Variables["Name"] = result.Name;
  308. notification.Variables["ErrorMessage"] = result.ErrorMessage;
  309. await SendNotification(notification).ConfigureAwait(false);
  310. }
  311. }
  312. async void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
  313. {
  314. var type = NotificationType.PluginUninstalled.ToString();
  315. var plugin = e.Argument;
  316. var notification = new NotificationRequest
  317. {
  318. NotificationType = type
  319. };
  320. notification.Variables["Name"] = plugin.Name;
  321. notification.Variables["Version"] = plugin.Version.ToString();
  322. await SendNotification(notification).ConfigureAwait(false);
  323. }
  324. async void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
  325. {
  326. var installationInfo = e.InstallationInfo;
  327. var type = NotificationType.InstallationFailed.ToString();
  328. var notification = new NotificationRequest
  329. {
  330. Level = NotificationLevel.Error,
  331. Description = e.Exception.Message,
  332. NotificationType = type
  333. };
  334. notification.Variables["Name"] = installationInfo.Name;
  335. notification.Variables["Version"] = installationInfo.Version;
  336. await SendNotification(notification).ConfigureAwait(false);
  337. }
  338. private async Task SendNotification(NotificationRequest notification)
  339. {
  340. try
  341. {
  342. await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
  343. }
  344. catch (Exception ex)
  345. {
  346. _logger.ErrorException("Error sending notification", ex);
  347. }
  348. }
  349. public void Dispose()
  350. {
  351. DisposeLibraryUpdateTimer();
  352. _installationManager.PluginInstalled -= _installationManager_PluginInstalled;
  353. _installationManager.PluginUpdated -= _installationManager_PluginUpdated;
  354. _installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
  355. _installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
  356. _taskManager.TaskCompleted -= _taskManager_TaskCompleted;
  357. _userManager.UserCreated -= _userManager_UserCreated;
  358. _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
  359. _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
  360. _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged;
  361. _appHost.HasUpdateAvailableChanged -= _appHost_HasUpdateAvailableChanged;
  362. _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
  363. }
  364. private void DisposeLibraryUpdateTimer()
  365. {
  366. if (LibraryUpdateTimer != null)
  367. {
  368. LibraryUpdateTimer.Dispose();
  369. LibraryUpdateTimer = null;
  370. }
  371. }
  372. }
  373. }