Notifications.cs 18 KB

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