Notifications.cs 17 KB

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