Notifications.cs 19 KB

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