Notifications.cs 16 KB

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