Notifications.cs 16 KB

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