Notifications.cs 19 KB

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