Notifications.cs 19 KB

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