Notifications.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. if (e.Item != null && e.Item.Parent == null)
  159. {
  160. // Don't report theme song or local trailer playback
  161. // TODO: This will also cause movie specials to not be reported
  162. return;
  163. }
  164. var notification = new NotificationRequest
  165. {
  166. NotificationType = type,
  167. ExcludeUserIds = e.Users.Select(i => i.Id.ToString("N")).ToList()
  168. };
  169. notification.Variables["ItemName"] = item.Name;
  170. notification.Variables["UserName"] = user == null ? "Unknown user" : user.Name;
  171. notification.Variables["AppName"] = e.ClientName;
  172. notification.Variables["DeviceName"] = e.DeviceName;
  173. await SendNotification(notification).ConfigureAwait(false);
  174. }
  175. private string GetPlaybackNotificationType(string mediaType)
  176. {
  177. if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  178. {
  179. return NotificationType.AudioPlayback.ToString();
  180. }
  181. if (string.Equals(mediaType, MediaType.Game, StringComparison.OrdinalIgnoreCase))
  182. {
  183. return NotificationType.GamePlayback.ToString();
  184. }
  185. if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  186. {
  187. return NotificationType.VideoPlayback.ToString();
  188. }
  189. return null;
  190. }
  191. private string GetPlaybackStoppedNotificationType(string mediaType)
  192. {
  193. if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  194. {
  195. return NotificationType.AudioPlaybackStopped.ToString();
  196. }
  197. if (string.Equals(mediaType, MediaType.Game, StringComparison.OrdinalIgnoreCase))
  198. {
  199. return NotificationType.GamePlaybackStopped.ToString();
  200. }
  201. if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  202. {
  203. return NotificationType.VideoPlaybackStopped.ToString();
  204. }
  205. return null;
  206. }
  207. private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
  208. void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  209. {
  210. if (e.Item.LocationType == LocationType.FileSystem && !e.Item.IsFolder)
  211. {
  212. lock (_libraryChangedSyncLock)
  213. {
  214. if (LibraryUpdateTimer == null)
  215. {
  216. LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, 5000,
  217. Timeout.Infinite);
  218. }
  219. else
  220. {
  221. LibraryUpdateTimer.Change(5000, Timeout.Infinite);
  222. }
  223. _itemsAdded.Add(e.Item);
  224. }
  225. }
  226. }
  227. private async void LibraryUpdateTimerCallback(object state)
  228. {
  229. List<BaseItem> items;
  230. lock (_libraryChangedSyncLock)
  231. {
  232. items = _itemsAdded.ToList();
  233. _itemsAdded.Clear();
  234. DisposeLibraryUpdateTimer();
  235. }
  236. if (items.Count == 1)
  237. {
  238. var item = items.First();
  239. var notification = new NotificationRequest
  240. {
  241. NotificationType = NotificationType.NewLibraryContent.ToString()
  242. };
  243. notification.Variables["Name"] = GetItemName(item);
  244. await SendNotification(notification).ConfigureAwait(false);
  245. }
  246. else
  247. {
  248. var notification = new NotificationRequest
  249. {
  250. NotificationType = NotificationType.NewLibraryContentMultiple.ToString()
  251. };
  252. notification.Variables["ItemCount"] = items.Count.ToString(CultureInfo.InvariantCulture);
  253. await SendNotification(notification).ConfigureAwait(false);
  254. }
  255. }
  256. public static string GetItemName(BaseItem item)
  257. {
  258. var name = item.Name;
  259. var hasSeries = item as IHasSeries;
  260. if (hasSeries != null)
  261. {
  262. name = hasSeries.SeriesName + " - " + name;
  263. }
  264. var hasArtist = item as IHasArtist;
  265. if (hasArtist != null)
  266. {
  267. var artists = hasArtist.AllArtists;
  268. if (artists.Count > 0)
  269. {
  270. name = hasArtist.AllArtists[0] + " - " + name;
  271. }
  272. }
  273. return name;
  274. }
  275. async void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
  276. {
  277. var notification = new NotificationRequest
  278. {
  279. UserIds = new List<string> { e.Argument.Id.ToString("N") },
  280. Name = "Welcome to Media Browser!",
  281. Description = "Check back here for more notifications."
  282. };
  283. await SendNotification(notification).ConfigureAwait(false);
  284. }
  285. async void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
  286. {
  287. var result = e.Result;
  288. if (result.Status == TaskCompletionStatus.Failed)
  289. {
  290. var type = NotificationType.TaskFailed.ToString();
  291. var notification = new NotificationRequest
  292. {
  293. Description = result.ErrorMessage,
  294. Level = NotificationLevel.Error,
  295. NotificationType = type
  296. };
  297. notification.Variables["Name"] = result.Name;
  298. notification.Variables["ErrorMessage"] = result.ErrorMessage;
  299. await SendNotification(notification).ConfigureAwait(false);
  300. }
  301. }
  302. async void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
  303. {
  304. var type = NotificationType.PluginUninstalled.ToString();
  305. var plugin = e.Argument;
  306. var notification = new NotificationRequest
  307. {
  308. NotificationType = type
  309. };
  310. notification.Variables["Name"] = plugin.Name;
  311. notification.Variables["Version"] = plugin.Version.ToString();
  312. await SendNotification(notification).ConfigureAwait(false);
  313. }
  314. async void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
  315. {
  316. var installationInfo = e.InstallationInfo;
  317. var type = NotificationType.InstallationFailed.ToString();
  318. var notification = new NotificationRequest
  319. {
  320. Level = NotificationLevel.Error,
  321. Description = e.Exception.Message,
  322. NotificationType = type
  323. };
  324. notification.Variables["Name"] = installationInfo.Name;
  325. notification.Variables["Version"] = installationInfo.Version;
  326. await SendNotification(notification).ConfigureAwait(false);
  327. }
  328. private async Task SendNotification(NotificationRequest notification)
  329. {
  330. try
  331. {
  332. await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
  333. }
  334. catch (Exception ex)
  335. {
  336. _logger.ErrorException("Error sending notification", ex);
  337. }
  338. }
  339. public void Dispose()
  340. {
  341. DisposeLibraryUpdateTimer();
  342. _installationManager.PluginInstalled -= _installationManager_PluginInstalled;
  343. _installationManager.PluginUpdated -= _installationManager_PluginUpdated;
  344. _installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
  345. _installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
  346. _taskManager.TaskCompleted -= _taskManager_TaskCompleted;
  347. _userManager.UserCreated -= _userManager_UserCreated;
  348. _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
  349. _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
  350. _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged;
  351. _appHost.HasUpdateAvailableChanged -= _appHost_HasUpdateAvailableChanged;
  352. _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
  353. }
  354. private void DisposeLibraryUpdateTimer()
  355. {
  356. if (LibraryUpdateTimer != null)
  357. {
  358. LibraryUpdateTimer.Dispose();
  359. LibraryUpdateTimer = null;
  360. }
  361. }
  362. }
  363. }