Notifier.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using InABox.Core;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. namespace InABox.Core
  7. {
  8. public interface IPollHandler
  9. {
  10. Type Type { get; }
  11. /// <summary>
  12. /// Polls for notifications, called on client connection.
  13. /// </summary>
  14. /// <returns>New notifications</returns>
  15. IEnumerable<object> Poll(Guid session);
  16. }
  17. public class PollHandler<TNotification> : IPollHandler
  18. {
  19. public delegate IEnumerable<TNotification> PollEvent(Guid session);
  20. public event PollEvent? OnPoll;
  21. public Type Type => typeof(TNotification);
  22. public PollHandler() { }
  23. public PollHandler(PollEvent poll)
  24. {
  25. OnPoll += poll;
  26. }
  27. public IEnumerable<object> Poll(Guid session) => (OnPoll?.Invoke(session) ?? Array.Empty<TNotification>()).Cast<object>();
  28. }
  29. public abstract class Notifier
  30. {
  31. private List<IPollHandler> Handlers = new List<IPollHandler>();
  32. protected abstract void NotifyAll<TNotification>(TNotification notification);
  33. protected abstract void NotifySession<TNotification>(Guid session, TNotification notification);
  34. protected abstract void NotifySession(Guid session, Type TNotification, object? notification);
  35. protected abstract IEnumerable<Guid> GetUserSessions(Guid user);
  36. protected abstract IEnumerable<Guid> GetSessions(Platform platform);
  37. public void Push<TNotification>(TNotification notification)
  38. {
  39. NotifyAll(notification);
  40. }
  41. public void Push<TNotification>(Guid session, TNotification notification)
  42. {
  43. NotifySession(session, notification);
  44. }
  45. public void PushUser<TNotification>(Guid user, TNotification notification)
  46. {
  47. foreach (var session in GetUserSessions(user))
  48. {
  49. NotifySession(session, notification);
  50. }
  51. }
  52. public void Push<TNotification>(Platform platform, TNotification notification)
  53. {
  54. foreach (var session in GetSessions(platform))
  55. {
  56. NotifySession(session, notification);
  57. }
  58. }
  59. public void Poll(Guid session)
  60. {
  61. foreach (var handler in Handlers)
  62. {
  63. foreach (var notification in handler.Poll(session))
  64. {
  65. NotifySession(session, handler.Type, notification);
  66. }
  67. }
  68. }
  69. public void AddPollHandler<TNotification>(PollHandler<TNotification> handler)
  70. {
  71. Handlers.Add(handler);
  72. }
  73. public void AddPollHandler<TNotification>(PollHandler<TNotification>.PollEvent poll)
  74. {
  75. Handlers.Add(new PollHandler<TNotification>(poll));
  76. }
  77. }
  78. }