Notifications.cs 18 KB

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