Notifications.cs 18 KB

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