Notifications.cs 19 KB

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